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
ziligy/JGSettingsManager
JGSettingsManager/SegmentedControlTableCell.swift
1
3613
// // SegmentedControlTableCell.swift // JGSettingsManager // // Created by Jeff on 12/22/15. // Copyright © 2015 Jeff Greenberg. All rights reserved. // import UIKit public class SegmentedControlTableCell: UITableViewCell { // MARK: Data private var dataInt: JGUserDefault<Int>! private var dataString: JGUserDefault<String>! // MARK: UI private let segmentedControl = UISegmentedControl() // MARK: Init public convenience init (index: JGUserDefault<Int>, segments: [String]) { self.init() dataInt = index setupViews() initializeUIforInt(segments) } public convenience init (stringValue: JGUserDefault<String>, segments: [String]) { self.init() dataString = stringValue setupViews() initializeUIforString(segments) } private func setupViews() { addSubview(segmentedControl) segmentedControl.setFontSize(20) segmentedControl.translatesAutoresizingMaskIntoConstraints = false segmentedControl.addTarget(self, action: Selector("save:"), forControlEvents: .ValueChanged) } private func initializeUIforInt(segments: [String]) { for (index, segment) in segments.enumerate() { segmentedControl.insertSegmentWithTitle(segment, atIndex: index, animated: false) } segmentedControl.selectedSegmentIndex = dataInt.value() } private func initializeUIforString(segments: [String]) { var selectedSegmentIndex = 0 let stringValue = dataString.value() for (index, segment) in segments.enumerate() { if segment == stringValue { selectedSegmentIndex = index } segmentedControl.insertSegmentWithTitle(segment, atIndex: index, animated: false) } // set the default to zero to avoid error // it is initiailied to -1 by iOS segmentedControl.selectedSegmentIndex = selectedSegmentIndex } // MARK: Save public func save(sender: UISegmentedControl) { if dataString == nil { dataInt.save(sender.selectedSegmentIndex) } else { dataString.save(sender.titleForSegmentAtIndex(sender.selectedSegmentIndex)!) } } // MARK: Constraints override public func layoutSubviews() { updateConstraints() } override public func updateConstraints() { segmentedControl.centerYAnchor.constraintEqualToAnchor(centerYAnchor, constant: 0).active = true segmentedControl.centerXAnchor.constraintEqualToAnchor(centerXAnchor, constant: 0).active = true super.updateConstraints() } } extension UISegmentedControl { func setFontSize(fontSize: CGFloat) { let normalTextAttributes: [NSObject : AnyObject] = [ NSForegroundColorAttributeName: UIColor.blackColor(), NSFontAttributeName: UIFont.systemFontOfSize(fontSize, weight: UIFontWeightRegular) ] let boldTextAttributes: [NSObject : AnyObject] = [ NSForegroundColorAttributeName : UIColor.whiteColor(), NSFontAttributeName : UIFont.systemFontOfSize(fontSize, weight: UIFontWeightMedium) ] self.setTitleTextAttributes(normalTextAttributes, forState: .Normal) self.setTitleTextAttributes(normalTextAttributes, forState: .Highlighted) self.setTitleTextAttributes(boldTextAttributes, forState: .Selected) } }
mit
d8f8fd3acf9c4288352719274bf16cb4
29.1
104
0.648394
5.769968
false
false
false
false
seuzl/iHerald
Herald/Config.swift
1
3594
// // Config.swift // 先声 // // Created by Wangshuo on 14-8-4. // Copyright (c) 2015年 WangShuo,Li Zhuoli. All rights reserved. // import Foundation class Config:NSObject { static let sharedInstance = Config() static let settings : NSUserDefaults = NSUserDefaults.standardUserDefaults() var isNetworkRunning : Bool = false static var UUID:String? { let temp = settings.objectForKey("UUID") as? String return AESCrypt.decrypt(temp, password: "UUID") } static var studentID:String? { return settings.objectForKey("studentID") as? String } static var cardID:String? { return settings.objectForKey("cardID") as? String } static var cardPassword:String? { let temp = settings.objectForKey("cardPassword") as? String return AESCrypt.decrypt(temp, password: "cardPassword") } static var curriculum:NSDictionary? { return settings.objectForKey("curriculum") as? NSDictionary } static var GPA:NSArray? { return settings.objectForKey("GPA") as? NSArray } static var token:String? { return settings.objectForKey("token") as? String } static func saveUUID(var UUID:NSString) { settings.removeObjectForKey("UUID") UUID = AESCrypt.encrypt(UUID as String, password: "UUID") settings.setObject(UUID, forKey: "UUID") settings.synchronize() } static func saveStudentID(studentID:NSString) { settings.removeObjectForKey("studentID") settings.setObject(studentID, forKey: "studentID") settings.synchronize() } static func saveCardID(cardID:NSString) { settings.removeObjectForKey("cardID") settings.setObject(cardID, forKey: "cardID") settings.synchronize() } static func saveCardPassword(cardPassword:NSString) { settings.removeObjectForKey("cardPassword") let encodePassword = AESCrypt.encrypt(cardPassword as String, password: "cardPassword") settings.setObject(encodePassword, forKey: "cardPassword") settings.synchronize() } static func saveCurriculum(Curriculum:NSDictionary) { settings.removeObjectForKey("curriculum") settings.setObject(Curriculum, forKey: "curriculum") settings.synchronize() } static func saveGPA(GPA:NSArray) { settings.removeObjectForKey("GPA") settings.setObject(GPA, forKey: "GPA") settings.synchronize() } static func saveToken(token:String) { settings.removeObjectForKey("token") settings.setObject(token, forKey: "token") settings.synchronize() } static func removeUUID() { settings.removeObjectForKey("UUID") settings.synchronize() } static func removeStudentID() { settings.removeObjectForKey("studentID") settings.synchronize() } static func removeCardID() { settings.removeObjectForKey("cardID") settings.synchronize() } static func removeCardPassword() { settings.removeObjectForKey("cardPassword") settings.synchronize() } static func removeCurriculum() { settings.removeObjectForKey("curriculum") settings.synchronize() } static func removeGPA() { settings.removeObjectForKey("GPA") settings.synchronize() } static func removeToken() { settings.removeObjectForKey("token") settings.synchronize() } }
mit
f6b578fc089b096cdc4db9165dd298a1
27.039063
95
0.641304
4.696335
false
false
false
false
335g/Bass
Bass/Types/Cont.swift
1
2564
// Copyright © 2016 Yoshiki Kudo. All rights reserved. // MARK: - ContType public protocol ContType: Pointed { associatedtype IRC // Intermediate Result of ContType associatedtype FRC // Final Result of ContType var run: (IRC -> FRC) -> FRC { get } init(_ run: (IRC -> FRC) -> FRC) } // MARK: - ContType: Pointed public extension ContType { public static func pure(a: IRC) -> Self { return Self.init{ f in f(a) } } } // MARK: - ContType - method public extension ContType where IRC == FRC { /// The result of running a CPS computation with the identity as the final continuation. public var eval: FRC { return run { $0 } } } public extension ContType { /// Apply a function to transform the continuation passed to a CPS computation. public func with<I>(f: (I -> FRC) -> (IRC -> FRC)) -> Cont<FRC, I> { return Cont { self.run(f($0)) } } } // MARK: - ContType - map/flatMap/ap public extension ContType { public func map(f: FRC -> FRC) -> Cont<FRC, IRC> { return Cont(f • self.run) } public func map<I>(f: IRC -> I) -> Cont<FRC, I> { return Cont { self.run($0 • f) } } public func flatMap<I>(fn: IRC -> Cont<FRC, I>) -> Cont<FRC, I> { return Cont { c in self.run{ fn($0).run(c) } } } public func ap<I, CT: ContType where CT.IRC == IRC -> I, CT.FRC == FRC>(fn: CT) -> Cont<FRC, I> { return Cont { c in fn.run{ g in self.run(c • g) } } } } /// Alias for `map(f:)` public func <^> <I, F, CT: ContType where CT.IRC == I, CT.FRC == F>(f: F -> F, g: CT) -> Cont<F, I> { return g.map(f) } /// Alias for `map(f:)` public func <^> <I, I2, F, CT: ContType where CT.IRC == I, CT.FRC == F>(f: I -> I2, g: CT) -> Cont<F, I2> { return g.map(f) } /// Alias for `flatMap(g:)` public func >>- <I, I2, F, CT: ContType where CT.IRC == I, CT.FRC == F>(m: CT, fn: I -> Cont<F, I2>) -> Cont<F, I2> { return m.flatMap(fn) } /// Alias for `ap(fn:)` public func <*> <I, I2, F, CT1: ContType, CT2: ContType where CT1.IRC == I -> I2, CT1.FRC == F, CT2.IRC == I, CT2.FRC == F>(fn: CT1, m: CT2) -> Cont<F, I2> { return m.ap(fn) } // MARK: - Cont public struct Cont<F, I> { public let run: (I -> F) -> F } // MARK: - Cont: ContType extension Cont: ContType { public typealias IRC = I public typealias FRC = F public init(_ run: (I -> F) -> F) { self.run = run } } // MARK: - Cont: Pointed extension Cont { public typealias PointedValue = I } // MARK: - Functions public func callCC<F, I1, I2>(f: (I1 -> Cont<F, I2>) -> Cont<F, I1>) -> Cont<F, I1> { return Cont { c in f{ x in Cont{ _ in c(x) } }.run(c) } }
mit
e276649086c049baad6c52f9e732824e
23.122642
157
0.590145
2.572435
false
false
false
false
nanthi1990/SwiftCharts
Examples/Examples/ExamplesDefaults.swift
5
2383
// // ExamplesDefaults.swift // SwiftCharts // // Created by ischuetz on 04/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit import SwiftCharts struct ExamplesDefaults { static var chartSettings: ChartSettings { if Env.iPad { return self.iPadChartSettings } else { return self.iPhoneChartSettings } } private static var iPadChartSettings: ChartSettings { let chartSettings = ChartSettings() chartSettings.leading = 20 chartSettings.top = 20 chartSettings.trailing = 20 chartSettings.bottom = 20 chartSettings.labelsToAxisSpacingX = 10 chartSettings.labelsToAxisSpacingY = 10 chartSettings.axisTitleLabelsToLabelsSpacing = 5 chartSettings.axisStrokeWidth = 1 chartSettings.spacingBetweenAxesX = 15 chartSettings.spacingBetweenAxesY = 15 return chartSettings } private static var iPhoneChartSettings: ChartSettings { let chartSettings = ChartSettings() chartSettings.leading = 10 chartSettings.top = 10 chartSettings.trailing = 10 chartSettings.bottom = 10 chartSettings.labelsToAxisSpacingX = 5 chartSettings.labelsToAxisSpacingY = 5 chartSettings.axisTitleLabelsToLabelsSpacing = 4 chartSettings.axisStrokeWidth = 0.2 chartSettings.spacingBetweenAxesX = 8 chartSettings.spacingBetweenAxesY = 8 return chartSettings } static func chartFrame(containerBounds: CGRect) -> CGRect { return CGRectMake(0, 70, containerBounds.size.width, containerBounds.size.height - 70) } static var labelSettings: ChartLabelSettings { return ChartLabelSettings(font: ExamplesDefaults.labelFont) } static var labelFont: UIFont { return ExamplesDefaults.fontWithSize(Env.iPad ? 14 : 11) } static var labelFontSmall: UIFont { return ExamplesDefaults.fontWithSize(Env.iPad ? 12 : 10) } static func fontWithSize(size: CGFloat) -> UIFont { return UIFont(name: "Helvetica", size: size) ?? UIFont.systemFontOfSize(size) } static var guidelinesWidth: CGFloat { return Env.iPad ? 0.5 : 0.1 } static var minBarSpacing: CGFloat { return Env.iPad ? 10 : 5 } }
apache-2.0
47342a68dd73923b4753f4f917298649
29.164557
94
0.660512
5.516204
false
false
false
false
fanxiangyang/FanRefresh
Classes/FanRefreshHeaderBubble.swift
1
10567
// // FanRefreshHeaderBubble.swift // FanRefresh // // Created by 向阳凡 on 2017/6/5. // Copyright © 2017年 凡向阳. All rights reserved. // /// 该类处于测试阶段,不能使用,有bug import UIKit public class FanRefreshHeaderBubble: FanRefreshHeader { /// 存放状态标题字典 public var fan_stateTitles:Dictionary<FanRefreshState, String> = Dictionary<FanRefreshState, String>() /// 状态Label public lazy var fan_stateLabel:UILabel = { let titleLabel = UILabel.fan_label() self.addSubview(titleLabel) return titleLabel }() /// 菊花样式 public var fan_activityIndicatorViewStyle:UIActivityIndicatorView.Style = .gray // { // //这里应该不需要重新刷新 // didSet{ // self.setNeedsLayout() // } // } public lazy var fan_loadingView:UIActivityIndicatorView? = { let loadingView = UIActivityIndicatorView(style: self.fan_activityIndicatorViewStyle) self.addSubview(loadingView) return loadingView }() ///是否隐藏状态内容 public var fan_stateTitleHidden:Bool = true //文字距离圆圈和箭头的距离 public var fan_labelInsetLeft:CGFloat = FanRefreshLabelInsetLeft public var fillColor:UIColor = UIColor.darkGray public var dragHeight:CGFloat = 90 public var bubbleRadius:CGFloat = (FanRefreshHeaderHeight-20)/2.0; public var bubbleCenter:CGPoint{ return CGPoint(x: self.frame.size.width/2.0, y: FanRefreshHeaderHeight/2.0) } /// 开始的距离,偏移量-圆直径 public var startY:CGFloat = 0.0 public var selfFrame:CGRect?; //MARK: - 外部类调用方法 /// 设置title状态 public func fan_setTitle(title:String?,state:FanRefreshState) { if title == nil { return } self.fan_stateTitles[state]=title self.fan_stateLabel.text=self.fan_stateTitles[self.state] } //MARK: - 重写父类方法 public override func fan_prepare() { super.fan_prepare() //初始化UI,放在最前面(已经用懒加载) //初始化状态文字(已经国际化) self.fan_setTitle(title: Bundle.fan_localizedString(key: FanRefreshHeaderDefaultText), state: .Default) self.fan_setTitle(title: Bundle.fan_localizedString(key: FanRefreshHeaderPullingText), state: .Pulling) self.fan_setTitle(title: Bundle.fan_localizedString(key: FanRefreshHeaderRefreshingText), state: .Refreshing) self.fan_stateLabel.isHidden=true } override public func fan_placeSubviews() { super.fan_placeSubviews() let noConstrainsOnStatusLabel = (self.fan_stateLabel.constraints.count == 0) //MARK: 菊花 var loadingCenterX = self.fan_width * 0.5 //圆圈 if self.fan_loadingView?.constraints.count == 0 { if !self.fan_stateTitleHidden { loadingCenterX -= self.fan_stateLabel.fan_textWidth(height: self.fan_stateLabel.fan_height) * 0.5 + self.fan_labelInsetLeft if noConstrainsOnStatusLabel { // self.fan_stateLabel.frame = self.bounds self.fan_stateLabel.fan_x=0.0 self.fan_stateLabel.fan_y=0 self.fan_stateLabel.fan_width = self.fan_width self.fan_stateLabel.fan_height = self.fan_height } } let loadingCenterY = self.fan_height * 0.5 self.fan_loadingView?.center = CGPoint(x: loadingCenterX, y: loadingCenterY) } } override public func fan_changeState(oldState: FanRefreshState) { self.fan_stateLabel.isHidden=true //每次继承都要判断,防止多次调用执行代码 if self.state == oldState { return } super.fan_changeState(oldState: oldState) //设置状态文字 //重新显示时间,重新设置Key self.fan_lastUpdatedTimeKey = self.fan_lastUpdatedTimeKey self.fan_stateLabel.text=self.fan_stateTitles[state] //MARK: 箭头和菊花状态变化 if self.state == .Default { if oldState == .Refreshing { if self.state != .Default { return } self.alpha=1.0 self.fan_loadingView?.stopAnimating() }else{ self.fan_loadingView?.stopAnimating() } }else if self.state == .Pulling { self.fan_loadingView?.stopAnimating() }else if self.state == .Refreshing { self.fan_loadingView?.alpha=1.0 self.fan_loadingView?.startAnimating() self.fan_stateLabel.isHidden=self.fan_stateTitleHidden } } override public func fan_scrollViewContentOffsetDidChange(change: [NSKeyValueChangeKey : Any]) { // super.fan_scrollViewContentOffsetDidChange(change: change) // print(change[.newKey]) if self.state == .Refreshing{ if self.window == nil { return } // sectionheader停留状态 var insetT = -((self.superScrollView)?.fan_offsetY)! > ((self.scrollViewOriginalInset)?.top)! ? -((self.superScrollView)?.fan_offsetY)! : (self.scrollViewOriginalInset?.top)! // print("tttttt",insetT,self.scrollViewOriginalInset?.top) self.superScrollView?.fan_insetTop=60 if insetT > 60 + (self.scrollViewOriginalInset?.top)! { insetT = 60 + (self.scrollViewOriginalInset?.top)! // self.superScrollView?.fan_insetTop = 60 // self.fan_height = 60 // self.fan_y = -60 } self.fan_height = 60 self.fan_y = -insetT//-60 self.superScrollView?.fan_insetTop=insetT // self.scrollViewOriginalInset=self.superScrollView?.contentInset self.insetTopDefault = (self.scrollViewOriginalInset?.top)! - insetT print("111111111") self.scrollViewOriginalInset=self.superScrollView?.contentInset return; } //防止 self.scrollViewOriginalInset=self.superScrollView?.contentInset let offsetY = (self.superScrollView?.fan_offsetY)! let happenOffsetY = -(self.scrollViewOriginalInset?.top)! //如果是向上滑动看不到头控件,直接返回 if offsetY > happenOffsetY { return } //普通和即将刷新的临界点 let normalPullingOffsetY=happenOffsetY-self.dragHeight let pullingPercent = (happenOffsetY-offsetY)/self.dragHeight if (self.superScrollView?.isDragging)! { self.fan_pullingPercent=pullingPercent if self.state == .Default && offsetY < normalPullingOffsetY { //将要刷新状态,拖拽超过控件高度 self.state = .Pulling // print("2222222") }else if self.state == .Pulling && offsetY >= normalPullingOffsetY { //转为普通默认状态,拖拽超过又小于控件高度 self.state = .Default // print("33333333") } }else if self.state == .Pulling { //即将刷新或手松开开始刷新 // print("44444444") self.fan_beginRefreshing() }else if pullingPercent < 1 { self.fan_pullingPercent=pullingPercent // print("555555555") } // print("yyyyyyyyyyyyyy",self.superScrollView?.fan_insetTop,self.scrollViewOriginalInset?.top) let newPoint:CGPoint = change[.newKey] as! CGPoint var frame = self.frame frame.origin.y = newPoint.y+(self.superScrollView?.fan_insetTop)! frame.size.height = fmax(0, -newPoint.y-(self.superScrollView?.fan_insetTop)!) self.startY = fmax(0, -newPoint.y-(self.superScrollView?.fan_insetTop)!-FanRefreshHeaderHeight) self.frame = frame // print("=======",frame.origin.x,frame.origin.y,frame.size.width,frame.size.height) self.setNeedsDisplay() } // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override public func draw(_ rect: CGRect) { // 预防view还没显示出来就调用了fan_beginRefreshing // if self.state == .WillRefresh { // self.state = .Refreshing // } if self.state == .Refreshing { return } // Drawing code // print(rect) let rad1 = self.bubbleRadius-self.startY*0.1 let rad2 = self.bubbleRadius-self.startY*0.2 let Y:CGFloat = CGFloat(fmaxf(Float(self.startY), 0.0)) var rad3:CGFloat = 0.0 if rad1-rad2 > 0 { rad3 = (pow(Y, 2)+pow(rad2, 2)-pow(rad1, 2))/(2*(rad1-rad2)) } rad3 = fmax(0, rad3); // print(self.bubbleCenter) let center2 = CGPoint(x: self.bubbleCenter.x, y: self.bubbleCenter.y+Y) let center3 = CGPoint(x: center2.x+rad2+rad3, y: center2.y) let center4 = CGPoint(x: center2.x-rad2-rad3, y: center2.y) let circle = UIBezierPath(arcCenter: self.bubbleCenter, radius: rad1, startAngle: 0, endAngle: CGFloat(2*Double.pi), clockwise: true) circle.move(to: center2) circle.addArc(withCenter: center2, radius: rad2, startAngle: 0, endAngle: CGFloat(2*Double.pi), clockwise: true) let circle2 = UIBezierPath(arcCenter: center3, radius: rad3, startAngle: 0, endAngle: CGFloat(2*Double.pi), clockwise: true) circle2.move(to: center4) circle2.addArc(withCenter: center4, radius: rad3, startAngle: 0, endAngle: CGFloat(2*Double.pi), clockwise: true) let bezidrPath = UIBezierPath() bezidrPath.move(to: self.bubbleCenter) bezidrPath.addLine(to: center3) bezidrPath.addLine(to: center2) bezidrPath.addLine(to: center4) bezidrPath.close() bezidrPath.append(circle) self.fillColor.setFill() bezidrPath.fill() self.backgroundColor?.setFill() circle2.fill() } }
mit
9b35aa3387021e2a09a207eefb2e14c6
36.440299
186
0.59129
4.149711
false
false
false
false
liuxuan30/SwiftCharts
SwiftCharts/AxisValues/ChartAxisValueString.swift
2
710
// // ChartAxisValueString.swift // SwiftCharts // // Created by ischuetz on 29/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public class ChartAxisValueString: ChartAxisValue { let string: String private let labelSettings: ChartLabelSettings public init(_ string: String = "", order: Int, labelSettings: ChartLabelSettings = ChartLabelSettings()) { self.string = string self.labelSettings = labelSettings super.init(scalar: CGFloat(order)) } override public var labels: [ChartAxisLabel] { let axisLabel = ChartAxisLabel(text: self.string, settings: self.labelSettings) return [axisLabel] } }
apache-2.0
5d1759f775e5fcc803e91031e2d06147
26.307692
110
0.68169
4.733333
false
false
false
false
danielgindi/Charts
Source/Charts/Charts/HorizontalBarChartView.swift
2
9693
// // HorizontalBarChartView.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 /// BarChart with horizontal bar orientation. In this implementation, x- and y-axis are switched. open class HorizontalBarChartView: BarChartView { internal override func initialize() { super.initialize() _leftAxisTransformer = TransformerHorizontalBarChart(viewPortHandler: viewPortHandler) _rightAxisTransformer = TransformerHorizontalBarChart(viewPortHandler: viewPortHandler) renderer = HorizontalBarChartRenderer(dataProvider: self, animator: chartAnimator, viewPortHandler: viewPortHandler) leftYAxisRenderer = YAxisRendererHorizontalBarChart(viewPortHandler: viewPortHandler, axis: leftAxis, transformer: _leftAxisTransformer) rightYAxisRenderer = YAxisRendererHorizontalBarChart(viewPortHandler: viewPortHandler, axis: rightAxis, transformer: _rightAxisTransformer) xAxisRenderer = XAxisRendererHorizontalBarChart(viewPortHandler: viewPortHandler, axis: xAxis, transformer: _leftAxisTransformer, chart: self) self.highlighter = HorizontalBarHighlighter(chart: self) } internal override func calculateLegendOffsets(offsetLeft: inout CGFloat, offsetTop: inout CGFloat, offsetRight: inout CGFloat, offsetBottom: inout CGFloat) { guard legend.isEnabled, !legend.drawInside else { return } // setup offsets for legend switch legend.orientation { case .vertical: switch legend.horizontalAlignment { case .left: offsetLeft += min(legend.neededWidth, viewPortHandler.chartWidth * legend.maxSizePercent) + legend.xOffset case .right: offsetRight += min(legend.neededWidth, viewPortHandler.chartWidth * legend.maxSizePercent) + legend.xOffset case .center: switch legend.verticalAlignment { case .top: offsetTop += min(legend.neededHeight, viewPortHandler.chartHeight * legend.maxSizePercent) + legend.yOffset case .bottom: offsetBottom += min(legend.neededHeight, viewPortHandler.chartHeight * legend.maxSizePercent) + legend.yOffset default: break } } case .horizontal: switch legend.verticalAlignment { case .top: offsetTop += min(legend.neededHeight, viewPortHandler.chartHeight * legend.maxSizePercent) + legend.yOffset // left axis equals the top x-axis in a horizontal chart if leftAxis.isEnabled && leftAxis.isDrawLabelsEnabled { offsetTop += leftAxis.getRequiredHeightSpace() } case .bottom: offsetBottom += min(legend.neededHeight, viewPortHandler.chartHeight * legend.maxSizePercent) + legend.yOffset // right axis equals the bottom x-axis in a horizontal chart if rightAxis.isEnabled && rightAxis.isDrawLabelsEnabled { offsetBottom += rightAxis.getRequiredHeightSpace() } default: break } } } internal override func calculateOffsets() { var offsetLeft: CGFloat = 0.0, offsetRight: CGFloat = 0.0, offsetTop: CGFloat = 0.0, offsetBottom: CGFloat = 0.0 calculateLegendOffsets(offsetLeft: &offsetLeft, offsetTop: &offsetTop, offsetRight: &offsetRight, offsetBottom: &offsetBottom) // offsets for y-labels if leftAxis.needsOffset { offsetTop += leftAxis.getRequiredHeightSpace() } if rightAxis.needsOffset { offsetBottom += rightAxis.getRequiredHeightSpace() } let xlabelwidth = xAxis.labelRotatedWidth if xAxis.isEnabled { // offsets for x-labels if xAxis.labelPosition == .bottom { offsetLeft += xlabelwidth } else if xAxis.labelPosition == .top { offsetRight += xlabelwidth } else if xAxis.labelPosition == .bothSided { offsetLeft += xlabelwidth offsetRight += xlabelwidth } } offsetTop += self.extraTopOffset offsetRight += self.extraRightOffset offsetBottom += self.extraBottomOffset offsetLeft += self.extraLeftOffset viewPortHandler.restrainViewPort( offsetLeft: max(self.minOffset, offsetLeft), offsetTop: max(self.minOffset, offsetTop), offsetRight: max(self.minOffset, offsetRight), offsetBottom: max(self.minOffset, offsetBottom)) prepareOffsetMatrix() prepareValuePxMatrix() } internal override func prepareValuePxMatrix() { _rightAxisTransformer.prepareMatrixValuePx(chartXMin: rightAxis._axisMinimum, deltaX: CGFloat(rightAxis.axisRange), deltaY: CGFloat(xAxis.axisRange), chartYMin: xAxis._axisMinimum) _leftAxisTransformer.prepareMatrixValuePx(chartXMin: leftAxis._axisMinimum, deltaX: CGFloat(leftAxis.axisRange), deltaY: CGFloat(xAxis.axisRange), chartYMin: xAxis._axisMinimum) } open override func getMarkerPosition(highlight: Highlight) -> CGPoint { return CGPoint(x: highlight.drawY, y: highlight.drawX) } open override func getBarBounds(entry e: BarChartDataEntry) -> CGRect { guard let data = data as? BarChartData, let set = data.getDataSetForEntry(e) as? BarChartDataSetProtocol else { return .null } let y = e.y let x = e.x let barWidth = data.barWidth let top = x - 0.5 + barWidth / 2.0 let bottom = x + 0.5 - barWidth / 2.0 let left = y >= 0.0 ? y : 0.0 let right = y <= 0.0 ? y : 0.0 var bounds = CGRect(x: left, y: top, width: right - left, height: bottom - top) getTransformer(forAxis: set.axisDependency).rectValueToPixel(&bounds) return bounds } open override func getPosition(entry e: ChartDataEntry, axis: YAxis.AxisDependency) -> CGPoint { var vals = CGPoint(x: CGFloat(e.y), y: CGFloat(e.x)) getTransformer(forAxis: axis).pointValueToPixel(&vals) return vals } open override func getHighlightByTouchPoint(_ pt: CGPoint) -> Highlight? { if data === nil { Swift.print("Can't select by touch. No data set.", terminator: "\n") return nil } return self.highlighter?.getHighlight(x: pt.y, y: pt.x) } /// The lowest x-index (value on the x-axis) that is still visible on he chart. open override var lowestVisibleX: Double { var pt = CGPoint( x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom) getTransformer(forAxis: .left).pixelToValues(&pt) return max(xAxis._axisMinimum, Double(pt.y)) } /// The highest x-index (value on the x-axis) that is still visible on the chart. open override var highestVisibleX: Double { var pt = CGPoint( x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop) getTransformer(forAxis: .left).pixelToValues(&pt) return min(xAxis._axisMaximum, Double(pt.y)) } // MARK: - Viewport open override func setVisibleXRangeMaximum(_ maxXRange: Double) { let xScale = xAxis.axisRange / maxXRange viewPortHandler.setMinimumScaleY(CGFloat(xScale)) } open override func setVisibleXRangeMinimum(_ minXRange: Double) { let xScale = xAxis.axisRange / minXRange viewPortHandler.setMaximumScaleY(CGFloat(xScale)) } open override func setVisibleXRange(minXRange: Double, maxXRange: Double) { let minScale = xAxis.axisRange / minXRange let maxScale = xAxis.axisRange / maxXRange viewPortHandler.setMinMaxScaleY(minScaleY: CGFloat(minScale), maxScaleY: CGFloat(maxScale)) } open override func setVisibleYRangeMaximum(_ maxYRange: Double, axis: YAxis.AxisDependency) { let yScale = getAxisRange(axis: axis) / maxYRange viewPortHandler.setMinimumScaleX(CGFloat(yScale)) } open override func setVisibleYRangeMinimum(_ minYRange: Double, axis: YAxis.AxisDependency) { let yScale = getAxisRange(axis: axis) / minYRange viewPortHandler.setMaximumScaleX(CGFloat(yScale)) } open override func setVisibleYRange(minYRange: Double, maxYRange: Double, axis: YAxis.AxisDependency) { let minScale = getAxisRange(axis: axis) / minYRange let maxScale = getAxisRange(axis: axis) / maxYRange viewPortHandler.setMinMaxScaleX(minScaleX: CGFloat(minScale), maxScaleX: CGFloat(maxScale)) } }
apache-2.0
3ff4c6114c6f6cd7fee6266ba370a384
35.033457
188
0.605179
5.685044
false
false
false
false
lkzhao/MCollectionView
Sources/DictionaryTwoWay.swift
1
1441
// // https://gist.github.com/CanTheAlmighty/70b3bf66eb1f2a5cee28 // struct DictionaryTwoWay<S:Hashable, T:Hashable> : ExpressibleByDictionaryLiteral { // Literal convertible typealias Key = S typealias Value = T // Real storage var st: [S : T] = [:] var ts: [T : S] = [:] init(leftRight st: [S:T]) { var ts: [T:S] = [:] for (key, value) in st { ts[value] = key } self.st = st self.ts = ts } init(rightLeft ts: [T:S]) { var st: [S:T] = [:] for (key, value) in ts { st[value] = key } self.st = st self.ts = ts } init(dictionaryLiteral elements: (Key, Value)...) { for element in elements { st[element.0] = element.1 ts[element.1] = element.0 } } init() { } subscript(key: S) -> T? { get { return st[key] } set(val) { remove(key) if let val = val { remove(val) st[key] = val ts[val] = key } } } subscript(key: T) -> S? { get { return ts[key] } set(val) { remove(key) if let val = val { remove(val) ts[key] = val st[val] = key } } } mutating func remove(_ key: S) { if let item = st.removeValue(forKey: key) { ts.removeValue(forKey: item) } } mutating func remove(_ key: T) { if let item = ts.removeValue(forKey: key) { st.removeValue(forKey: item) } } }
mit
836510823343059e7ae877bfd74efd8a
15.755814
82
0.506593
3.119048
false
false
false
false
languageininteraction/VowelSpaceTravel
mobile/Vowel Space Travel iOS/Vowel Space Travel iOS/ReselectableSegmentedControl.swift
1
952
// // ReselectableSegmentedControl.swift // Vowel Space Travel iOS // // Created by Wessel Stoop on 20/08/15. // Copyright (c) 2015 Radboud University. All rights reserved. // import Foundation import UIKit class ReselectableSegmentedControl: UISegmentedControl { @IBInspectable var allowReselection: Bool = true override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { let previousSelectedSegmentIndex = self.selectedSegmentIndex super.touchesEnded(touches, withEvent: event) if allowReselection && previousSelectedSegmentIndex == self.selectedSegmentIndex { if let touch = touches.first { let touchLocation = touch.locationInView(self) if CGRectContainsPoint(bounds, touchLocation) { self.sendActionsForControlEvents(.ValueChanged) } } } } }
gpl-2.0
93abf62820a1306ab7f5e91e358ba3c5
28.78125
88
0.646008
5.378531
false
false
false
false
wenghengcong/Coderpursue
BeeFun/BeeFun/View/Event/NotUse/BFImageViewAttachment.swift
1
1094
// // BFEventCellImageViewAttachment.swift // BeeFun // // Created by WengHengcong on 22/09/2017. // Copyright © 2017 JungleSong. All rights reserved. // import UIKit import YYText class BFImageViewAttachment: YYTextAttachment { var imageURL: URL? var size: CGSize? private var _imageView: UIImageView? override var content: Any? { set { _imageView = content as? UIImageView } get { /// UIImageView 只能在主线程访问 if pthread_main_np() == 0 { return nil } if _imageView != nil { return _imageView } /// 第一次获取时 (应该是在文本渲染完成,需要添加附件视图时),初始化图片视图,并下载图片 /// 这里改成 YYAnimatedImageView 就能支持 GIF/APNG/WebP 动画了 _imageView = UIImageView() _imageView?.size = size ?? CGSize.zero _imageView?.kf.setImage(with: imageURL) return _imageView } } }
mit
a54d07d2d82c85960b21ca397ce08d82
23.375
63
0.547692
4.352679
false
false
false
false
proversity-org/edx-app-ios
Source/DetailToolbarButton.swift
1
3584
// // DetailToolbarButton.swift // edX // // Created by Akiva Leffert on 6/27/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit /// A simple two line button with an action and detail text text. /// Views of this class are meant to be embedded in a UIBarButtonItem in a UIToolbar class DetailToolbarButton: UIView { enum Direction { case Next case Prev } let direction : Direction let button = UIButton(type: .system) init(direction : Direction, titleText : String, destinationText : String?, action : @escaping () -> Void) { self.direction = direction // TODO: Switch to size classes when giving htis this a maximum size when we add tablet support super.init(frame: CGRect(x: 0, y: 0, width: 140, height: 44)) addSubview(button) let styledTitle = titleStyle.attributedString(withText: titleText) var title: NSAttributedString if let destination = destinationText { let styledDestination = destinationStyle.attributedString(withText: destination) title = NSAttributedString(string: "{top}\n{bottom}", attributes : titleStyle.attributes.attributedKeyDictionary()).oex_format(withParameters: ["top" : styledTitle, "bottom" : styledDestination]) } else { title = NSAttributedString(string: "{top}", attributes : titleStyle.attributes.attributedKeyDictionary()).oex_format(withParameters: ["top" : styledTitle]) } button.titleLabel?.numberOfLines = 2 button.setAttributedTitle(title, for: .normal) let disabledTitle = NSMutableAttributedString(attributedString: title) disabledTitle.setAttributes([NSAttributedString.Key.foregroundColor: OEXStyles.shared().disabledButtonColor()], range: NSMakeRange(0, title.length)) button.setAttributedTitle(disabledTitle, for: .disabled) button.contentHorizontalAlignment = buttonAlignment button.oex_addAction({_ in action() }, for: .touchUpInside) button.snp.makeConstraints { make in make.leading.equalTo(self) make.trailing.equalTo(self) make.top.equalTo(self) make.bottom.equalTo(self) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var buttonAlignment : UIControl.ContentHorizontalAlignment { // TODO: Deal with RTL once we add iOS 9 support and swap the toolbar buttons depending on layout // direction switch direction { case .Next: return .right case .Prev: return .left } } var textAlignment : NSTextAlignment { // TODO: Deal with RTL once we add iOS 9 support and swap the toolbar buttons depending on layout // direction switch direction { case .Next: return .right case .Prev: return .left } } private var titleStyle : OEXTextStyle { let style = OEXMutableTextStyle(weight: .semiBold, size: .small, color: OEXStyles.shared().primaryBaseColor()) style.alignment = self.textAlignment style.dynamicTypeSupported = false return style } private var destinationStyle : OEXTextStyle { let style = OEXMutableTextStyle(weight: .normal, size: .xSmall, color: OEXStyles.shared().neutralBase()) style.alignment = self.textAlignment style.dynamicTypeSupported = false return style } }
apache-2.0
31200736b02251ca2c2c37d3713cf0b7
36.333333
207
0.649833
5.026648
false
false
false
false
abdullah-chhatra/iLayout
iLayout/iLayout/Layout+Relative+Dimension.swift
1
8145
// // Layout+Sibling+Dimension.swift // iLayout // // Created by Abdulmunaf Chhatra on 5/23/15. // Copyright (c) 2015 Abdullah. All rights reserved. // import UIKit /** This extension exposes method to set dimensions of views in realtion to other view. */ public extension Layout { /** Makes the height of given view same as another view. :param: view Make height of this view same as equalTo view. :param: equalTo Given view's height will be set as equal to this view. :param: offset Offset to the height. :returns: Returns the created constraint. */ @discardableResult public func makeWidthOfView(_ view: UIView, equalTo: UIView, offset: CGFloat = 0) -> NSLayoutConstraint { return makeView(view, toView: equalTo, attribute: .width, relatedBy: .equal, constant: offset) } /** Makes the width of given view same as another view. :param: view Make width of this view same as equalTo view. :param: equalTo Given view's width will be set as equal to this view. :param: offset Offset to the width. :returns: Returns the created constraint. */ @discardableResult public func makeHeightOfView(_ view: UIView, equalTo: UIView, offset: CGFloat = 0) -> NSLayoutConstraint { return makeView(view, toView: equalTo, attribute: .height, relatedBy: .equal, constant: offset) } /** Makes the size of given view same as another view. :param: view Make size of this view same as equalTo view. :param: equalTo Given view's size will be set as equal to this view. :param: offsetWidth Offset to the width. :param: offsetHeight Offset to the width. :returns: Returns the two created constraints to set height and width. */ @discardableResult public func makeSizeOfView(_ view: UIView, equalTo: UIView, offsetWidth: CGFloat = 0, offsetHeight: CGFloat = 0) -> [NSLayoutConstraint] { return [makeHeightOfView(view, equalTo: equalTo, offset: offsetHeight), makeWidthOfView(view, equalTo: equalTo, offset: offsetWidth)] } /** Makes the width of given view greater than or equal to another view. :param: view Make width of this view greater than or equal to `greaterOrEqualTo` view. :param: greaterOrEqualTo Given view's width will be set greater than or equal to this view. :param: offset Offset to the width. :returns: Returns the created constraint. */ @discardableResult public func makeWidthOfView(_ view: UIView, greaterOrEqualTo: UIView, offset: CGFloat = 0) -> NSLayoutConstraint { return makeView(view, toView: greaterOrEqualTo, attribute: .width, relatedBy: .greaterThanOrEqual, constant: offset) } /** Makes the height of given view greater than or equal to another view. :param: view Make height of this view greater than or equal to `greaterOrEqualTo` view. :param: greaterOrEqualTo Given view's height will be set greater than or equal to this view. :param: offset Offset to the height. :returns: Returns the created constraint. */ @discardableResult public func makeHeightOfView(_ view: UIView, greaterOrEqualTo: UIView, offset: CGFloat = 0) -> NSLayoutConstraint { return makeView(view, toView: greaterOrEqualTo, attribute: .height, relatedBy: .greaterThanOrEqual, constant: offset) } /** Makes the width of given view less than or equal to another view. :param: view Make width of this view less than or equal to `lessOrEqualTo` view. :param: lessOrEqualTo Given view's width will be set less than or equal to this view. :param: offset Offset to the width. :returns: Returns the created constraint. */ @discardableResult public func makeWidthOfView(_ view: UIView, lessOrEqualTo: UIView, offset: CGFloat = 0) -> NSLayoutConstraint { return makeView(view, toView: lessOrEqualTo, attribute: .width, relatedBy: .lessThanOrEqual, constant: offset) } /** Makes the height of given view less than or equal to another view. :param: view Make height of this view less than or equal to `lessOrEqualTo` view. :param: lessOrEqualTo Given view's height will be set less than or equal to this view. :param: offset Offset to the height. :returns: Returns the created constraint. */ @discardableResult public func makeHeightOfView(_ view: UIView, lessOrEqualTo: UIView, offset: CGFloat = 0) -> NSLayoutConstraint { return makeView(view, toView: lessOrEqualTo, attribute: .height, relatedBy: .lessThanOrEqual, constant: offset) } /** Makes the width of give view relative to that of another view. :param: view Make width of this view relative to `relativeTo` view. :param: relativeTo Given view's width will be set relative to this view. :param: multiplier Relative multiplier. :returns: Returns created contraint. */ @discardableResult public func makeWidthOfView(_ view: UIView, relativeTo: UIView, multiplier: CGFloat) -> NSLayoutConstraint { return makeAttributeOfView(view, relativeTo: relativeTo, attribute: NSLayoutAttribute.width, multiplier: multiplier); } /** Makes the height of give view relative to that of another view. :param: view Make height of this view relative to `relativeTo` view. :param: relativeTo Given view's height will be set relative to this view. :param: multiplier Relative multiplier. :returns: Returns created contraint. */ @discardableResult public func makeHeightOfView(_ view: UIView, relativeTo: UIView, multiplier: CGFloat) -> NSLayoutConstraint { return makeAttributeOfView(view, relativeTo: relativeTo, attribute: NSLayoutAttribute.height, multiplier: multiplier); } private func makeAttributeOfView(_ view: UIView, relativeTo: UIView, attribute: NSLayoutAttribute, multiplier: CGFloat) -> NSLayoutConstraint { constraints.append(NSLayoutConstraint(item: view, attribute: attribute, relatedBy: .equal, toItem: relativeTo, attribute: attribute, multiplier: multiplier, constant: 0)) return constraints.last! } private func makeView(_ view: UIView, toView: UIView, attribute: NSLayoutAttribute, relatedBy: NSLayoutRelation, constant: CGFloat) -> NSLayoutConstraint { constraints.append(NSLayoutConstraint(item: view, attribute: attribute, relatedBy: relatedBy, toItem: toView, attribute: attribute, multiplier: 1, constant: constant)) return constraints.last! } }
mit
fe404c9adb39214745b2371dacc1907b
30.692607
159
0.57078
5.507099
false
false
false
false
nghialv/Future
DemoApp/DemoApp/Api.swift
3
1616
// // Api.swift // DemoApp // // Created by Le VanNghia on 6/4/15. // Copyright (c) 2015 Le Van Nghia. All rights reserved. // import Foundation import Alamofire import Result import Future import Himotoki func requestUser(username: String) -> Future<User, NSError> { return Future { completion in let urlString = "https://api.github.com/users/\(username)" Alamofire.request(.GET, urlString) .responseJSON { _, _, json, error in let result: Result<User, NSError> if let error = error { result = Result(error: error) } else { let u: User? = decode(json!) result = Result(value: u!) } completion(result) } } } func searchRepositories(keyword: String) -> Future<[Repository], NSError> { return Future { completion in let urlString = "https://api.github.com/search/repositories?q=\(keyword)+language:swift&sort=stars&order=desc" Alamofire.request(.GET, urlString) .responseJSON { _, _, json, error in let itemsJson: AnyObject? = (json as! [String: AnyObject])["items"] let repos: [Repository]? = decode(itemsJson!) let result: Result<[Repository], NSError> if let error = error { result = Result(error: error) } else { result = Result(value: repos ?? []) } completion(result) } } }
mit
28a66d4a962915e4ee8f02f8c1436957
30.096154
118
0.52104
4.67052
false
false
false
false
apple/swift-nio
Tests/NIOPosixTests/CodecTest+XCTest.swift
1
5978
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // // CodecTest+XCTest.swift // import XCTest /// /// NOTE: This file was generated by generate_linux_tests.rb /// /// Do NOT edit this file directly as it will be regenerated automatically when needed. /// extension ByteToMessageDecoderTest { @available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings") static var allTests : [(String, (ByteToMessageDecoderTest) -> () throws -> Void)] { return [ ("testDecoder", testDecoder), ("testDecoderPropagatesChannelInactive", testDecoderPropagatesChannelInactive), ("testDecoderIsNotQuadratic", testDecoderIsNotQuadratic), ("testMemoryIsReclaimedIfMostIsConsumed", testMemoryIsReclaimedIfMostIsConsumed), ("testMemoryIsReclaimedIfLotsIsAvailable", testMemoryIsReclaimedIfLotsIsAvailable), ("testWeDoNotCallShouldReclaimMemoryAsLongAsWeContinue", testWeDoNotCallShouldReclaimMemoryAsLongAsWeContinue), ("testDecoderReentranceChannelRead", testDecoderReentranceChannelRead), ("testTrivialDecoderDoesSensibleStuffWhenCloseInRead", testTrivialDecoderDoesSensibleStuffWhenCloseInRead), ("testLeftOversMakeDecodeLastCalled", testLeftOversMakeDecodeLastCalled), ("testRemovingHandlerMakesLeftoversAppearInDecodeLast", testRemovingHandlerMakesLeftoversAppearInDecodeLast), ("testStructsWorkAsByteToMessageDecoders", testStructsWorkAsByteToMessageDecoders), ("testReentrantChannelReadWhileWholeBufferIsBeingProcessed", testReentrantChannelReadWhileWholeBufferIsBeingProcessed), ("testReentrantChannelCloseInChannelRead", testReentrantChannelCloseInChannelRead), ("testHandlerRemoveInChannelRead", testHandlerRemoveInChannelRead), ("testChannelCloseInChannelRead", testChannelCloseInChannelRead), ("testDecodeLoopGetsInterruptedWhenRemovalIsTriggered", testDecodeLoopGetsInterruptedWhenRemovalIsTriggered), ("testDecodeLastIsInvokedOnceEvenIfNothingEverArrivedOnChannelClosed", testDecodeLastIsInvokedOnceEvenIfNothingEverArrivedOnChannelClosed), ("testDecodeLastIsInvokedOnceEvenIfNothingEverArrivedOnChannelHalfClosure", testDecodeLastIsInvokedOnceEvenIfNothingEverArrivedOnChannelHalfClosure), ("testDecodeLastHasSeenEOFFalseOnHandlerRemoved", testDecodeLastHasSeenEOFFalseOnHandlerRemoved), ("testDecodeLastHasSeenEOFFalseOnHandlerRemovedEvenIfNoData", testDecodeLastHasSeenEOFFalseOnHandlerRemovedEvenIfNoData), ("testDecodeLastHasSeenEOFTrueOnChannelInactive", testDecodeLastHasSeenEOFTrueOnChannelInactive), ("testWriteObservingByteToMessageDecoderBasic", testWriteObservingByteToMessageDecoderBasic), ("testWriteObservingByteToMessageDecoderWhereWriteIsReentrantlyCalled", testWriteObservingByteToMessageDecoderWhereWriteIsReentrantlyCalled), ("testDecodeMethodsNoLongerCalledIfErrorInDecode", testDecodeMethodsNoLongerCalledIfErrorInDecode), ("testDecodeMethodsNoLongerCalledIfErrorInDecodeLast", testDecodeMethodsNoLongerCalledIfErrorInDecodeLast), ("testBasicLifecycle", testBasicLifecycle), ("testDecodeLoopStopsOnChannelInactive", testDecodeLoopStopsOnChannelInactive), ("testDecodeLoopStopsOnInboundHalfClosure", testDecodeLoopStopsOnInboundHalfClosure), ("testWeForwardReadEOFAndChannelInactive", testWeForwardReadEOFAndChannelInactive), ("testErrorInDecodeLastWhenCloseIsReceivedReentrantlyInDecode", testErrorInDecodeLastWhenCloseIsReceivedReentrantlyInDecode), ("testWeAreOkayWithReceivingDataAfterHalfClosureEOF", testWeAreOkayWithReceivingDataAfterHalfClosureEOF), ("testWeAreOkayWithReceivingDataAfterFullClose", testWeAreOkayWithReceivingDataAfterFullClose), ("testPayloadTooLarge", testPayloadTooLarge), ("testPayloadTooLargeButHandlerOk", testPayloadTooLargeButHandlerOk), ("testRemoveHandlerBecauseOfChannelTearDownWhilstUserTriggeredRemovalIsInProgress", testRemoveHandlerBecauseOfChannelTearDownWhilstUserTriggeredRemovalIsInProgress), ] } } extension MessageToByteEncoderTest { @available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings") static var allTests : [(String, (MessageToByteEncoderTest) -> () throws -> Void)] { return [ ("testEncoderOverrideAllocateOutBuffer", testEncoderOverrideAllocateOutBuffer), ("testEncoder", testEncoder), ("testB2MHIsHappyNeverBeingAddedToAPipeline", testB2MHIsHappyNeverBeingAddedToAPipeline), ("testM2BHIsHappyNeverBeingAddedToAPipeline", testM2BHIsHappyNeverBeingAddedToAPipeline), ] } } extension MessageToByteHandlerTest { @available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings") static var allTests : [(String, (MessageToByteHandlerTest) -> () throws -> Void)] { return [ ("testThrowingEncoderFailsPromises", testThrowingEncoderFailsPromises), ] } }
apache-2.0
879cc19528e69f608d0752736d59a9a8
64.692308
181
0.738207
5.153448
false
true
false
false
szpnygo/firefox-ios
Client/Frontend/Home/RemoteTabsPanel.swift
5
19114
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Account import Shared import SnapKit import Storage import Sync import XCGLogger // TODO: same comment as for SyncAuthState.swift! private let log = XCGLogger.defaultInstance() private struct RemoteTabsPanelUX { static let HeaderHeight: CGFloat = SiteTableViewControllerUX.RowHeight // Not HeaderHeight! static let RowHeight: CGFloat = SiteTableViewControllerUX.RowHeight static let HeaderBackgroundColor = UIColor(rgb: 0xf8f8f8) static let EmptyStateTitleFont = UIFont.boldSystemFontOfSize(15) static let EmptyStateTitleTextColor = UIColor.darkGrayColor() static let EmptyStateInstructionsFont = UIFont.systemFontOfSize(15) static let EmptyStateInstructionsTextColor = UIColor.grayColor() static let EmptyStateInstructionsWidth = 256 static let EmptyStateTopPaddingInBetweenItems: CGFloat = 8 // UX TODO I set this to 8 so that it all fits on landscape static let EmptyStateSignInButtonColor = UIColor(red: 0.259, green: 0.49, blue: 0.831, alpha: 1.0) static let EmptyStateSignInButtonTitleFont = UIFont.systemFontOfSize(20) static let EmptyStateSignInButtonTitleColor = UIColor.whiteColor() static let EmptyStateSignInButtonCornerRadius: CGFloat = 6 static let EmptyStateSignInButtonHeight = 56 static let EmptyStateSignInButtonWidth = 272 static let EmptyStateCreateAccountButtonFont = UIFont.systemFontOfSize(12) } private let RemoteClientIdentifier = "RemoteClient" private let RemoteTabIdentifier = "RemoteTab" class RemoteTabsPanel: UITableViewController, HomePanel { weak var homePanelDelegate: HomePanelDelegate? = nil var profile: Profile! init() { super.init(nibName: nil, bundle: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "firefoxAccountChanged:", name: NotificationFirefoxAccountChanged, object: nil) } required init!(coder aDecoder: NSCoder!) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.registerClass(TwoLineHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: RemoteClientIdentifier) tableView.registerClass(TwoLineTableViewCell.self, forCellReuseIdentifier: RemoteTabIdentifier) tableView.rowHeight = RemoteTabsPanelUX.RowHeight tableView.separatorInset = UIEdgeInsetsZero tableView.delegate = nil tableView.dataSource = nil refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: "SELrefresh", forControlEvents: UIControlEvents.ValueChanged) view.backgroundColor = UIConstants.PanelBackgroundColor } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) refresh() } func firefoxAccountChanged(notification: NSNotification) { if notification.name == NotificationFirefoxAccountChanged { refresh() } } var tableViewDelegate: RemoteTabsPanelDataSource? { didSet { self.tableView.delegate = tableViewDelegate self.tableView.dataSource = tableViewDelegate } } func refresh() { tableView.scrollEnabled = false tableView.allowsSelection = false tableView.tableFooterView = UIView(frame: CGRectZero) // Short circuit if the user is not logged in if profile.getAccount() == nil { self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: self, error: .NotLoggedIn) self.tableView.reloadData() return } self.profile.getCachedClientsAndTabs().uponQueue(dispatch_get_main_queue()) { result in if let clientAndTabs = result.successValue { self.updateDelegateClientAndTabData(clientAndTabs) } // Otherwise, fetch the tabs cloud if its been more than 1 minute since last sync let lastSyncTime = self.profile.prefs.timestampForKey(PrefsKeys.KeyLastRemoteTabSyncTime) if NSDate.now() - (lastSyncTime ?? 0) > OneMinuteInMilliseconds { self.profile.getClientsAndTabs().uponQueue(dispatch_get_main_queue()) { result in if let clientAndTabs = result.successValue { self.profile.prefs.setTimestamp(NSDate.now(), forKey: PrefsKeys.KeyLastRemoteTabSyncTime) self.updateDelegateClientAndTabData(clientAndTabs) } self.endRefreshing() } } else { // If we failed before and didn't sync, show the failure delegate if let failed = result.failureValue { self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: self, error: .FailedToSync) } self.endRefreshing() } } } func endRefreshing() { self.refreshControl?.endRefreshing() self.tableView.scrollEnabled = true self.tableView.reloadData() } func updateDelegateClientAndTabData(clientAndTabs: [ClientAndTabs]) { if clientAndTabs.count == 0 { self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: self, error: .NoClients) } else { let nonEmptyClientAndTabs = clientAndTabs.filter { $0.tabs.count > 0 } if nonEmptyClientAndTabs.count == 0 { self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: self, error: .NoTabs) } else { self.tableViewDelegate = RemoteTabsPanelClientAndTabsDataSource(homePanel: self, clientAndTabs: nonEmptyClientAndTabs) self.tableView.allowsSelection = true } } } @objc private func SELrefresh() { self.refreshControl?.beginRefreshing() refresh() } } enum RemoteTabsError { case NotLoggedIn case NoClients case NoTabs case FailedToSync func localizedString() -> String { switch self { case NotLoggedIn: return "" // This does not have a localized string because we have a whole specific screen for it. case NoClients: return NSLocalizedString("You don't have any other devices connected to this Firefox Account available to sync.", comment: "Error message in the remote tabs panel") case NoTabs: return NSLocalizedString("You don't have any tabs open in Firefox on your other devices.", comment: "Error message in the remote tabs panel") case FailedToSync: return NSLocalizedString("There was a problem accessing tabs from your other devices. Try again in a few moments.", comment: "Error message in the remote tabs panel") } } } protocol RemoteTabsPanelDataSource: UITableViewDataSource, UITableViewDelegate { } class RemoteTabsPanelClientAndTabsDataSource: NSObject, RemoteTabsPanelDataSource { weak var homePanel: HomePanel? private var clientAndTabs: [ClientAndTabs] init(homePanel: HomePanel, clientAndTabs: [ClientAndTabs]) { self.homePanel = homePanel self.clientAndTabs = clientAndTabs } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.clientAndTabs.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.clientAndTabs[section].tabs.count } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return RemoteTabsPanelUX.HeaderHeight } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let clientTabs = self.clientAndTabs[section] let client = clientTabs.client let view = tableView.dequeueReusableHeaderFooterViewWithIdentifier(RemoteClientIdentifier) as! TwoLineHeaderFooterView view.frame = CGRect(x: 0, y: 0, width: tableView.frame.width, height: RemoteTabsPanelUX.HeaderHeight) view.textLabel.text = client.name view.contentView.backgroundColor = RemoteTabsPanelUX.HeaderBackgroundColor /* * A note on timestamps. * We have access to two timestamps here: the timestamp of the remote client record, * and the set of timestamps of the client's tabs. * Neither is "last synced". The client record timestamp changes whenever the remote * client uploads its record (i.e., infrequently), but also whenever another device * sends a command to that client -- which can be much later than when that client * last synced. * The client's tabs haven't necessarily changed, but it can still have synced. * Ideally, we should save and use the modified time of the tabs record itself. * This will be the real time that the other client uploaded tabs. */ let timestamp = clientTabs.approximateLastSyncTime() let label = NSLocalizedString("Last synced: %@", comment: "Remote tabs last synced time. Argument is the relative date string.") view.detailTextLabel.text = String(format: label, NSDate.fromTimestamp(timestamp).toRelativeTimeString()) let image: UIImage? if client.type == "desktop" { image = UIImage(named: "deviceTypeDesktop") image?.accessibilityLabel = NSLocalizedString("computer", comment: "Accessibility label for Desktop Computer (PC) image in remote tabs list") } else { image = UIImage(named: "deviceTypeMobile") image?.accessibilityLabel = NSLocalizedString("mobile device", comment: "Accessibility label for Mobile Device image in remote tabs list") } view.imageView.image = image view.mergeAccessibilityLabels() return view } private func tabAtIndexPath(indexPath: NSIndexPath) -> RemoteTab { return clientAndTabs[indexPath.section].tabs[indexPath.item] } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(RemoteTabIdentifier, forIndexPath: indexPath) as! TwoLineTableViewCell let tab = tabAtIndexPath(indexPath) cell.setLines(tab.title, detailText: tab.URL.absoluteString) // TODO: Bug 1144765 - Populate image with cached favicons. return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) let tab = tabAtIndexPath(indexPath) if let homePanel = self.homePanel { // It's not a bookmark, so let's call it Typed (which means History, too). homePanel.homePanelDelegate?.homePanel(homePanel, didSelectURL: tab.URL, visitType: VisitType.Typed) } } } // MARK: - class RemoteTabsPanelErrorDataSource: NSObject, RemoteTabsPanelDataSource { weak var homePanel: HomePanel? var error: RemoteTabsError init(homePanel: HomePanel, error: RemoteTabsError) { self.homePanel = homePanel self.error = error } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return tableView.bounds.height } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch error { case .NotLoggedIn: let cell = RemoteTabsNotLoggedInCell(homePanel: homePanel) return cell default: let cell = RemoteTabsErrorCell(error: self.error) return cell } } } // MARK: - class RemoteTabsErrorCell: UITableViewCell { static let Identifier = "RemoteTabsErrorCell" init(error: RemoteTabsError) { super.init(style: .Default, reuseIdentifier: RemoteTabsErrorCell.Identifier) separatorInset = UIEdgeInsetsMake(0, 1000, 0, 0) let containerView = UIView() contentView.addSubview(containerView) let imageView = UIImageView() imageView.image = UIImage(named: "emptySync") containerView.addSubview(imageView) imageView.snp_makeConstraints { (make) -> Void in make.top.equalTo(containerView) make.centerX.equalTo(containerView) } let instructionsLabel = UILabel() instructionsLabel.font = RemoteTabsPanelUX.EmptyStateInstructionsFont instructionsLabel.text = error.localizedString() instructionsLabel.textAlignment = NSTextAlignment.Center instructionsLabel.textColor = RemoteTabsPanelUX.EmptyStateInstructionsTextColor instructionsLabel.numberOfLines = 0 containerView.addSubview(instructionsLabel) instructionsLabel.snp_makeConstraints({ (make) -> Void in make.top.equalTo(imageView.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.centerX.equalTo(containerView) make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth) }) containerView.snp_makeConstraints({ (make) -> Void in // Let the container wrap around the content make.top.equalTo(imageView.snp_top) make.left.bottom.right.equalTo(instructionsLabel) // And then center it in the overlay view that sits on top of the UITableView make.center.equalTo(contentView) }) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - class RemoteTabsNotLoggedInCell: UITableViewCell { static let Identifier = "RemoteTabsNotLoggedInCell" var homePanel: HomePanel? init(homePanel: HomePanel?) { super.init(style: .Default, reuseIdentifier: RemoteTabsErrorCell.Identifier) self.homePanel = homePanel let containerView = UIView() contentView.addSubview(containerView) let imageView = UIImageView() imageView.image = UIImage(named: "emptySync") containerView.addSubview(imageView) imageView.snp_makeConstraints { (make) -> Void in make.top.equalTo(containerView) make.centerX.equalTo(containerView) } let titleLabel = UILabel() titleLabel.font = RemoteTabsPanelUX.EmptyStateTitleFont titleLabel.text = NSLocalizedString("Welcome to Sync", comment: "See http://mzl.la/1Qtkf0j") titleLabel.textAlignment = NSTextAlignment.Center titleLabel.textColor = RemoteTabsPanelUX.EmptyStateTitleTextColor containerView.addSubview(titleLabel) titleLabel.snp_makeConstraints({ (make) -> Void in make.top.equalTo(imageView.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.centerX.equalTo(containerView) }) let instructionsLabel = UILabel() instructionsLabel.font = RemoteTabsPanelUX.EmptyStateInstructionsFont instructionsLabel.text = NSLocalizedString("Sync your tabs, bookmarks, passwords and more.", comment: "See http://mzl.la/1Qtkf0j") instructionsLabel.textAlignment = NSTextAlignment.Center instructionsLabel.textColor = RemoteTabsPanelUX.EmptyStateInstructionsTextColor instructionsLabel.numberOfLines = 0 containerView.addSubview(instructionsLabel) instructionsLabel.snp_makeConstraints({ (make) -> Void in make.top.equalTo(titleLabel.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.centerX.equalTo(containerView) make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth) }) let signInButton = UIButton() signInButton.backgroundColor = RemoteTabsPanelUX.EmptyStateSignInButtonColor signInButton.setTitle(NSLocalizedString("Sign in", comment: "See http://mzl.la/1Qtkf0j"), forState: .Normal) signInButton.setTitleColor(RemoteTabsPanelUX.EmptyStateSignInButtonTitleColor, forState: .Normal) signInButton.titleLabel?.font = RemoteTabsPanelUX.EmptyStateSignInButtonTitleFont signInButton.layer.cornerRadius = RemoteTabsPanelUX.EmptyStateSignInButtonCornerRadius signInButton.clipsToBounds = true signInButton.addTarget(self, action: "SELsignIn", forControlEvents: UIControlEvents.TouchUpInside) containerView.addSubview(signInButton) signInButton.snp_makeConstraints { (make) -> Void in make.centerX.equalTo(containerView) make.top.equalTo(instructionsLabel.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.height.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonHeight) make.width.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonWidth) } let createAnAccountButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton createAnAccountButton.setTitle(NSLocalizedString("Create an account", comment: "See http://mzl.la/1Qtkf0j"), forState: .Normal) createAnAccountButton.titleLabel?.font = RemoteTabsPanelUX.EmptyStateCreateAccountButtonFont createAnAccountButton.addTarget(self, action: "SELcreateAnAccount", forControlEvents: UIControlEvents.TouchUpInside) containerView.addSubview(createAnAccountButton) createAnAccountButton.snp_makeConstraints({ (make) -> Void in make.centerX.equalTo(containerView) make.top.equalTo(signInButton.snp_bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) }) containerView.snp_makeConstraints({ (make) -> Void in // Let the container wrap around the content make.top.equalTo(imageView.snp_top) make.bottom.equalTo(createAnAccountButton) make.left.equalTo(signInButton) make.right.equalTo(signInButton) // And then center it in the overlay view that sits on top of the UITableView make.center.equalTo(contentView) }) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc private func SELsignIn() { if let homePanel = self.homePanel { homePanel.homePanelDelegate?.homePanelDidRequestToSignIn(homePanel) } } @objc private func SELcreateAnAccount() { if let homePanel = self.homePanel { homePanel.homePanelDelegate?.homePanelDidRequestToCreateAccount(homePanel) } } }
mpl-2.0
2a231cee18d9893b10e389c10fbc7077
42.04955
178
0.697918
5.253986
false
false
false
false
realm/SwiftLint
Source/SwiftLintFramework/Rules/Style/TrailingNewlineRule.swift
1
2492
import Foundation import SourceKittenFramework extension String { private func countOfTrailingCharacters(in characterSet: CharacterSet) -> Int { var count = 0 for char in unicodeScalars.lazy.reversed() { if !characterSet.contains(char) { break } count += 1 } return count } fileprivate func trailingNewlineCount() -> Int? { return countOfTrailingCharacters(in: .newlines) } } struct TrailingNewlineRule: CorrectableRule, ConfigurationProviderRule, SourceKitFreeRule { var configuration = SeverityConfiguration(.warning) init() {} static let description = RuleDescription( identifier: "trailing_newline", name: "Trailing Newline", description: "Files should have a single trailing newline.", kind: .style, nonTriggeringExamples: [ Example("let a = 0\n") ], triggeringExamples: [ Example("let a = 0"), Example("let a = 0\n\n") ].skipWrappingInCommentTests().skipWrappingInStringTests(), corrections: [ Example("let a = 0"): Example("let a = 0\n"), Example("let b = 0\n\n"): Example("let b = 0\n"), Example("let c = 0\n\n\n\n"): Example("let c = 0\n") ] ) func validate(file: SwiftLintFile) -> [StyleViolation] { if file.contents.trailingNewlineCount() == 1 { return [] } return [StyleViolation(ruleDescription: Self.description, severity: configuration.severity, location: Location(file: file.path, line: max(file.lines.count, 1)))] } func correct(file: SwiftLintFile) -> [Correction] { guard let count = file.contents.trailingNewlineCount(), count != 1 else { return [] } guard let lastLineRange = file.lines.last?.range else { return [] } if file.ruleEnabled(violatingRanges: [lastLineRange], for: self).isEmpty { return [] } if count < 1 { file.append("\n") } else { let index = file.contents.index(file.contents.endIndex, offsetBy: 1 - count) file.write(file.contents[..<index]) } let location = Location(file: file.path, line: max(file.lines.count, 1)) return [Correction(ruleDescription: Self.description, location: location)] } }
mit
0054f5f4c9632adddb57bb938838c4af
33.136986
100
0.573836
4.640596
false
true
false
false
samlaudev/DesignerNews
DesignerNews/MenuViewController.swift
1
2086
// // MenuViewController.swift // DesignerNews // // Created by Sam Lau on 3/13/15. // Copyright (c) 2015 Sam Lau. All rights reserved. // import UIKit protocol MenuViewControllerDelegate: class { func menuViewControllerDidTouchTop(controller: MenuViewController) func menuViewControllerDidTouchRecent(controller: MenuViewController) func menuViewControllerDidTouchLogout(controller: MenuViewController) func menuViewControllerDidTouchLogin(controller: MenuViewController) } class MenuViewController: UIViewController { // MARK: - UI properties @IBOutlet weak var dialogView: DesignableView! @IBOutlet weak var logoutLabel: UILabel! // MARK: - Delegate weak var delegate: MenuViewControllerDelegate? // MARK: - View controller lifecycle override func viewDidLoad() { super.viewDidLoad() if LocalStore.getToken() == nil { logoutLabel.text = "Login" }else { logoutLabel.text = "Logout" } } // MARK: - Respond to action @IBAction func closeButtonDidTouch(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) dialogView.animation = "fall" dialogView.animate() } @IBAction func topStoriesDidTouch(sender: AnyObject) { delegate?.menuViewControllerDidTouchTop(self) closeButtonDidTouch(sender) } @IBAction func recentButtonDidTouch(sender: AnyObject) { delegate?.menuViewControllerDidTouchRecent(self) closeButtonDidTouch(sender) } @IBAction func logoutButtonDidTouch(sender: AnyObject) { if LocalStore.getToken() == nil { // need to login dismissViewControllerAnimated(true, completion: nil) self.delegate?.menuViewControllerDidTouchLogin(self) }else { // need to logout LocalStore.removeToken() dismissViewControllerAnimated(true, completion: nil) self.delegate?.menuViewControllerDidTouchLogout(self) } } }
mit
b8f4e9b46ed189ad09c72ef81f849449
30.606061
73
0.667785
5.254408
false
false
false
false
xdliu002/TAC_communication
2016.4.28/TableView/TableView/ChecklistViewController.swift
1
3188
// // ViewController.swift // TableView // // Created by 李茂琦 on 4/28/16. // Copyright © 2016 Li Maoqi. All rights reserved. // import UIKit class ChecklistViewController: UITableViewController { var items = [ChecklistItem]() required init?(coder aDecoder: NSCoder) { let row0Item = ChecklistItem() row0Item.text = "limaoqi" items.append(row0Item) let row1Item = ChecklistItem() row1Item.text = "huangrui" items.append(row1Item) let row2Item = ChecklistItem() row2Item.text = "linjunqi" items.append(row2Item) let row3Item = ChecklistItem() row3Item.text = "anzhehong" items.append(row3Item) let row4Item = ChecklistItem() row4Item.text = "huoteng" items.append(row4Item) super.init(coder: aDecoder) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ChecklistItem", forIndexPath: indexPath) let item = items[indexPath.row] configureTextForCell(cell, withChecklistItem: item) configureCheckmarkForCell(cell, withChecklistItem: item) return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let cell = tableView.cellForRowAtIndexPath(indexPath) { let item = items[indexPath.row] item.toggleChecked() configureCheckmarkForCell(cell, withChecklistItem: item) } tableView.deselectRowAtIndexPath(indexPath, animated: true) } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { items.removeAtIndex(indexPath.row) let indexPaths = [indexPath] tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic) } func configureCheckmarkForCell(cell: UITableViewCell, withChecklistItem item: ChecklistItem) { if item.checked { cell.accessoryType = .Checkmark } else { cell.accessoryType = .None } } func configureTextForCell(cell: UITableViewCell, withChecklistItem item: ChecklistItem) { let label = cell.viewWithTag(1000) as! UILabel label.text = item.text } @IBAction func addItem(sender: UIBarButtonItem) { let newRowIndex = items.count let item = ChecklistItem() item.text = "I am a new item" item.checked = false items.append(item) let indexPath = NSIndexPath(forRow: newRowIndex, inSection: 0) let indexPaths = [indexPath] tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic) } }
mit
45c0682481921b8ec2fa089d5450d130
29.596154
157
0.631562
5.08147
false
false
false
false
jboullianne/EndlessTunes
EndlessSoundFeed/RecentsRow.swift
1
3060
// // RecentsRow.swift // EndlessSoundFeed // // Created by Jean-Marc Boullianne on 7/15/17. // Copyright © 2017 Jean-Marc Boullianne. All rights reserved. // import UIKit import Alamofire import AlamofireImage class RecentsRow: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { var manager:ETDataManager! var rowUser:SearchManager.ETUser? var recents:[[String]] = [] @IBOutlet var collectionView: UICollectionView! override func awakeFromNib() { super.awakeFromNib() // Initialization code manager = ETDataManager.sharedInstance } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //Load User Info If Not Nil if rowUser != nil { return recents.count } //Else Load Current User's Info return manager.rpInfo.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RecentCollectionCell", for: indexPath) as! RecentCollectionCell let index = indexPath.row let recent:[String]? if rowUser != nil { recent = recents[index] }else { recent = manager.rpInfo[index] } if let recent = recent { cell.titleLabel.text = recent[0] cell.sourceLabel.text = recent[1] //Load External Thumbnail if it Exists if(recent[2] != "" && manager.rpImages[index] == nil){ Alamofire.request(recent[2]).responseImage { response in if let image = response.result.value { print("image downloaded: \(image)") DispatchQueue.main.async { if let updatedCell = collectionView.cellForItem(at: indexPath) as? RecentCollectionCell { updatedCell.thumbnailView.contentMode = .scaleAspectFill updatedCell.thumbnailView.image = image collectionView.reloadItems(at: [indexPath]) } self.manager.rpImages[index] = image } } } } else { cell.thumbnailView.image = manager.rpImages[index] } } return cell } } extension RecentsRow: ETDataManagerRecentsDelagate { func newRecentsReceived() { self.collectionView.reloadData() } }
gpl-3.0
9b243a4705499d9f74223ccb8fc8cdc0
30.536082
139
0.551814
5.717757
false
false
false
false
Neft-io/neft
packages/neft-runtime-macos/io.neft.mac/Reader.swift
1
1122
import Foundation class Reader { private var data: ClientUpdateMessage? private var actionsIndex = 0 private var booleansIndex = 0 private var integersIndex = 0 private var floatsIndex = 0 private var stringsIndex = 0 func reload(_ message: ClientUpdateMessage) { data = message actionsIndex = 0 booleansIndex = 0 integersIndex = 0 floatsIndex = 0 stringsIndex = 0 } func getAction() -> InAction? { if actionsIndex >= data!.actions.count { return nil } actionsIndex += 1 return InAction(rawValue: data!.actions[actionsIndex - 1]) } func getBoolean() -> Bool { booleansIndex += 1 return data!.booleans[booleansIndex - 1] } func getInteger() -> Int { integersIndex += 1 return data!.integers[integersIndex - 1] } func getFloat() -> CGFloat { floatsIndex += 1 return data!.floats[floatsIndex - 1] } func getString() -> String { stringsIndex += 1 return data!.strings[stringsIndex - 1] } }
apache-2.0
bdbad8ad8b2f8707a3637dbf0a4368c0
22.375
66
0.58467
4.579592
false
false
false
false
RxSwiftCommunity/RxSwiftExt
Playground/RxSwiftExtPlayground.playground/Pages/partition.xcplaygroundpage/Contents.swift
2
661
/*: > # IMPORTANT: To use `RxSwiftExtPlayground.playground`, please: 1. Make sure you have [Carthage](https://github.com/Carthage/Carthage) installed 1. Fetch Carthage dependencies from shell: `carthage bootstrap --platform ios` 1. Build scheme `RxSwiftExtPlayground` scheme for a simulator target 1. Choose `View > Show Debug Area` */ //: [Previous](@previous) import RxSwift import RxSwiftExt example("partition") { let numbers = Observable .of(1, 2, 3, 5, 8, 13, 18, 21, 23) let (evens, odds) = numbers.partition { $0 % 2 == 0 } _ = evens.debug("even").subscribe() _ = odds.debug("odds").subscribe() } //: [Next](@next)
mit
fb767abd170030cec79b23fcfca55526
25.44
81
0.66112
3.612022
false
false
false
false
finder39/Swignals
Source/Swignal3Args.swift
1
1543
// // Swignal3Args.swift // Plug // // Created by Joseph Neuman on 7/3/16. // Copyright © 2016 Plug. All rights reserved. // import Foundation open class Swignal3Args<A,B,C>: SwignalBase { public override init() { } open func addObserver<L: AnyObject>(_ observer: L, callback: @escaping (_ observer: L, _ arg1: A, _ arg2: B, _ arg3: C) -> ()) { let observer = Observer3Args(swignal: self, observer: observer, callback: callback) addSwignalObserver(observer) } open func fire(_ arg1: A, arg2: B, arg3: C) { synced(self) { for watcher in self.swignalObservers { watcher.fire(arg1, arg2, arg3) } } } } private class Observer3Args<L: AnyObject,A,B,C>: ObserverGenericBase<L> { let callback: (_ observer: L, _ arg1: A, _ arg2: B, _ arg3: C) -> () init(swignal: SwignalBase, observer: L, callback: @escaping (_ observer: L, _ arg1: A, _ arg2: B, _ arg3: C) -> ()) { self.callback = callback super.init(swignal: swignal, observer: observer) } override func fire(_ args: Any...) { if let arg1 = args[0] as? A, let arg2 = args[1] as? B, let arg3 = args[2] as? C { fire(arg1: arg1, arg2: arg2, arg3: arg3) } else { assert(false, "Types incorrect") } } fileprivate func fire(arg1: A, arg2: B, arg3: C) { if let observer = observer { callback(observer, arg1, arg2, arg3) } } }
mit
74fe22e3097e46221927349ab3588126
28.09434
132
0.549287
3.301927
false
false
false
false
iadmir/Signal-iOS
Signal/src/call/SignalCall.swift
1
6260
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation enum CallState: String { case idle case dialing case answering case remoteRinging case localRinging case connected case localFailure // terminal case localHangup // terminal case remoteHangup // terminal case remoteBusy // terminal } enum CallDirection { case outgoing, incoming } // All Observer methods will be invoked from the main thread. protocol CallObserver: class { func stateDidChange(call: SignalCall, state: CallState) func hasLocalVideoDidChange(call: SignalCall, hasLocalVideo: Bool) func muteDidChange(call: SignalCall, isMuted: Bool) func audioSourceDidChange(call: SignalCall, audioSource: AudioSource?) } /** * Data model for a WebRTC backed voice/video call. * * This class' state should only be accessed on the main queue. */ @objc class SignalCall: NSObject { let TAG = "[SignalCall]" var observers = [Weak<CallObserver>]() let remotePhoneNumber: String // Signal Service identifier for this Call. Used to coordinate the call across remote clients. let signalingId: UInt64 let direction: CallDirection // Distinguishes between calls locally, e.g. in CallKit let localId: UUID let thread: TSContactThread var callRecord: TSCall? { didSet { AssertIsOnMainThread() assert(oldValue == nil) updateCallRecordType() } } var hasLocalVideo = false { didSet { AssertIsOnMainThread() for observer in observers { observer.value?.hasLocalVideoDidChange(call: self, hasLocalVideo: hasLocalVideo) } } } var state: CallState { didSet { AssertIsOnMainThread() Logger.debug("\(TAG) state changed: \(oldValue) -> \(self.state) for call: \(self.identifiersForLogs)") // Update connectedDate if self.state == .connected { if connectedDate == nil { connectedDate = NSDate() } } else { connectedDate = nil } updateCallRecordType() for observer in observers { observer.value?.stateDidChange(call: self, state: state) } } } var isMuted = false { didSet { AssertIsOnMainThread() Logger.debug("\(TAG) muted changed: \(oldValue) -> \(self.isMuted)") for observer in observers { observer.value?.muteDidChange(call: self, isMuted: isMuted) } } } var audioSource: AudioSource? = nil { didSet { AssertIsOnMainThread() Logger.debug("\(TAG) audioSource changed: \(String(describing:oldValue)) -> \(String(describing: audioSource))") for observer in observers { observer.value?.audioSourceDidChange(call: self, audioSource: audioSource) } } } var isSpeakerphoneEnabled: Bool { guard let audioSource = self.audioSource else { return false } return audioSource.isBuiltInSpeaker } var isOnHold = false var connectedDate: NSDate? var error: CallError? // MARK: Initializers and Factory Methods init(direction: CallDirection, localId: UUID, signalingId: UInt64, state: CallState, remotePhoneNumber: String) { self.direction = direction self.localId = localId self.signalingId = signalingId self.state = state self.remotePhoneNumber = remotePhoneNumber self.thread = TSContactThread.getOrCreateThread(contactId: remotePhoneNumber) } // A string containing the three identifiers for this call. var identifiersForLogs: String { return "{\(remotePhoneNumber), \(localId), \(signalingId)}" } class func outgoingCall(localId: UUID, remotePhoneNumber: String) -> SignalCall { return SignalCall(direction: .outgoing, localId: localId, signalingId: newCallSignalingId(), state: .dialing, remotePhoneNumber: remotePhoneNumber) } class func incomingCall(localId: UUID, remotePhoneNumber: String, signalingId: UInt64) -> SignalCall { return SignalCall(direction: .incoming, localId: localId, signalingId: signalingId, state: .answering, remotePhoneNumber: remotePhoneNumber) } // - func addObserverAndSyncState(observer: CallObserver) { AssertIsOnMainThread() observers.append(Weak(value: observer)) // Synchronize observer with current call state observer.stateDidChange(call: self, state: state) } func removeObserver(_ observer: CallObserver) { AssertIsOnMainThread() while let index = observers.index(where: { $0.value === observer }) { observers.remove(at: index) } } func removeAllObservers() { AssertIsOnMainThread() observers = [] } private func updateCallRecordType() { AssertIsOnMainThread() guard let callRecord = self.callRecord else { return } // Mark incomplete calls as completed if call has connected. if state == .connected && callRecord.callType == RPRecentCallTypeOutgoingIncomplete { callRecord.updateCallType(RPRecentCallTypeOutgoing) } if state == .connected && callRecord.callType == RPRecentCallTypeIncomingIncomplete { callRecord.updateCallType(RPRecentCallTypeIncoming) } } // MARK: Equatable static func == (lhs: SignalCall, rhs: SignalCall) -> Bool { return lhs.localId == rhs.localId } static func newCallSignalingId() -> UInt64 { return UInt64.ows_random() } // This method should only be called when the call state is "connected". func connectionDuration() -> TimeInterval { return -connectedDate!.timeIntervalSinceNow } } fileprivate extension UInt64 { static func ows_random() -> UInt64 { var random: UInt64 = 0 arc4random_buf(&random, MemoryLayout.size(ofValue: random)) return random } }
gpl-3.0
c28ad9ed9bb63ab3dc6bcaf9ed54dbb7
27.198198
155
0.630192
5.085297
false
false
false
false
dduan/swift
stdlib/public/core/Builtin.swift
1
18278
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import SwiftShims // Definitions that make elements of Builtin usable in real code // without gobs of boilerplate. /// An initialized raw pointer to use as a NULL value. @_transparent internal var _nilRawPointer: Builtin.RawPointer { let zero: Int8 = 0 return Builtin.inttoptr_Int8(zero._value) } /// Returns the contiguous memory footprint of `T`. /// /// Does not include any dynamically-allocated or "remote" storage. /// In particular, `sizeof(X.self)`, when `X` is a class type, is the /// same regardless of how many stored properties `X` has. @_transparent @warn_unused_result public func sizeof<T>(_:T.Type) -> Int { return Int(Builtin.sizeof(T.self)) } /// Returns the contiguous memory footprint of `T`. /// /// Does not include any dynamically-allocated or "remote" storage. /// In particular, `sizeof(a)`, when `a` is a class instance, is the /// same regardless of how many stored properties `a` has. @_transparent @warn_unused_result public func sizeofValue<T>(_:T) -> Int { return sizeof(T.self) } /// Returns the minimum memory alignment of `T`. @_transparent @warn_unused_result public func alignof<T>(_:T.Type) -> Int { return Int(Builtin.alignof(T.self)) } /// Returns the minimum memory alignment of `T`. @_transparent @warn_unused_result public func alignofValue<T>(_:T) -> Int { return alignof(T.self) } /// Returns the least possible interval between distinct instances of /// `T` in memory. The result is always positive. @_transparent @warn_unused_result public func strideof<T>(_:T.Type) -> Int { return Int(Builtin.strideof_nonzero(T.self)) } /// Returns the least possible interval between distinct instances of /// `T` in memory. The result is always positive. @_transparent @warn_unused_result public func strideofValue<T>(_:T) -> Int { return strideof(T.self) } @warn_unused_result internal func _roundUp(offset: Int, toAlignment alignment: Int) -> Int { _sanityCheck(offset >= 0) _sanityCheck(alignment > 0) _sanityCheck(_isPowerOf2(alignment)) // Note, given that offset is >= 0, and alignment > 0, we don't // need to underflow check the -1, as it can never underflow. let x = (offset + alignment &- 1) // Note, as alignment is a power of 2, we'll use masking to efficiently // get the aligned value return x & ~(alignment &- 1) } /// Returns a tri-state of 0 = no, 1 = yes, 2 = maybe. @_transparent @warn_unused_result public // @testable func _canBeClass<T>(_: T.Type) -> Int8 { return Int8(Builtin.canBeClass(T.self)) } /// Returns the bits of `x`, interpreted as having type `U`. /// /// - Warning: Breaks the guarantees of Swift's type system; use /// with extreme care. There's almost always a better way to do /// anything. /// @_transparent @warn_unused_result public func unsafeBitCast<T, U>(x: T, to: U.Type) -> U { _precondition(sizeof(T.self) == sizeof(U.self), "can't unsafeBitCast between types of different sizes") return Builtin.reinterpretCast(x) } /// `unsafeBitCast` something to `AnyObject`. @_transparent @warn_unused_result public func _reinterpretCastToAnyObject<T>(x: T) -> AnyObject { return unsafeBitCast(x, to: AnyObject.self) } @_transparent @warn_unused_result func ==(lhs: Builtin.NativeObject, rhs: Builtin.NativeObject) -> Bool { return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self) } @_transparent @warn_unused_result func !=(lhs: Builtin.NativeObject, rhs: Builtin.NativeObject) -> Bool { return !(lhs == rhs) } @_transparent @warn_unused_result func ==(lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool { return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self) } @_transparent @warn_unused_result func !=(lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool { return !(lhs == rhs) } /// Returns `true` iff `t0` is identical to `t1`; i.e. if they are both /// `nil` or they both represent the same type. @warn_unused_result public func == (t0: Any.Type?, t1: Any.Type?) -> Bool { return unsafeBitCast(t0, to: Int.self) == unsafeBitCast(t1, to: Int.self) } /// Returns `false` iff `t0` is identical to `t1`; i.e. if they are both /// `nil` or they both represent the same type. @warn_unused_result public func != (t0: Any.Type?, t1: Any.Type?) -> Bool { return !(t0 == t1) } /// Tell the optimizer that this code is unreachable if condition is /// known at compile-time to be true. If condition is false, or true /// but not a compile-time constant, this call has no effect. @_transparent internal func _unreachable(condition: Bool = true) { if condition { // FIXME: use a parameterized version of Builtin.unreachable when // <rdar://problem/16806232> is closed. Builtin.unreachable() } } /// Tell the optimizer that this code is unreachable if this builtin is /// reachable after constant folding build configuration builtins. @_transparent @noreturn internal func _conditionallyUnreachable() { Builtin.conditionallyUnreachable() } @warn_unused_result @_silgen_name("swift_isClassOrObjCExistentialType") func _swift_isClassOrObjCExistentialType<T>(x: T.Type) -> Bool /// Returns `true` iff `T` is a class type or an `@objc` existential such as /// `AnyObject`. @inline(__always) @warn_unused_result internal func _isClassOrObjCExistential<T>(x: T.Type) -> Bool { let tmp = _canBeClass(x) // Is not a class. if tmp == 0 { return false // Is a class. } else if tmp == 1 { return true } // Maybe a class. return _swift_isClassOrObjCExistentialType(x) } /// Returns an `UnsafePointer` to the storage used for `object`. There's /// not much you can do with this other than use it to identify the /// object. @_transparent @warn_unused_result public func unsafeAddress(of object: AnyObject) -> UnsafePointer<Void> { return UnsafePointer(Builtin.bridgeToRawPointer(object)) } @available(*, unavailable, renamed: "unsafeAddress(of:)") public func unsafeAddressOf(object: AnyObject) -> UnsafePointer<Void> { fatalError("unavailable function can't be called") } /// Converts a reference of type `T` to a reference of type `U` after /// unwrapping one level of Optional. /// /// Unwrapped `T` and `U` must be convertible to AnyObject. They may /// be either a class or a class protocol. Either T, U, or both may be /// optional references. @_transparent @warn_unused_result public func _unsafeReferenceCast<T, U>(x: T, to: U.Type) -> U { return Builtin.castReference(x) } /// - returns: `x as T`. /// /// - Precondition: `x is T`. In particular, in -O builds, no test is /// performed to ensure that `x` actually has dynamic type `T`. /// /// - Warning: Trades safety for performance. Use `unsafeDowncast` /// only when `x as T` has proven to be a performance problem and you /// are confident that, always, `x is T`. It is better than an /// `unsafeBitCast` because it's more restrictive, and because /// checking is still performed in debug builds. @_transparent @warn_unused_result public func unsafeDowncast<T : AnyObject>(x: AnyObject, to: T.Type) -> T { _debugPrecondition(x is T, "invalid unsafeDowncast") return Builtin.castReference(x) } @inline(__always) @warn_unused_result public func _getUnsafePointerToStoredProperties(x: AnyObject) -> UnsafeMutablePointer<UInt8> { let storedPropertyOffset = _roundUp( sizeof(_HeapObject.self), toAlignment: alignof(Optional<AnyObject>.self)) return UnsafeMutablePointer<UInt8>(Builtin.bridgeToRawPointer(x)) + storedPropertyOffset } //===----------------------------------------------------------------------===// // Branch hints //===----------------------------------------------------------------------===// // Use @_semantics to indicate that the optimizer recognizes the // semantics of these function calls. This won't be necessary with // mandatory generic inlining. @_transparent @_semantics("branchhint") @warn_unused_result internal func _branchHint<C : Boolean>(actual: C, expected: Bool) -> Bool { return Bool(Builtin.int_expect_Int1(actual.boolValue._value, expected._value)) } /// Optimizer hint that `x` is expected to be `true`. @_transparent @_semantics("fastpath") @warn_unused_result public func _fastPath<C: Boolean>(x: C) -> Bool { return _branchHint(x.boolValue, expected: true) } /// Optimizer hint that `x` is expected to be `false`. @_transparent @_semantics("slowpath") @warn_unused_result public func _slowPath<C : Boolean>(x: C) -> Bool { return _branchHint(x.boolValue, expected: false) } //===--- Runtime shim wrappers --------------------------------------------===// /// Returns `true` iff the class indicated by `theClass` uses native /// Swift reference-counting. @inline(__always) @warn_unused_result internal func _usesNativeSwiftReferenceCounting(theClass: AnyClass) -> Bool { #if _runtime(_ObjC) return swift_objc_class_usesNativeSwiftReferenceCounting( unsafeAddress(of: theClass) ) #else return true #endif } @warn_unused_result @_silgen_name("swift_class_getInstanceExtents") func swift_class_getInstanceExtents(theClass: AnyClass) -> (negative: UInt, positive: UInt) @warn_unused_result @_silgen_name("swift_objc_class_unknownGetInstanceExtents") func swift_objc_class_unknownGetInstanceExtents(theClass: AnyClass) -> (negative: UInt, positive: UInt) /// - Returns: @inline(__always) @warn_unused_result internal func _class_getInstancePositiveExtentSize(theClass: AnyClass) -> Int { #if _runtime(_ObjC) return Int(swift_objc_class_unknownGetInstanceExtents(theClass).positive) #else return Int(swift_class_getInstanceExtents(theClass).positive) #endif } //===--- Builtin.BridgeObject ---------------------------------------------===// #if arch(i386) || arch(arm) internal var _objectPointerSpareBits: UInt { @inline(__always) get { return 0x0000_0003 } } internal var _objectPointerIsObjCBit: UInt { @inline(__always) get { return 0x0000_0002 } } internal var _objectPointerLowSpareBitShift: UInt { @inline(__always) get { return 0 } } internal var _objCTaggedPointerBits: UInt { @inline(__always) get { return 0 } } #elseif arch(x86_64) internal var _objectPointerSpareBits: UInt { @inline(__always) get { return 0x7F00_0000_0000_0006 } } internal var _objectPointerIsObjCBit: UInt { @inline(__always) get { return 0x4000_0000_0000_0000 } } internal var _objectPointerLowSpareBitShift: UInt { @inline(__always) get { return 1 } } internal var _objCTaggedPointerBits: UInt { @inline(__always) get { return 0x8000_0000_0000_0001 } } #elseif arch(arm64) internal var _objectPointerSpareBits: UInt { @inline(__always) get { return 0x7F00_0000_0000_0007 } } internal var _objectPointerIsObjCBit: UInt { @inline(__always) get { return 0x4000_0000_0000_0000 } } internal var _objectPointerLowSpareBitShift: UInt { @inline(__always) get { return 0 } } internal var _objCTaggedPointerBits: UInt { @inline(__always) get { return 0x8000_0000_0000_0000 } } #elseif arch(powerpc64) || arch(powerpc64le) internal var _objectPointerSpareBits: UInt { @inline(__always) get { return 0x0000_0000_0000_0007 } } internal var _objectPointerIsObjCBit: UInt { @inline(__always) get { return 0x0000_0000_0000_0002 } } internal var _objectPointerLowSpareBitShift: UInt { @inline(__always) get { return 0 } } internal var _objCTaggedPointerBits: UInt { @inline(__always) get { return 0 } } #endif /// Extract the raw bits of `x`. @inline(__always) @warn_unused_result internal func _bitPattern(x: Builtin.BridgeObject) -> UInt { return UInt(Builtin.castBitPatternFromBridgeObject(x)) } /// Extract the raw spare bits of `x`. @inline(__always) @warn_unused_result internal func _nonPointerBits(x: Builtin.BridgeObject) -> UInt { return _bitPattern(x) & _objectPointerSpareBits } @inline(__always) @warn_unused_result internal func _isObjCTaggedPointer(x: AnyObject) -> Bool { return (Builtin.reinterpretCast(x) & _objCTaggedPointerBits) != 0 } /// Create a `BridgeObject` around the given `nativeObject` with the /// given spare bits. /// /// Reference-counting and other operations on this /// object will have access to the knowledge that it is native. /// /// - Precondition: `bits & _objectPointerIsObjCBit == 0`, /// `bits & _objectPointerSpareBits == bits`. @inline(__always) @warn_unused_result internal func _makeNativeBridgeObject( nativeObject: AnyObject, _ bits: UInt ) -> Builtin.BridgeObject { _sanityCheck( (bits & _objectPointerIsObjCBit) == 0, "BridgeObject is treated as non-native when ObjC bit is set" ) return _makeBridgeObject(nativeObject, bits) } /// Create a `BridgeObject` around the given `objCObject`. @inline(__always) @warn_unused_result public // @testable func _makeObjCBridgeObject( objCObject: AnyObject ) -> Builtin.BridgeObject { return _makeBridgeObject( objCObject, _isObjCTaggedPointer(objCObject) ? 0 : _objectPointerIsObjCBit) } /// Create a `BridgeObject` around the given `object` with the /// given spare bits. /// /// - Precondition: /// /// 1. `bits & _objectPointerSpareBits == bits` /// 2. if `object` is a tagged pointer, `bits == 0`. Otherwise, /// `object` is either a native object, or `bits == /// _objectPointerIsObjCBit`. @inline(__always) @warn_unused_result internal func _makeBridgeObject( object: AnyObject, _ bits: UInt ) -> Builtin.BridgeObject { _sanityCheck(!_isObjCTaggedPointer(object) || bits == 0, "Tagged pointers cannot be combined with bits") _sanityCheck( _isObjCTaggedPointer(object) || _usesNativeSwiftReferenceCounting(object.dynamicType) || bits == _objectPointerIsObjCBit, "All spare bits must be set in non-native, non-tagged bridge objects" ) _sanityCheck( bits & _objectPointerSpareBits == bits, "Can't store non-spare bits into Builtin.BridgeObject") return Builtin.castToBridgeObject( object, bits._builtinWordValue ) } /// Returns the superclass of `t`, if any. The result is `nil` if `t` is /// a root class or class protocol. @inline(__always) @warn_unused_result public // @testable func _getSuperclass(t: AnyClass) -> AnyClass? { return unsafeBitCast( swift_class_getSuperclass(unsafeBitCast(t, to: OpaquePointer.self)), to: AnyClass.self) } /// Returns the superclass of `t`, if any. The result is `nil` if `t` is /// not a class, is a root class, or is a class protocol. @inline(__always) @warn_unused_result public // @testable func _getSuperclass(t: Any.Type) -> AnyClass? { return (t as? AnyClass).flatMap { _getSuperclass($0) } } //===--- Builtin.IsUnique -------------------------------------------------===// // _isUnique functions must take an inout object because they rely on // Builtin.isUnique which requires an inout reference to preserve // source-level copies in the presence of ARC optimization. // // Taking an inout object makes sense for two additional reasons: // // 1. You should only call it when about to mutate the object. // Doing so otherwise implies a race condition if the buffer is // shared across threads. // // 2. When it is not an inout function, self is passed by // value... thus bumping the reference count and disturbing the // result we are trying to observe, Dr. Heisenberg! // // _isUnique and _isUniquePinned cannot be made public or the compiler // will attempt to generate generic code for the transparent function // and type checking will fail. /// Returns `true` if `object` is uniquely referenced. @_transparent @warn_unused_result internal func _isUnique<T>(object: inout T) -> Bool { return Bool(Builtin.isUnique(&object)) } /// Returns `true` if `object` is uniquely referenced or pinned. @_transparent @warn_unused_result internal func _isUniqueOrPinned<T>(object: inout T) -> Bool { return Bool(Builtin.isUniqueOrPinned(&object)) } /// Returns `true` if `object` is uniquely referenced. /// This provides sanity checks on top of the Builtin. @_transparent @warn_unused_result public // @testable func _isUnique_native<T>(object: inout T) -> Bool { // This could be a bridge object, single payload enum, or plain old // reference. Any case it's non pointer bits must be zero, so // force cast it to BridgeObject and check the spare bits. _sanityCheck( (_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits) == 0) _sanityCheck(_usesNativeSwiftReferenceCounting( (Builtin.reinterpretCast(object) as AnyObject).dynamicType)) return Bool(Builtin.isUnique_native(&object)) } /// Returns `true` if `object` is uniquely referenced or pinned. /// This provides sanity checks on top of the Builtin. @_transparent @warn_unused_result public // @testable func _isUniqueOrPinned_native<T>(object: inout T) -> Bool { // This could be a bridge object, single payload enum, or plain old // reference. Any case it's non pointer bits must be zero. _sanityCheck( (_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits) == 0) _sanityCheck(_usesNativeSwiftReferenceCounting( (Builtin.reinterpretCast(object) as AnyObject).dynamicType)) return Bool(Builtin.isUniqueOrPinned_native(&object)) } /// Returns `true` if type is a POD type. A POD type is a type that does not /// require any special handling on copying or destruction. @_transparent @warn_unused_result public // @testable func _isPOD<T>(type: T.Type) -> Bool { return Bool(Builtin.ispod(type)) } /// Returns `true` if type is nominally an Optional type. @_transparent @warn_unused_result public // @testable func _isOptional<T>(type: T.Type) -> Bool { return Bool(Builtin.isOptional(type)) } @available(*, unavailable, message: "Removed in Swift 3. Please use Optional.unsafelyUnwrapped instead.") public func unsafeUnwrap<T>(nonEmpty: T?) -> T { fatalError("unavailable function can't be called") }
apache-2.0
7a66f2a3a9aa839917b1a14a5ad28777
31.066667
105
0.697341
3.897228
false
false
false
false
bradhowes/SynthInC
SynthInC/PhraseView.swift
1
2336
// // PhraseView.swift // SynthInC // // Created by Brad Howes on 6/16/16. // Copyright © 2016 Brad Howes. All rights reserved. // import AVFoundation import UIKit import SwiftMIDI /// Graphical depiction of what phrases have been played by an instrument. final class PhraseView : UIView { static let phraseColors: [CGColor] = { let phraseColorSaturation: CGFloat = 0.5 let phraseColorBrightness: CGFloat = 0.95 let phraseColorAlpha: CGFloat = 1.0 let hueGenerator: () -> CGFloat = { let inverseGoldenRatio: CGFloat = 1.0 / 1.6180339887498948482 var lastValue: CGFloat = 0.5 func nextValue() -> CGFloat { lastValue = (lastValue + inverseGoldenRatio).truncatingRemainder(dividingBy: 1.0) return lastValue } return nextValue }() return ScorePhrases.map { ($0, UIColor(hue: hueGenerator(), saturation: phraseColorSaturation, brightness: phraseColorBrightness, alpha: phraseColorAlpha).cgColor).1 } }() weak var part: Part! = nil var normalizedCurrentPosition: CGFloat = 0.0 /** Draw/update what phrases have been played by an instrument. - parameter rect: the area to update */ override func draw(_ rect: CGRect) { guard let cgc = UIGraphicsGetCurrentContext() else { return } // Draw color bands that show how long a performner stays in each phrase var lastX: CGFloat = 0.0 for (index, duration) in part.normalizedRunningDurations.enumerated() { let color = PhraseView.phraseColors[index] cgc.setFillColor(color) let x = duration * bounds.width let rect = CGRect(x: lastX, y: bounds.minY, width: x - lastX, height: bounds.height) lastX = x cgc.fill(rect) } // Draw indicator showing playback position cgc.setFillColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.5) let x = bounds.width * normalizedCurrentPosition let rect = CGRect(x: 0, y: bounds.minY + 2, width: x, height: bounds.height - 4) cgc.fill(rect) cgc.setFillColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 0.85) cgc.fill(CGRect(x: x - 2, y: bounds.minY + 2, width: 4, height: bounds.height - 4)) } }
mit
ae231b6f9edfa9e841e43e24d55c977e
35.484375
175
0.620557
4.067944
false
false
false
false
nathawes/swift
test/IRGen/generic_casts.swift
6
6056
// RUN: %empty-directory(%t) // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir -enable-objc-interop -disable-objc-attr-requires-foundation-module | %FileCheck %s // REQUIRES: CPU=x86_64 import Foundation import gizmo // -- Protocol records for cast-to ObjC protocols // CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto1_ = internal constant // CHECK: @"\01l_OBJC_LABEL_PROTOCOL_$__TtP13generic_casts10ObjCProto1_" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL__TtP13generic_casts10ObjCProto1_ to i8*), section {{"__DATA,__objc_protolist,coalesced,no_dead_strip"|"objc_protolist"|".objc_protolist\$B"}} // CHECK: @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP13generic_casts10ObjCProto1_" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL__TtP13generic_casts10ObjCProto1_ to i8*), section {{"__DATA,__objc_protorefs,coalesced,no_dead_strip"|"objc_protorefs"|".objc_protorefs\$B"}} // CHECK: @_PROTOCOL_NSRuncing = internal constant // CHECK: @"\01l_OBJC_LABEL_PROTOCOL_$_NSRuncing" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL_NSRuncing to i8*), section {{"__DATA,__objc_protolist,coalesced,no_dead_strip"|"objc_protolist"|".objc_protolist\$B"}} // CHECK: @"\01l_OBJC_PROTOCOL_REFERENCE_$_NSRuncing" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL_NSRuncing to i8*), section {{"__DATA,__objc_protorefs,coalesced,no_dead_strip"|"objc_protorefs"|".objc_protorefs\$B"}} // CHECK: @_PROTOCOLS__TtC13generic_casts10ObjCClass2 = internal constant { i64, [1 x i8*] } { // CHECK: i64 1, // CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto2_ // CHECK: } // CHECK: @_DATA__TtC13generic_casts10ObjCClass2 = internal constant {{.*}} @_PROTOCOLS__TtC13generic_casts10ObjCClass2 // CHECK: @_PROTOCOL_PROTOCOLS__TtP13generic_casts10ObjCProto2_ = internal constant { i64, [1 x i8*] } { // CHECK: i64 1, // CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto1_ // CHECK: } // CHECK: define hidden swiftcc i64 @"$s13generic_casts8allToIntySixlF"(%swift.opaque* noalias nocapture %0, %swift.type* %T) func allToInt<T>(_ x: T) -> Int { return x as! Int // CHECK: [[INT_TEMP:%.*]] = alloca %TSi, // CHECK: [[TYPE_ADDR:%.*]] = bitcast %swift.type* %T to i8*** // CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[TYPE_ADDR]], i64 -1 // CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK: [[VWT_CAST:%.*]] = bitcast i8** [[VWT]] to %swift.vwtable* // CHECK: [[SIZE_ADDR:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[VWT_CAST]], i32 0, i32 8 // CHECK: [[SIZE:%.*]] = load i64, i64* [[SIZE_ADDR]] // CHECK: [[T_ALLOCA:%.*]] = alloca i8, {{.*}} [[SIZE]], align 16 // CHECK: [[T_TMP:%.*]] = bitcast i8* [[T_ALLOCA]] to %swift.opaque* // CHECK: [[TEMP:%.*]] = call %swift.opaque* {{.*}}(%swift.opaque* noalias [[T_TMP]], %swift.opaque* noalias %0, %swift.type* %T) // CHECK: [[T0:%.*]] = bitcast %TSi* [[INT_TEMP]] to %swift.opaque* // CHECK: call i1 @swift_dynamicCast(%swift.opaque* [[T0]], %swift.opaque* [[T_TMP]], %swift.type* %T, %swift.type* @"$sSiN", i64 7) // CHECK: [[T0:%.*]] = getelementptr inbounds %TSi, %TSi* [[INT_TEMP]], i32 0, i32 0 // CHECK: [[INT_RESULT:%.*]] = load i64, i64* [[T0]], // CHECK: ret i64 [[INT_RESULT]] } // CHECK: define hidden swiftcc void @"$s13generic_casts8intToAllyxSilF"(%swift.opaque* noalias nocapture sret %0, i64 %1, %swift.type* %T) {{.*}} { func intToAll<T>(_ x: Int) -> T { // CHECK: [[INT_TEMP:%.*]] = alloca %TSi, // CHECK: [[T0:%.*]] = getelementptr inbounds %TSi, %TSi* [[INT_TEMP]], i32 0, i32 0 // CHECK: store i64 %1, i64* [[T0]], // CHECK: [[T0:%.*]] = bitcast %TSi* [[INT_TEMP]] to %swift.opaque* // CHECK: call i1 @swift_dynamicCast(%swift.opaque* %0, %swift.opaque* [[T0]], %swift.type* @"$sSiN", %swift.type* %T, i64 7) return x as! T } // CHECK: define hidden swiftcc i64 @"$s13generic_casts8anyToIntySiypF"(%Any* noalias nocapture dereferenceable({{.*}}) %0) {{.*}} { func anyToInt(_ x: Any) -> Int { return x as! Int } @objc protocol ObjCProto1 { static func forClass() static func forInstance() var prop: NSObject { get } } @objc protocol ObjCProto2 : ObjCProto1 {} @objc class ObjCClass {} // CHECK: define hidden swiftcc %objc_object* @"$s13generic_casts9protoCastyAA10ObjCProto1_So9NSRuncingpAA0E6CClassCF"(%T13generic_casts9ObjCClassC* %0) {{.*}} { func protoCast(_ x: ObjCClass) -> ObjCProto1 & NSRuncing { // CHECK: load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP13generic_casts10ObjCProto1_" // CHECK: load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$_NSRuncing" // CHECK: call %objc_object* @swift_dynamicCastObjCProtocolUnconditional(%objc_object* {{%.*}}, i64 2, i8** {{%.*}}) return x as! ObjCProto1 & NSRuncing } @objc class ObjCClass2 : NSObject, ObjCProto2 { class func forClass() {} class func forInstance() {} var prop: NSObject { return self } } // <rdar://problem/15313840> // Class existential to opaque archetype cast // CHECK: define hidden swiftcc void @"$s13generic_casts33classExistentialToOpaqueArchetypeyxAA10ObjCProto1_plF"(%swift.opaque* noalias nocapture sret %0, %objc_object* %1, %swift.type* %T) func classExistentialToOpaqueArchetype<T>(_ x: ObjCProto1) -> T { var x = x // CHECK: [[X:%.*]] = alloca %T13generic_casts10ObjCProto1P // CHECK: [[LOCAL:%.*]] = alloca %T13generic_casts10ObjCProto1P // CHECK: [[LOCAL_OPAQUE:%.*]] = bitcast %T13generic_casts10ObjCProto1P* [[LOCAL]] to %swift.opaque* // CHECK: [[PROTO_TYPE:%.*]] = call {{.*}}@"$s13generic_casts10ObjCProto1_pMD" // CHECK: call i1 @swift_dynamicCast(%swift.opaque* %0, %swift.opaque* [[LOCAL_OPAQUE]], %swift.type* [[PROTO_TYPE]], %swift.type* %T, i64 7) return x as! T } protocol P {} protocol Q {} // CHECK: define hidden swiftcc void @"$s13generic_casts19compositionToMemberyAA1P_pAaC_AA1QpF{{.*}}"(%T13generic_casts1PP* noalias nocapture sret %0, %T13generic_casts1P_AA1Qp* noalias nocapture dereferenceable({{.*}}) %1) {{.*}} { func compositionToMember(_ a: P & Q) -> P { return a }
apache-2.0
6f5757340451e4dc3c36ae8ead47995e
53.071429
270
0.658851
3.243706
false
false
false
false
davidbutz/ChristmasFamDuels
iOS/Boat Aware/StatusView.swift
1
1944
// // StatusView.swift // Boat Aware // // Created by Adam Douglass on 2/8/16. // Copyright © 2016 Thrive Engineering. All rights reserved. // import UIKit //@IBDesignable class StatusView: UIView { @IBOutlet private weak var statusLabel : UILabel! var deviceCapability: DeviceCapabilityNew? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() self.layoutIfNeeded() layer.cornerRadius = frame.width / 2.0 layer.masksToBounds = true // Based on Status, green/yellow/red if let thisDeviceCapability = deviceCapability { var color = UIColor.greenColor() switch (thisDeviceCapability.current_state_id) { case 1: color = UIColor.redColor() case 2: color = UIColor.yellowColor() case 5: color = UIColor.redColor() case 4: color = UIColor.yellowColor() default: //green2 (b6d7a8) color = UIColor(red: CGFloat(182.0/255.0), green: CGFloat(215.0/255.0), blue: CGFloat(168.0/255.0), alpha: CGFloat(1.0)) } self.backgroundColor = color self.layer.borderColor = color.darkerColor.CGColor self.layer.borderWidth = 2.0; if (deviceCapability?.current_value) != nil { statusLabel.text = String(thisDeviceCapability.current_value_string);//String(format: "%.2f", thisDeviceCapability.current_value); } } } // @IBInspectable var cornerRadius: CGFloat = 0 { // didSet { // layer.cornerRadius = cornerRadius // layer.masksToBounds = cornerRadius > 0 // } // } }
mit
657e796e888503346b1ae6d80ae83dcb
29.857143
146
0.544519
4.62619
false
false
false
false
practicalswift/swift
test/SILGen/guaranteed_normal_args.swift
6
8429
// RUN: %target-swift-emit-silgen -parse-as-library -module-name Swift -parse-stdlib %s | %FileCheck %s // This test checks specific codegen related to normal arguments being passed at // +0. Eventually, it should be merged into normal SILGen tests. ///////////////// // Fake Stdlib // ///////////////// precedencegroup AssignmentPrecedence { assignment: true } public protocol ExpressibleByNilLiteral { init(nilLiteral: ()) } protocol IteratorProtocol { associatedtype Element mutating func next() -> Element? } protocol Sequence { associatedtype Element associatedtype Iterator : IteratorProtocol where Iterator.Element == Element func makeIterator() -> Iterator } enum Optional<T> { case none case some(T) } extension Optional : ExpressibleByNilLiteral { public init(nilLiteral: ()) { self = .none } } func _diagnoseUnexpectedNilOptional(_filenameStart: Builtin.RawPointer, _filenameLength: Builtin.Word, _filenameIsASCII: Builtin.Int1, _line: Builtin.Word) { // This would usually contain an assert, but we don't need one since we are // just emitting SILGen. } class Klass { init() {} } struct Buffer { var k: Klass init(inK: Klass) { k = inK } } public typealias AnyObject = Builtin.AnyObject protocol Protocol { associatedtype AssocType static func useInput(_ input: Builtin.Int32, into processInput: (AssocType) -> ()) } struct FakeArray<Element> { // Just to make this type non-trivial var k: Klass // We are only interested in this being called. We are not interested in its // implementation. mutating func append(_ t: Element) {} } struct FakeDictionary<Key, Value> { } struct FakeDictionaryIterator<Key, Value> { var dictionary: FakeDictionary<Key, Value>? init(_ newDictionary: FakeDictionary<Key, Value>) { dictionary = newDictionary } } extension FakeDictionaryIterator : IteratorProtocol { public typealias Element = (Key, Value) public mutating func next() -> Element? { return .none } } extension FakeDictionary : Sequence { public typealias Element = (Key, Value) public typealias Iterator = FakeDictionaryIterator<Key, Value> public func makeIterator() -> FakeDictionaryIterator<Key, Value> { return FakeDictionaryIterator(self) } } public struct Unmanaged<Instance : AnyObject> { internal unowned(unsafe) var _value: Instance } /////////// // Tests // /////////// class KlassWithBuffer { var buffer: Buffer // Make sure that the allocating init forwards into the initializing init at +1. // CHECK-LABEL: sil hidden [ossa] @$ss15KlassWithBufferC3inKABs0A0C_tcfC : $@convention(method) (@owned Klass, @thick KlassWithBuffer.Type) -> @owned KlassWithBuffer { // CHECK: bb0([[ARG:%.*]] : @owned $Klass, // CHECK: [[INITIALIZING_INIT:%.*]] = function_ref @$ss15KlassWithBufferC3inKABs0A0C_tcfc : $@convention(method) (@owned Klass, @owned KlassWithBuffer) -> @owned KlassWithBuffer // CHECK: apply [[INITIALIZING_INIT]]([[ARG]], // CHECK: } // end sil function '$ss15KlassWithBufferC3inKABs0A0C_tcfC' init(inK: Klass = Klass()) { buffer = Buffer(inK: inK) } // This test makes sure that we: // // 1. Are able to propagate a +0 value value buffer.k into a +0 value and that // we then copy that +0 value into a +1 value, before we begin the epilog and // then return that value. // CHECK-LABEL: sil hidden [ossa] @$ss15KlassWithBufferC03getC14AsNativeObjectBoyF : $@convention(method) (@guaranteed KlassWithBuffer) -> @owned Builtin.NativeObject { // CHECK: bb0([[SELF:%.*]] : @guaranteed $KlassWithBuffer): // CHECK: [[METHOD:%.*]] = class_method [[SELF]] : $KlassWithBuffer, #KlassWithBuffer.buffer!getter.1 // CHECK: [[BUF:%.*]] = apply [[METHOD]]([[SELF]]) // CHECK: [[BUF_BORROW:%.*]] = begin_borrow [[BUF]] // CHECK: [[K:%.*]] = struct_extract [[BUF_BORROW]] : $Buffer, #Buffer.k // CHECK: [[COPIED_K:%.*]] = copy_value [[K]] // CHECK: end_borrow [[BUF_BORROW]] // CHECK: [[CASTED_COPIED_K:%.*]] = unchecked_ref_cast [[COPIED_K]] // CHECK: destroy_value [[BUF]] // CHECK: return [[CASTED_COPIED_K]] // CHECK: } // end sil function '$ss15KlassWithBufferC03getC14AsNativeObjectBoyF' func getBufferAsNativeObject() -> Builtin.NativeObject { return Builtin.unsafeCastToNativeObject(buffer.k) } } struct StructContainingBridgeObject { var rawValue: Builtin.BridgeObject // CHECK-LABEL: sil hidden [ossa] @$ss28StructContainingBridgeObjectV8swiftObjAByXl_tcfC : $@convention(method) (@owned AnyObject, @thin StructContainingBridgeObject.Type) -> @owned StructContainingBridgeObject { // CHECK: bb0([[ARG:%.*]] : @owned $AnyObject, // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[COPIED_ARG:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[CASTED_ARG:%.*]] = unchecked_ref_cast [[COPIED_ARG]] : $AnyObject to $Builtin.BridgeObject // CHECK: assign [[CASTED_ARG]] to // CHECK: } // end sil function '$ss28StructContainingBridgeObjectV8swiftObjAByXl_tcfC' init(swiftObj: AnyObject) { rawValue = Builtin.reinterpretCast(swiftObj) } } struct ReabstractionThunkTest : Protocol { typealias AssocType = Builtin.Int32 static func useInput(_ input: Builtin.Int32, into processInput: (AssocType) -> ()) { processInput(input) } } // Make sure that we provide a cleanup to x properly before we pass it to // result. extension FakeDictionary { // CHECK-LABEL: sil hidden [ossa] @$ss14FakeDictionaryV20makeSureToCopyTuplesyyF : $@convention(method) <Key, Value> (FakeDictionary<Key, Value>) -> () { // CHECK: [[X:%.*]] = alloc_stack $(Key, Value), let, name "x" // CHECK: [[INDUCTION_VAR:%.*]] = unchecked_take_enum_data_addr {{%.*}} : $*Optional<(Key, Value)>, #Optional.some!enumelt.1 // CHECK: [[INDUCTION_VAR_0:%.*]] = tuple_element_addr [[INDUCTION_VAR]] : $*(Key, Value), 0 // CHECK: [[INDUCTION_VAR_1:%.*]] = tuple_element_addr [[INDUCTION_VAR]] : $*(Key, Value), 1 // CHECK: [[X_0:%.*]] = tuple_element_addr [[X]] : $*(Key, Value), 0 // CHECK: [[X_1:%.*]] = tuple_element_addr [[X]] : $*(Key, Value), 1 // CHECK: copy_addr [take] [[INDUCTION_VAR_0]] to [initialization] [[X_0]] // CHECK: copy_addr [take] [[INDUCTION_VAR_1]] to [initialization] [[X_1]] // CHECK: [[X_0:%.*]] = tuple_element_addr [[X]] : $*(Key, Value), 0 // CHECK: [[X_1:%.*]] = tuple_element_addr [[X]] : $*(Key, Value), 1 // CHECK: [[TMP_X:%.*]] = alloc_stack $(Key, Value) // CHECK: [[TMP_X_0:%.*]] = tuple_element_addr [[TMP_X]] : $*(Key, Value), 0 // CHECK: [[TMP_X_1:%.*]] = tuple_element_addr [[TMP_X]] : $*(Key, Value), 1 // CHECK: [[TMP_0:%.*]] = alloc_stack $Key // CHECK: copy_addr [[X_0]] to [initialization] [[TMP_0]] // CHECK: copy_addr [take] [[TMP_0]] to [initialization] [[TMP_X_0]] // CHECK: [[TMP_1:%.*]] = alloc_stack $Value // CHECK: copy_addr [[X_1]] to [initialization] [[TMP_1]] // CHECK: copy_addr [take] [[TMP_1]] to [initialization] [[TMP_X_1]] // CHECK: [[FUNC:%.*]] = function_ref @$ss9FakeArrayV6appendyyxF : $@convention(method) <τ_0_0> (@in_guaranteed τ_0_0, @inout FakeArray<τ_0_0>) -> () // CHECK: apply [[FUNC]]<(Key, Value)>([[TMP_X]], // CHECK: } // end sil function '$ss14FakeDictionaryV20makeSureToCopyTuplesyyF' func makeSureToCopyTuples() { var result = FakeArray<Element>(k: Klass()) for x in self { result.append(x) } } } extension Unmanaged { // Just make sure that we do not crash on this. func unsafeGuaranteedTest<Result>( _ body: (Instance) -> Result ) -> Result { let (guaranteedInstance, token) = Builtin.unsafeGuaranteed(_value) let result = body(guaranteedInstance) Builtin.unsafeGuaranteedEnd(token) return result } } // Make sure that we properly forward x into memory and don't crash. public func forwardIntoMemory(fromNative x: AnyObject, y: Builtin.Word) -> Builtin.BridgeObject { // y would normally be 0._builtinWordValue. We don't want to define that // conformance. let object = Builtin.castToBridgeObject(x, y) return object } public struct StructWithOptionalAddressOnlyField<T> { public let newValue: T? } func useStructWithOptionalAddressOnlyField<T>(t: T) -> StructWithOptionalAddressOnlyField<T> { return StructWithOptionalAddressOnlyField<T>(newValue: t) }
apache-2.0
c85c2e5acf88f7b29d6b61fab07bf4dd
35.79476
214
0.657607
3.744889
false
false
false
false
apple/swift-driver
Sources/SwiftDriver/IncrementalCompilation/TwoDMap.swift
1
2696
//===---------------- TwoDMap.swift ---------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A map with 2 keys that can iterate in a number of ways public struct TwoDMap<Key1: Hashable, Key2: Hashable, Value: Equatable>: MutableCollection, Equatable { private var map1 = TwoLevelMap<Key1, Key2, Value>() private var map2 = TwoLevelMap<Key2, Key1, Value>() public typealias Key = (Key1, Key2) public typealias Element = (Key, Value) public typealias Index = TwoLevelMap<Key1, Key2, Value>.Index public init() {} public subscript(position: Index) -> Element { get { map1[position] } set { map1[newValue.0] = newValue.1 map2[(newValue.0.1, newValue.0.0)] = newValue.1 } } public subscript(key: Key) -> Value? { get { map1[key] } } public subscript(key: Key1) -> [Key2: Value]? { get { map1[key] } } public subscript(key: Key2) -> [Key1: Value]? { get { map2[key] } } public var startIndex: Index { map1.startIndex } public var endIndex: Index { map1.endIndex } public func index(after i: Index) -> Index { map1.index(after: i) } @discardableResult public mutating func updateValue(_ v: Value, forKey keys: (Key1, Key2)) -> Value? { let inserted1 = map1.updateValue(v, forKey: keys ) let inserted2 = map2.updateValue(v, forKey: (keys.1, keys.0)) assert(inserted1 == inserted2) return inserted1 } @discardableResult public mutating func removeValue(forKey keys: (Key1, Key2)) -> Value? { let v1 = map1.removeValue(forKey: keys ) let v2 = map2.removeValue(forKey: (keys.1, keys.0)) assert(v1 == v2) return v1 } /// Verify the integrity of each map and the cross-map consistency. /// Then call \p verifyFn for each entry found in each of the two maps, /// passing an index so that the verifyFn knows which map is being tested. @discardableResult public func verify(_ fn: ((Key1, Key2), Value, Int) -> Void) -> Bool { map1.forEach { (kv: ((Key1, Key2), Value)) in assert(kv.1 == map2[(kv.0.1, kv.0.0)]) fn(kv.0, kv.1, 0) } map2.forEach { (kv: ((Key2, Key1), Value)) in assert(kv.1 == map1[(kv.0.1, kv.0.0)]) fn((kv.0.1, kv.0.0), kv.1, 1) } return true } }
apache-2.0
332e355db0c13d119627bd246cc6e7ba
29.292135
103
0.606083
3.483204
false
false
false
false
fluidpixel/SwiftHN
SwiftHNToday/TodayViewController.swift
1
4686
// // TodayViewController.swift // SwiftHNTodayWidget // // Created by Thomas Ricouard on 18/06/14. // Copyright (c) 2014 Thomas Ricouard. All rights reserved. // import UIKit import NotificationCenter import HackerSwifter import SwiftHNShared class TodayViewController: UIViewController, NCWidgetProviding, UITableViewDelegate, UITableViewDataSource { let cellId = "widgetCellId" let topBottomWidgetInset: CGFloat = 10.0 var completionHandler: ((NCUpdateResult) -> Void)? var posts: [Post] = [] { didSet { self.tableView.reloadData() self.preferredContentSize = CGSizeMake(0, self.tableView.contentSize.height) } } var expanded: Bool = false { didSet { self.tableView.reloadData() self.preferredContentSize = CGSizeMake(0, self.tableView.contentSize.height) } } @IBOutlet var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.tableView.backgroundColor = UIColor.clearColor() Post.fetch(Post.PostFilter.Top, completion: {(posts: [Post]!, error: Fetcher.ResponseError!, local: Bool) in if let realDatasource = posts { self.posts = realDatasource self.completionHandler?(NCUpdateResult.NewData) } }) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.expanded = false } func widgetMarginInsetsForProposedMarginInsets(defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets { return UIEdgeInsetsMake(self.topBottomWidgetInset, 0, self.topBottomWidgetInset, 0) } func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) { self.completionHandler = completionHandler self.completionHandler?(NCUpdateResult.NewData) } //MARK: Actions func onViewMoreButton() { self.expanded = true } func onOpenApp() { self.extensionContext!.openURL(NSURL(string:"swifthn://")!, completionHandler: nil) } //MARK: TableView Management func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.expanded { return 7 } return self.posts.count > 5 ? 5 : self.posts.count } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 55.0 } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if self.expanded { return 0 } return 60.0 } func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { if self.expanded { return UIView(frame: CGRectZero) } var view = UIVisualEffectView(effect: UIVibrancyEffect.notificationCenterVibrancyEffect()) view.frame = CGRectMake(0, 0, self.tableView.frame.size.width, 30.0) var label = UILabel(frame: CGRectMake(48.0, 0, self.tableView.frame.size.width - 48.0, 30.0)) view.contentView.addSubview(label) label.numberOfLines = 0 label.textColor = UIColor.DateLighGrayColor() label.text = "See More..." label.userInteractionEnabled = true var tap = UITapGestureRecognizer(target: self, action: "onViewMoreButton") label.addGestureRecognizer(tap) var openApp = UILabel(frame: CGRectMake(48.0, 30.0, self.tableView.frame.size.width - 48.0, 30.0)) view.contentView.addSubview(openApp) openApp.numberOfLines = 0 openApp.textColor = UIColor.DateLighGrayColor() openApp.text = "Open SwiftHN" openApp.userInteractionEnabled = true var openAppTap = UITapGestureRecognizer(target: self, action: "onOpenApp") openApp.addGestureRecognizer(openAppTap) return view } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = self.tableView.dequeueReusableCellWithIdentifier(todayCellId) as? TodayWidgetCell var post = self.posts[indexPath.row] as Post cell!.post = post return cell! } func tableView(tableView: UITableView , didSelectRowAtIndexPath indexPath: NSIndexPath) { var post = self.posts[indexPath.row] as Post self.extensionContext!.openURL(post.url!, completionHandler: nil) } }
gpl-2.0
eab4ac50a99b5d931d9d3de6a92eedf2
33.20438
116
0.653436
4.974522
false
false
false
false
PekanMmd/Pokemon-XD-Code
Objects/data types/enumerable/CMTrainer.swift
1
6188
// // CMTrainer.swift // Colosseum Tool // // Created by The Steez on 04/06/2018. // import Foundation let kSizeOfTrainerData = 0x34 let kNumberOfTrainerPokemon = 0x06 let kNumberOfTrainerEntries = CommonIndexes.NumberOfTrainers.value // 820 let kTrainerGenderOffset = 0x00 let kTrainerClassOffset = 0x03 let kTrainerFirstPokemonOffset = 0x04 let kTrainerAIOffset = 0x06 let kTrainerNameIDOffset = 0x08 let kTrainerBattleTransitionOffset = 0x0C let kTrainerClassModelOffset = 0x13 let kTrainerPreBattleTextIDOffset = 0x24 let kTrainerVictoryTextIDOffset = 0x28 let kTrainerDefeatTextIDOffset = 0x2C let kFirstTrainerLoseText2Offset = 0x32 let kTrainerFirstItemOffset = 0x14 typealias TrainerInfo = (fullname:String,name:String,location:String,hasShadow: Bool,trainerModel:XGTrainerModels,index:Int, deck: XGDecks) final class XGTrainer: NSObject, Codable { var index = 0x0 var AI = 0 var cameraEffects = 0 // xd only var nameID = 0x0 var preBattleTextID = 0x0 var victoryTextID = 0x0 var defeatTextID = 0x0 var shadowMask = 0x0 var pokemon = [XGTrainerPokemon]() var trainerClass = XGTrainerClasses.none var trainerModel = XGTrainerModels.wes var items = [XGItems]() lazy var battleData: XGBattle? = { return XGBattle.battleForTrainer(index: self.index) }() var startOffset : Int { get { return CommonIndexes.Trainers.startOffset + (index * kSizeOfTrainerData) } } var name : XGString { get { return XGFiles.common_rel.stringTable.stringSafelyWithID(self.nameID) } } var isPlayer : Bool { return self.index == 1 } var prizeMoney : Int { get { var maxLevel = 0 for poke in self.pokemon { maxLevel = poke.level > maxLevel ? poke.level : maxLevel } return self.trainerClass.payout * 2 * maxLevel } } var hasShadow : Bool { get { for poke in self.pokemon { if poke.isShadowPokemon { return true } } return false } } var trainerInfo: TrainerInfo { return (self.trainerClass.name.string + " " + self.name.unformattedString, self.name.unformattedString,"",self.hasShadow,self.trainerModel,self.index, .DeckStory) } init(index: Int) { super.init() self.index = index let start = startOffset let deck = XGFiles.common_rel.data! self.nameID = deck.getWordAtOffset(start + kTrainerNameIDOffset).int self.preBattleTextID = deck.getWordAtOffset(start + kTrainerPreBattleTextIDOffset).int self.victoryTextID = deck.getWordAtOffset(start + kTrainerVictoryTextIDOffset).int self.defeatTextID = deck.getWordAtOffset(start + kTrainerDefeatTextIDOffset).int self.AI = deck.get2BytesAtOffset(start + kTrainerAIOffset) let tClass = deck.getByteAtOffset(start + kTrainerClassOffset) let tModel = deck.getByteAtOffset(start + kTrainerClassModelOffset) self.trainerClass = XGTrainerClasses(rawValue: tClass) ?? .none self.trainerModel = XGTrainerModels(rawValue: tModel) ?? .wes self.items = deck.getShortStreamFromOffset(start + kTrainerFirstItemOffset, length: 8).map({ (index) -> XGItems in return .index(index) }) let first = deck.get2BytesAtOffset(start + kTrainerFirstPokemonOffset) if first < CommonIndexes.NumberOfTrainerPokemonData.value { for i in 0 ..< kNumberOfTrainerPokemon { self.pokemon.append(XGTrainerPokemon(index: (first + i))) } } } func save() { let start = startOffset let deck = XGFiles.common_rel.data! deck.replaceWordAtOffset(start + kTrainerNameIDOffset, withBytes: UInt32(self.nameID)) deck.replaceWordAtOffset(start + kTrainerPreBattleTextIDOffset, withBytes: UInt32(self.preBattleTextID)) deck.replaceWordAtOffset(start + kTrainerVictoryTextIDOffset, withBytes: UInt32(self.victoryTextID)) deck.replaceWordAtOffset(start + kTrainerDefeatTextIDOffset, withBytes: UInt32(self.defeatTextID)) deck.replace2BytesAtOffset(start + kTrainerAIOffset, withBytes: self.AI) deck.replaceByteAtOffset(start + kTrainerClassOffset , withByte: self.trainerClass.rawValue) deck.replaceByteAtOffset(start + kTrainerClassModelOffset, withByte: self.trainerModel.rawValue) deck.replaceBytesFromOffset(start + kTrainerFirstItemOffset, withShortStream: items.map({ (item) -> Int in return item.index })) deck.save() } func purge(autoSave: Bool) { for poke in self.pokemon { poke.purge() if autoSave { poke.save() } } } var fullDescription : String { let trainerLength = 30 let pokemonLength = 20 var string = "" let className = self.trainerClass.name.unformattedString string += (className + " " + name.string).spaceToLength(trainerLength) + "\n\n" for p in pokemon { if p.isSet { string += ((p.isShadowPokemon ? "Shadow " : "") + p.species.name.string).spaceToLength(pokemonLength) } } string += "\n" for p in self.pokemon { if p.isSet { string += ("Level " + p.level.string).spaceToLength(pokemonLength) } } string += "\n" for p in pokemon { if p.isSet { if p.ability == 0xFF { string += "Random".spaceToLength(pokemonLength) } else { string += (p.ability == 0 ? p.species.ability1 : p.species.ability2).spaceToLength(pokemonLength) } } } string += "\n" for p in pokemon { if p.isSet { string += p.item.name.string.spaceToLength(pokemonLength) } } string += "\n" for i in 0 ..< 4 { for p in pokemon { if p.isSet { string += p.moves[i].name.string.spaceToLength(pokemonLength) } } string += "\n" } string += "\n" return string } } func allTrainers() -> [XGTrainer] { var trainers = [XGTrainer]() for i in 0 ..< kNumberOfTrainerEntries { trainers.append(XGTrainer(index: i)) } return trainers } extension XGTrainer: XGEnumerable { var enumerableName: String { return trainerClass.name.string + " " + name.string } var enumerableValue: String? { return String(format: "%03d", index) } static var className: String { return "Trainers" } static var allValues: [XGTrainer] { var values = [XGTrainer]() for i in 0 ..< CommonIndexes.NumberOfTrainers.value { values.append(XGTrainer(index: i)) } return values } }
gpl-2.0
1b46837383d217762b978e3d96b90c8a
24.465021
164
0.706044
3.145907
false
false
false
false
lionheart/LionheartExtensions
Pod/Classes/TitleButton.swift
1
3272
// // TitleButton.swift // LionheartExtensions // // Created by Dan Loewenherz on 4/10/18. // import Foundation public protocol TitleButtonThemeProtocol { static var normalColor: UIColor { get } static var highlightedColor: UIColor { get } static var subtitleColor: UIColor { get } } extension TitleButtonThemeProtocol { static var centeredParagraphStyle: NSParagraphStyle { let style = NSMutableParagraphStyle() style.setParagraphStyle(.default) style.alignment = .center return style } static var normalAttributes: [NSAttributedString.Key: Any] { return [ NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 17), NSAttributedString.Key.foregroundColor: Self.normalColor, NSAttributedString.Key.paragraphStyle: centeredParagraphStyle ] } static var highlightedAttributes: [NSAttributedString.Key: Any] { return [ NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 17), NSAttributedString.Key.foregroundColor: Self.highlightedColor, NSAttributedString.Key.paragraphStyle: centeredParagraphStyle ] } static var subtitleAttributes: [NSAttributedString.Key: Any] { return [ NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12), NSAttributedString.Key.foregroundColor: Self.subtitleColor, NSAttributedString.Key.paragraphStyle: centeredParagraphStyle ] } } public final class TitleButton<T>: UIButton where T: TitleButtonThemeProtocol { public var enableTitleCopy = false public override var canBecomeFirstResponder: Bool { return true } public override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { return enableTitleCopy && action == #selector(UIApplication.copy(_:)) } public override func copy(_ sender: Any?) { UIPasteboard.general.string = titleLabel?.text } @objc public convenience init() { self.init(frame: .zero) } } // MARK: - CustomButtonType extension TitleButton: CustomButtonType { public func setTitle(title: String) { setTitle(title: title, subtitle: nil) } public func setTitle(title: String, subtitle: String?) { let normalString = NSMutableAttributedString(string: title, attributes: T.normalAttributes) let highlightedString = NSMutableAttributedString(string: title, attributes: T.highlightedAttributes) if let subtitle = subtitle { normalString.append(NSAttributedString(string: "\n" + subtitle, attributes: T.subtitleAttributes)) highlightedString.append(NSAttributedString(string: "\n" + subtitle, attributes: T.subtitleAttributes)) titleLabel?.lineBreakMode = .byWordWrapping } else { titleLabel?.lineBreakMode = .byTruncatingTail } setAttributedTitle(normalString, for: .normal) setAttributedTitle(highlightedString, for: .highlighted) sizeToFit() } public func startAnimating() { fatalError() } public func stopAnimating() { fatalError() } }
apache-2.0
a5cd7d0de5aecec68568271ed908bfb2
31.39604
115
0.666565
5.268921
false
false
false
false
zmian/xcore.swift
Sources/Xcore/SwiftUI/Extensions/Label+Extensions.swift
1
2660
// // Xcore // Copyright © 2020 Xcore // MIT license, see LICENSE file for details // import SwiftUI // MARK: - SystemAssetIdentifier extension Label where Title == Text, Icon == Image { /// Creates a label with a system icon image and a title generated from a /// localized string. /// /// - Parameters: /// - titleKey: A title generated from a localized string. /// - systemImage: The name of the image resource to lookup. public init(_ titleKey: LocalizedStringKey, systemImage: SystemAssetIdentifier) { self.init(titleKey, systemImage: systemImage.rawValue) } /// Creates a label with a system icon image and a title generated from a /// string. /// /// - Parameters: /// - title: A string to used as the label's title. /// - systemImage: The name of the image resource to lookup. public init<S>(_ title: S, systemImage: SystemAssetIdentifier) where S: StringProtocol { self.init(title, systemImage: systemImage.rawValue) } } // MARK: - ImageAssetIdentifier extension Label where Title == Text, Icon == Image { /// Creates a label with an icon image and a title generated from a localized /// string. /// /// - Parameters: /// - titleKey: A title generated from a localized string. /// - image: The name of the image resource to lookup. public init(_ titleKey: LocalizedStringKey, image: ImageAssetIdentifier) { self.init(titleKey, image: Image(assetIdentifier: image)) } /// Creates a label with an icon image and a title generated from a string. /// /// - Parameters: /// - title: A string to used as the label's title. /// - image: The name of the image resource to lookup. public init<S>(_ title: S, image: ImageAssetIdentifier) where S: StringProtocol { self.init(title, image: Image(assetIdentifier: image)) } } // MARK: - Image extension Label where Title == Text, Icon == Image { /// Creates a label with an icon image and a title generated from a localized /// string. /// /// - Parameters: /// - titleKey: A title generated from a localized string. /// - image: The image. public init(_ titleKey: LocalizedStringKey, image: Image) { self.init { Text(titleKey) } icon: { image } } /// Creates a label with an icon image and a title generated from a string. /// /// - Parameters: /// - title: A string to used as the label's title. /// - image: The image. public init<S>(_ title: S, image: Image) where S: StringProtocol { self.init { Text(title) } icon: { image } } }
mit
2f4c40df7029a040400ea47600e54c74
33.532468
92
0.633697
4.240829
false
false
false
false
JoshAtTheDistance/TZStackView
TZStackViewDemo/ViewController.swift
6
8601
// // ViewController.swift // TZStackView-Example // // Created by Tom van Zummeren on 20/06/15. // Copyright (c) 2015 Tom van Zummeren. All rights reserved. // import UIKit import TZStackView class ViewController: UIViewController { //MARK: - Properties //-------------------------------------------------------------------------- var tzStackView: TZStackView! let resetButton = UIButton(type: .System) let instructionLabel = UILabel() var axisSegmentedControl: UISegmentedControl! var alignmentSegmentedControl: UISegmentedControl! var distributionSegmentedControl: UISegmentedControl! //MARK: - Lifecyle //-------------------------------------------------------------------------- override func viewDidLoad() { super.viewDidLoad() edgesForExtendedLayout = .None; view.backgroundColor = UIColor.blackColor() title = "TZStackView" tzStackView = TZStackView(arrangedSubviews: createViews()) tzStackView.translatesAutoresizingMaskIntoConstraints = false tzStackView.axis = .Vertical tzStackView.distribution = .Fill tzStackView.alignment = .Fill tzStackView.spacing = 15 view.addSubview(tzStackView) instructionLabel.translatesAutoresizingMaskIntoConstraints = false instructionLabel.font = UIFont.systemFontOfSize(15) instructionLabel.text = "Tap any of the boxes to set hidden=true" instructionLabel.textColor = UIColor.whiteColor() instructionLabel.numberOfLines = 0 instructionLabel.setContentCompressionResistancePriority(900, forAxis: .Horizontal) instructionLabel.setContentHuggingPriority(1000, forAxis: .Vertical) view.addSubview(instructionLabel) resetButton.translatesAutoresizingMaskIntoConstraints = false resetButton.setTitle("Reset", forState: .Normal) resetButton.addTarget(self, action: "reset", forControlEvents: .TouchUpInside) resetButton.setContentCompressionResistancePriority(1000, forAxis: .Horizontal) resetButton.setContentHuggingPriority(1000, forAxis: .Horizontal) resetButton.setContentHuggingPriority(1000, forAxis: .Vertical) view.addSubview(resetButton) axisSegmentedControl = UISegmentedControl(items: ["Vertical", "Horizontal"]) axisSegmentedControl.selectedSegmentIndex = 0 axisSegmentedControl.addTarget(self, action: "axisChanged:", forControlEvents: .ValueChanged) axisSegmentedControl.setContentCompressionResistancePriority(900, forAxis: .Horizontal) axisSegmentedControl.tintColor = UIColor.lightGrayColor() alignmentSegmentedControl = UISegmentedControl(items: ["Fill", "Center", "Leading", "Top", "Trailing", "Bottom", "FirstBaseline"]) alignmentSegmentedControl.selectedSegmentIndex = 0 alignmentSegmentedControl.addTarget(self, action: "alignmentChanged:", forControlEvents: .ValueChanged) alignmentSegmentedControl.setContentCompressionResistancePriority(1000, forAxis: .Horizontal) alignmentSegmentedControl.tintColor = UIColor.lightGrayColor() distributionSegmentedControl = UISegmentedControl(items: ["Fill", "FillEqually", "FillProportionally", "EqualSpacing", "EqualCentering"]) distributionSegmentedControl.selectedSegmentIndex = 0 distributionSegmentedControl.addTarget(self, action: "distributionChanged:", forControlEvents: .ValueChanged) distributionSegmentedControl.tintColor = UIColor.lightGrayColor() let controlsLayoutContainer = TZStackView(arrangedSubviews: [axisSegmentedControl, alignmentSegmentedControl, distributionSegmentedControl]) controlsLayoutContainer.axis = .Vertical controlsLayoutContainer.translatesAutoresizingMaskIntoConstraints = false controlsLayoutContainer.spacing = 5 controlsLayoutContainer.setContentHuggingPriority(1000, forAxis: .Vertical) view.addSubview(controlsLayoutContainer) let views: [String:AnyObject] = [ "instructionLabel": instructionLabel, "resetButton": resetButton, "tzStackView": tzStackView, "controlsLayoutContainer": controlsLayoutContainer ] let metrics: [String:AnyObject] = [ "gap": 10, "topspacing": 25 ] view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-gap-[instructionLabel]-[resetButton]-gap-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[tzStackView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[controlsLayoutContainer]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-topspacing-[instructionLabel]-gap-[controlsLayoutContainer]-gap-[tzStackView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views)) view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-topspacing-[resetButton]-gap-[controlsLayoutContainer]", options: NSLayoutFormatOptions(rawValue: 0), metrics: metrics, views: views)) } private func createViews() -> [UIView] { let redView = ExplicitIntrinsicContentSizeView(intrinsicContentSize: CGSize(width: 100, height: 100), name: "Red") let greenView = ExplicitIntrinsicContentSizeView(intrinsicContentSize: CGSize(width: 80, height: 80), name: "Green") let blueView = ExplicitIntrinsicContentSizeView(intrinsicContentSize: CGSize(width: 60, height: 60), name: "Blue") let purpleView = ExplicitIntrinsicContentSizeView(intrinsicContentSize: CGSize(width: 80, height: 80), name: "Purple") let yellowView = ExplicitIntrinsicContentSizeView(intrinsicContentSize: CGSize(width: 100, height: 100), name: "Yellow") redView.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.75) greenView.backgroundColor = UIColor.greenColor().colorWithAlphaComponent(0.75) blueView.backgroundColor = UIColor.blueColor().colorWithAlphaComponent(0.75) purpleView.backgroundColor = UIColor.purpleColor().colorWithAlphaComponent(0.75) yellowView.backgroundColor = UIColor.yellowColor().colorWithAlphaComponent(0.75) return [redView, greenView, blueView, purpleView, yellowView] } //MARK: - Button Actions //-------------------------------------------------------------------------- func reset() { UIView.animateWithDuration(0.6, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: .AllowUserInteraction, animations: { for view in self.tzStackView.arrangedSubviews { view.hidden = false } }, completion: nil) } //MARK: - Segmented Control Actions //-------------------------------------------------------------------------- func axisChanged(sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: tzStackView.axis = .Vertical default: tzStackView.axis = .Horizontal } } func alignmentChanged(sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: tzStackView.alignment = .Fill case 1: tzStackView.alignment = .Center case 2: tzStackView.alignment = .Leading case 3: tzStackView.alignment = .Top case 4: tzStackView.alignment = .Trailing case 5: tzStackView.alignment = .Bottom default: tzStackView.alignment = .FirstBaseline } tzStackView.setNeedsUpdateConstraints() } func distributionChanged(sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: tzStackView.distribution = .Fill case 1: tzStackView.distribution = .FillEqually case 2: tzStackView.distribution = .FillProportionally case 3: tzStackView.distribution = .EqualSpacing default: tzStackView.distribution = .EqualCentering } } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } }
mit
12639eb80e14d3ce4dc6e5395fddac25
46.005464
160
0.675038
5.899177
false
false
false
false
Darkkrye/DKDetailsParallax
DKDetailsParallax/Cells/RoundedTheme/RoundedButtonAnimationCell.swift
1
3954
// // RoundedButtonAnimationCell.swift // DKDetailsParallax // // Created by Tayeb Sedraia on 10/02/2017. // Copyright © 2017 Pierre BOUDON. All rights reserved. // import UIKit class RoundedButtonAnimationCell: UITableViewCell { struct DataBundle { static let bundle = Bundle.main } /// MARK: - Private Constants /// Cell default height public static let defaultHeight: CGFloat = 62 /// MARK: - Private Variables /// Cell primary color public var primaryColor = UIColor.black /// Cell secondary color public var secondaryColor = UIColor.white /// Cell page public var storyboardIDpage = "Vue" // MARK: - IBOutlets /// Button @IBOutlet weak var button: UIButton! /// MARK: - IBActions /// IBAction for button tapped /// /// - Parameter sender: Any - The button @IBAction func buttonTapped(_ sender: Any) { animateButton() } /// MARK: - "Default" Methods /// Override function awakeFromNib override func awakeFromNib() { super.awakeFromNib() } /// MARK: - Delegates /// MARK: - Personnal Delegates /// Complex constructor for the cell /// /// - Parameters: /// - withPrimaryColor: UIColor? - The primary color /// - andSecondaryColor: UIColor? - The secondary color /// - withPlainButton: Bool - If you want this item /// - Returns: RoundedButtonCell - The created cell open static func buttonCell(withPrimaryColor: UIColor?, andSecondaryColor: UIColor?, withStoryboardIDpage: String?) -> RoundedButtonAnimationCell { let nibs = DataBundle.bundle.loadNibNamed("RoundedButtonAnimationCell", owner: self, options: nil) let cell: RoundedButtonAnimationCell = nibs![0] as! RoundedButtonAnimationCell cell.selectionStyle = .none if let p = withPrimaryColor { cell.primaryColor = p } if let s = andSecondaryColor { cell.secondaryColor = s } if let v = withStoryboardIDpage { cell.storyboardIDpage = v } initialize(cell: cell) return cell } /// MARK: - Delegates /// MARK: - Personnal Delegates /// Initialize function for animation button /// /// - Parameter cell: nil func animateButton() { button.transform = CGAffineTransform(scaleX: 0.1, y: 0.1) /* Setup animation button */ UIView.animate(withDuration: 2.0, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 6.0, options: .allowUserInteraction, animations: { [weak self] in self?.button.transform = .identity }, completion: nil) DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: { /* Put your code which should be executed with a delay here */ let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let initViewController: UIViewController = storyBoard.instantiateViewController(withIdentifier: self.storyboardIDpage) self.window?.rootViewController? = initViewController }) } /// Initialize function for plain button /// /// - Parameter cell: RoundedButtonCell - The cell private static func initialize(cell: RoundedButtonAnimationCell) { /* Setup outlined button */ cell.button.layer.borderColor = cell.primaryColor.cgColor cell.button.layer.borderWidth = 1.0 cell.button.layer.cornerRadius = 15.0 cell.button.backgroundColor = cell.secondaryColor cell.button.setTitleColor(cell.primaryColor, for: .normal) } }
bsd-3-clause
1a5aa43236d91f3eb557da1b8d6e91da
28.94697
151
0.594485
5.16732
false
false
false
false
zeniuseducation/poly-euler
swift/fun-one.swift
1
818
func looperPrime (i : Int32, p : Int32) -> Bool { if (i*i) > p { return true } else if 0 == (p % i) { return false } else { return looperPrime (i + 2, p) } } func oddPrime (p : Int32) -> Bool { return looperPrime (3, p) } func looperSumPrimes (i : Int32, res : Int32, lim : Int32) -> Int32 { if i > lim { return res } else if oddPrime (i) { return looperSumPrimes (i+2, res+i, lim) } else { return looperSumPrimes (i+2,res, lim) } } func sumPrimes (lim : Int32) -> Int32 { return looperSumPrimes (3,2, lim) } var mdic = [Int : Int] () func funFact () -> Bool { var jika = mdic[123] if jika == nil { return true } else { return false } } func main () { let result = sumPrimes(2000000) println (result) } main()
epl-1.0
418ca2179adc43cba1358133c96587db
16.804348
69
0.547677
2.850174
false
false
false
false
nextforce/PhoneNumberKit
PhoneNumberKit/PhoneNumberKit.swift
1
7750
// // PhoneNumberKit.swift // PhoneNumberKit // // Created by Roy Marmelstein on 03/10/2015. // Copyright © 2015 Roy Marmelstein. All rights reserved. // import Foundation #if os(iOS) import CoreTelephony #endif public typealias MetadataCallback = (() throws -> Data?) public final class PhoneNumberKit: NSObject { // Manager objects let metadataManager: MetadataManager let parseManager: ParseManager let regexManager = RegexManager() // MARK: Lifecycle public init(metadataCallback: @escaping MetadataCallback = PhoneNumberKit.defaultMetadataCallback) { self.metadataManager = MetadataManager(metadataCallback: metadataCallback) self.parseManager = ParseManager(metadataManager: metadataManager, regexManager: regexManager) } // MARK: Parsing /// Parses a number string, used to create PhoneNumber objects. Throws. /// /// - Parameters: /// - numberString: the raw number string. /// - region: ISO 639 compliant region code. /// - ignoreType: Avoids number type checking for faster performance. /// - Returns: PhoneNumber object. public func parse(_ numberString: String, withRegion region: String = PhoneNumberKit.defaultRegionCode(), ignoreType: Bool = false) throws -> PhoneNumber { var numberStringWithPlus = numberString do { return try parseManager.parse(numberString, withRegion: region, ignoreType: ignoreType) } catch { if (numberStringWithPlus.first != "+") { numberStringWithPlus = "+" + numberStringWithPlus } } return try parseManager.parse(numberStringWithPlus, withRegion: region, ignoreType: ignoreType) } /// Parses an array of number strings. Optimised for performance. Invalid numbers are ignored in the resulting array /// /// - parameter numberStrings: array of raw number strings. /// - parameter region: ISO 639 compliant region code. /// - parameter ignoreType: Avoids number type checking for faster performance. /// /// - returns: array of PhoneNumber objects. public func parse(_ numberStrings: [String], withRegion region: String = PhoneNumberKit.defaultRegionCode(), ignoreType: Bool = false, shouldReturnFailedEmptyNumbers: Bool = false) -> [PhoneNumber] { return parseManager.parseMultiple(numberStrings, withRegion: region, ignoreType: ignoreType, shouldReturnFailedEmptyNumbers: shouldReturnFailedEmptyNumbers) } // MARK: Formatting /// Formats a PhoneNumber object for dispaly. /// /// - parameter phoneNumber: PhoneNumber object. /// - parameter formatType: PhoneNumberFormat enum. /// - parameter prefix: whether or not to include the prefix. /// /// - returns: Formatted representation of the PhoneNumber. public func format(_ phoneNumber: PhoneNumber, toType formatType: PhoneNumberFormat, withPrefix prefix: Bool = true) -> String { if formatType == .e164 { let formattedNationalNumber = phoneNumber.adjustedNationalNumber() if prefix == false { return formattedNationalNumber } return "+\(phoneNumber.countryCode)\(formattedNationalNumber)" } else { let formatter = Formatter(phoneNumberKit: self) let regionMetadata = metadataManager.mainTerritoryByCode[phoneNumber.countryCode] let formattedNationalNumber = formatter.format(phoneNumber: phoneNumber, formatType: formatType, regionMetadata: regionMetadata) if formatType == .international && prefix == true { return "+\(phoneNumber.countryCode) \(formattedNationalNumber)" } else { return formattedNationalNumber } } } // MARK: Country and region code /// Get a list of all the countries in the metadata database /// /// - returns: An array of ISO 639 compliant region codes. public func allCountries() -> [String] { let results = metadataManager.territories.map {$0.codeID} return results } /// Get an array of ISO 639 compliant region codes corresponding to a given country code. /// /// - parameter countryCode: international country code (e.g 44 for the UK). /// /// - returns: optional array of ISO 639 compliant region codes. public func countries(withCode countryCode: UInt64) -> [String]? { let results = metadataManager.filterTerritories(byCode: countryCode)?.map {$0.codeID} return results } /// Get an main ISO 639 compliant region code for a given country code. /// /// - parameter countryCode: international country code (e.g 1 for the US). /// /// - returns: ISO 639 compliant region code string. public func mainCountry(forCode countryCode: UInt64) -> String? { let country = metadataManager.mainTerritory(forCode: countryCode) return country?.codeID } /// Get an international country code for an ISO 639 compliant region code /// /// - parameter country: ISO 639 compliant region code. /// /// - returns: international country code (e.g. 33 for France). public func countryCode(for country: String) -> UInt64? { let results = metadataManager.filterTerritories(byCountry: country)?.countryCode return results } /// Get leading digits for an ISO 639 compliant region code. /// /// - parameter country: ISO 639 compliant region code. /// /// - returns: leading digits (e.g. 876 for Jamaica). public func leadingDigits(for country: String) -> String? { let leadingDigits = metadataManager.filterTerritories(byCountry: country)?.leadingDigits return leadingDigits } /// Determine the region code of a given phone number. /// /// - parameter phoneNumber: PhoneNumber object /// /// - returns: Region code, eg "US", or nil if the region cannot be determined. public func getRegionCode(of phoneNumber: PhoneNumber) -> String? { return parseManager.getRegionCode(of: phoneNumber.nationalNumber, countryCode: phoneNumber.countryCode, leadingZero: phoneNumber.leadingZero) } // MARK: Class functions /// Get a user's default region code /// /// - returns: A computed value for the user's current region - based on the iPhone's carrier and if not available, the device region. public class func defaultRegionCode() -> String { #if os(iOS) let networkInfo = CTTelephonyNetworkInfo() let carrier = networkInfo.subscriberCellularProvider if let isoCountryCode = carrier?.isoCountryCode { return isoCountryCode.uppercased() } #endif let currentLocale = Locale.current if #available(iOS 10.0, *), let countryCode = currentLocale.regionCode { return countryCode.uppercased() } else { if let countryCode = (currentLocale as NSLocale).object(forKey: .countryCode) as? String { return countryCode.uppercased() } } return PhoneNumberConstants.defaultCountry } /// Default metadta callback, reads metadata from PhoneNumberMetadata.json file in bundle /// /// - returns: an optional Data representation of the metadata. public static func defaultMetadataCallback() throws -> Data? { let frameworkBundle = Bundle(for: PhoneNumberKit.self) guard let jsonPath = frameworkBundle.path(forResource: "PhoneNumberMetadata", ofType: "json") else { throw PhoneNumberError.metadataNotFound } let data = try Data(contentsOf: URL(fileURLWithPath: jsonPath)) return data } }
mit
04f236413729d06b444f3879ca18a565
40.438503
203
0.671054
5.058094
false
false
false
false
apple/swift
test/Index/index_expressible_by_literals.swift
4
9720
// RUN: %target-swift-ide-test -print-indexed-symbols -source-filename %s | %FileCheck %s struct CustomInteger: ExpressibleByIntegerLiteral { init(integerLiteral: Int) {} } struct CustomFloat: ExpressibleByFloatLiteral { init(floatLiteral: Double) {} } struct CustomBool: ExpressibleByBooleanLiteral { init(booleanLiteral: Bool) {} } struct CustomNil: ExpressibleByNilLiteral { init(nilLiteral: ()) {} } struct CustomString: ExpressibleByStringLiteral { init(stringLiteral: StaticString) {} } struct CustomScalar: ExpressibleByUnicodeScalarLiteral { init(unicodeScalarLiteral: Unicode.Scalar) {} } struct CustomCharacter: ExpressibleByExtendedGraphemeClusterLiteral { init(extendedGraphemeClusterLiteral: Character) {} } struct CustomArray: ExpressibleByArrayLiteral { init(arrayLiteral: Int...) {} } struct CustomDictionary: ExpressibleByDictionaryLiteral { init(dictionaryLiteral: (Int, Int)...) {} } struct CustomInterpolation: ExpressibleByStringInterpolation { init(stringInterpolation: StringInterpolation) {} init(stringLiteral: String) {} } func customInteger() { // CHECK: [[@LINE+2]]:26 | constructor/Swift | init(integerLiteral:) | s:14swift_ide_test13CustomIntegerV14integerLiteralACSi_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customInteger() | s:14swift_ide_test13customIntegeryyF let _: CustomInteger = 100 // CHECK: [[@LINE+2]]:7 | constructor/Swift | init(integerLiteral:) | s:14swift_ide_test13CustomIntegerV14integerLiteralACSi_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customInteger() | s:14swift_ide_test13customIntegeryyF _ = 100 as CustomInteger // CHECK: [[@LINE+2]]:21 | constructor/Swift | init(integerLiteral:) | s:14swift_ide_test13CustomIntegerV14integerLiteralACSi_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customInteger() | s:14swift_ide_test13customIntegeryyF _ = CustomInteger(100) } func customFloat() { // CHECK: [[@LINE+2]]:24 | constructor/Swift | init(floatLiteral:) | s:14swift_ide_test11CustomFloatV12floatLiteralACSd_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customFloat() | s:14swift_ide_test11customFloatyyF let _: CustomFloat = -1.23 // CHECK: [[@LINE+2]]:7 | constructor/Swift | init(floatLiteral:) | s:14swift_ide_test11CustomFloatV12floatLiteralACSd_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customFloat() | s:14swift_ide_test11customFloatyyF _ = -1.23 as CustomFloat // CHECK: [[@LINE+2]]:19 | constructor/Swift | init(floatLiteral:) | s:14swift_ide_test11CustomFloatV12floatLiteralACSd_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customFloat() | s:14swift_ide_test11customFloatyyF _ = CustomFloat(-1.23) } func customBool() { // CHECK: [[@LINE+2]]:23 | constructor/Swift | init(booleanLiteral:) | s:14swift_ide_test10CustomBoolV14booleanLiteralACSb_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customBool() | s:14swift_ide_test10customBoolyyF let _: CustomBool = true // CHECK: [[@LINE+2]]:7 | constructor/Swift | init(booleanLiteral:) | s:14swift_ide_test10CustomBoolV14booleanLiteralACSb_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customBool() | s:14swift_ide_test10customBoolyyF _ = false as CustomBool // CHECK: [[@LINE+2]]:18 | constructor/Swift | init(booleanLiteral:) | s:14swift_ide_test10CustomBoolV14booleanLiteralACSb_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customBool() | s:14swift_ide_test10customBoolyyF _ = CustomBool(true) } func customNil() { // CHECK: [[@LINE+2]]:22 | constructor/Swift | init(nilLiteral:) | s:14swift_ide_test9CustomNilV10nilLiteralACyt_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customNil() | s:14swift_ide_test9customNilyyF let _: CustomNil = nil // CHECK: [[@LINE+2]]:7 | constructor/Swift | init(nilLiteral:) | s:14swift_ide_test9CustomNilV10nilLiteralACyt_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customNil() | s:14swift_ide_test9customNilyyF _ = nil as CustomNil } func customString() { // CHECK: [[@LINE+2]]:25 | constructor/Swift | init(stringLiteral:) | s:14swift_ide_test12CustomStringV13stringLiteralACs06StaticE0V_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customString() | s:14swift_ide_test12customStringyyF let _: CustomString = "abc" // CHECK: [[@LINE+2]]:7 | constructor/Swift | init(stringLiteral:) | s:14swift_ide_test12CustomStringV13stringLiteralACs06StaticE0V_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customString() | s:14swift_ide_test12customStringyyF _ = "abc" as CustomString // CHECK: [[@LINE+2]]:20 | constructor/Swift | init(stringLiteral:) | s:14swift_ide_test12CustomStringV13stringLiteralACs06StaticE0V_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customString() | s:14swift_ide_test12customStringyyF _ = CustomString("abc") } func customScalar() { // CHECK: [[@LINE+2]]:25 | constructor/Swift | init(unicodeScalarLiteral:) | s:14swift_ide_test12CustomScalarV07unicodeE7LiteralACs7UnicodeO0E0V_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customScalar() | s:14swift_ide_test12customScalaryyF let _: CustomScalar = "a" // CHECK: [[@LINE+2]]:7 | constructor/Swift | init(unicodeScalarLiteral:) | s:14swift_ide_test12CustomScalarV07unicodeE7LiteralACs7UnicodeO0E0V_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customScalar() | s:14swift_ide_test12customScalaryyF _ = "a" as CustomScalar // CHECK: [[@LINE+2]]:20 | constructor/Swift | init(unicodeScalarLiteral:) | s:14swift_ide_test12CustomScalarV07unicodeE7LiteralACs7UnicodeO0E0V_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customScalar() | s:14swift_ide_test12customScalaryyF _ = CustomScalar("a") } func customCharacter() { // CHECK: [[@LINE+2]]:28 | constructor/Swift | init(extendedGraphemeClusterLiteral:) | s:14swift_ide_test15CustomCharacterV30extendedGraphemeClusterLiteralACSJ_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customCharacter() | s:14swift_ide_test15customCharacteryyF let _: CustomCharacter = "a" // CHECK: [[@LINE+2]]:7 | constructor/Swift | init(extendedGraphemeClusterLiteral:) | s:14swift_ide_test15CustomCharacterV30extendedGraphemeClusterLiteralACSJ_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customCharacter() | s:14swift_ide_test15customCharacteryyF _ = "a" as CustomCharacter // CHECK: [[@LINE+2]]:23 | constructor/Swift | init(extendedGraphemeClusterLiteral:) | s:14swift_ide_test15CustomCharacterV30extendedGraphemeClusterLiteralACSJ_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customCharacter() | s:14swift_ide_test15customCharacteryyF _ = CustomCharacter("a") } func customArray() { // CHECK: [[@LINE+2]]:24 | constructor/Swift | init(arrayLiteral:) | s:14swift_ide_test11CustomArrayV12arrayLiteralACSid_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customArray() | s:14swift_ide_test11customArrayyyF let _: CustomArray = [1, 2, 3] // CHECK: [[@LINE+2]]:7 | constructor/Swift | init(arrayLiteral:) | s:14swift_ide_test11CustomArrayV12arrayLiteralACSid_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customArray() | s:14swift_ide_test11customArrayyyF _ = [1, 2, 3] as CustomArray } func customDictionary() { // CHECK: [[@LINE+2]]:29 | constructor/Swift | init(dictionaryLiteral:) | s:14swift_ide_test16CustomDictionaryV17dictionaryLiteralACSi_Sitd_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customDictionary() | s:14swift_ide_test16customDictionaryyyF let _: CustomDictionary = [1: 1, 2: 2, 3: 3] // CHECK: [[@LINE+2]]:7 | constructor/Swift | init(dictionaryLiteral:) | s:14swift_ide_test16CustomDictionaryV17dictionaryLiteralACSi_Sitd_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customDictionary() | s:14swift_ide_test16customDictionaryyyF _ = [1: 1, 2: 2, 3: 3] as CustomDictionary } func customInterpolation() { // CHECK: [[@LINE+2]]:32 | constructor/Swift | init(stringInterpolation:) | s:14swift_ide_test19CustomInterpolationV06stringE0ACs013DefaultStringE0V_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customInterpolation() | s:14swift_ide_test19customInterpolationyyF let _: CustomInterpolation = "a\(0)b" // CHECK: [[@LINE+2]]:7 | constructor/Swift | init(stringInterpolation:) | s:14swift_ide_test19CustomInterpolationV06stringE0ACs013DefaultStringE0V_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customInterpolation() | s:14swift_ide_test19customInterpolationyyF _ = "a\(0)b" as CustomInterpolation // CHECK: [[@LINE+2]]:27 | constructor/Swift | init(stringInterpolation:) | s:14swift_ide_test19CustomInterpolationV06stringE0ACs013DefaultStringE0V_tcfc | Ref,Call,Impl,RelCall,RelCont | // CHECK-NEXT: RelCall,RelCont | function/Swift | customInterpolation() | s:14swift_ide_test19customInterpolationyyF _ = CustomInterpolation("a\(0)b") }
apache-2.0
0c4a270b64cb3a2a9c6c7963ca1163b8
71
200
0.750823
3.390303
false
true
false
false
apple/swift
test/type/opaque.swift
2
19424
// RUN: %target-swift-frontend -disable-availability-checking -typecheck -verify %s protocol P { func paul() mutating func priscilla() } protocol Q { func quinn() } extension Int: P, Q { func paul() {}; mutating func priscilla() {}; func quinn() {} } extension String: P, Q { func paul() {}; mutating func priscilla() {}; func quinn() {} } extension Array: P, Q { func paul() {}; mutating func priscilla() {}; func quinn() {} } class C {} class D: C, P, Q { func paul() {}; func priscilla() {}; func quinn() {}; func d() {} } let property: some P = 1 let deflessLet: some P // expected-error{{has no initializer}} {{educational-notes=opaque-type-inference}} var deflessVar: some P // expected-error{{has no initializer}} struct GenericProperty<T: P> { var x: T var property: some P { return x } } let (bim, bam): some P = (1, 2) // expected-error{{'some' type can only be declared on a single property declaration}} var computedProperty: some P { get { return 1 } set { _ = newValue + 1 } // expected-error{{cannot convert value of type 'some P' to expected argument type 'Int'}} } struct SubscriptTest { subscript(_ x: Int) -> some P { return x } } func bar() -> some P { return 1 } func bas() -> some P & Q { return 1 } func zim() -> some C { return D() } func zang() -> some C & P & Q { return D() } func zung() -> some AnyObject { return D() } func zoop() -> some Any { return D() } func zup() -> some Any & P { return D() } func zip() -> some AnyObject & P { return D() } func zorp() -> some Any & C & P { return D() } func zlop() -> some C & AnyObject & P { return D() } // Don't allow opaque types to propagate by inference into other global decls' // types struct Test { let inferredOpaque = bar() // expected-error{{inferred type}} let inferredOpaqueStructural = Optional(bar()) // expected-error{{inferred type}} let inferredOpaqueStructural2 = (bar(), bas()) // expected-error{{inferred type}} } let zingle = {() -> some P in 1 } // expected-error{{'some' types are only permitted}} func twoOpaqueTypes() -> (some P, some P) { return (1, 2) } func asArrayElem() -> [some P] { return [1] } // Invalid positions typealias Foo = some P // expected-error{{'some' types are only permitted}} func blibble(blobble: some P) {} func blib() -> P & some Q { return 1 } // expected-error{{'some' should appear at the beginning}} func blab() -> some P? { return 1 } // expected-error{{must specify only}} expected-note{{did you mean to write an optional of an 'opaque' type?}} func blorb<T: some P>(_: T) { } // expected-error{{'some' types are only permitted}} func blub<T>() -> T where T == some P { return 1 } // expected-error{{'some' types are only permitted}} protocol OP: some P {} // expected-error{{'some' types are only permitted}} func foo() -> some P { let x = (some P).self // expected-error*{{}} return 1 } // Invalid constraints let zug: some Int = 1 // FIXME expected-error{{must specify only}} let zwang: some () = () // FIXME expected-error{{must specify only}} let zwoggle: some (() -> ()) = {} // FIXME expected-error{{must specify only}} // Type-checking of expressions of opaque type func alice() -> some P { return 1 } func bob() -> some P { return 1 } func grace<T: P>(_ x: T) -> some P { return x } func typeIdentity() { do { var a = alice() a = alice() a = bob() // expected-error{{}} a = grace(1) // expected-error{{}} a = grace("two") // expected-error{{}} } do { var af = alice af = alice af = bob // expected-error{{}} af = grace // expected-error{{generic parameter 'T' could not be inferred}} // expected-error@-1 {{cannot assign value of type '(T) -> some P' to type '() -> some P'}} } do { var b = bob() b = alice() // expected-error{{}} b = bob() b = grace(1) // expected-error{{}} b = grace("two") // expected-error{{}} } do { var gi = grace(1) gi = alice() // expected-error{{}} gi = bob() // expected-error{{}} gi = grace(2) gi = grace("three") // expected-error{{}} } do { var gs = grace("one") gs = alice() // expected-error{{}} gs = bob() // expected-error{{}} gs = grace(2) // expected-error{{}} gs = grace("three") } // The opaque type should conform to its constraining protocols do { let gs = grace("one") var ggs = grace(gs) ggs = grace(gs) } // The opaque type should expose the members implied by its protocol // constraints do { var a = alice() a.paul() a.priscilla() } } func recursion(x: Int) -> some P { if x == 0 { return 0 } return recursion(x: x - 1) } func noReturnStmts() -> some P {} // expected-error {{function declares an opaque return type, but has no return statements in its body from which to infer an underlying type}} {{educational-notes=opaque-type-inference}} func returnUninhabited() -> some P { // expected-note {{opaque return type declared here}} fatalError() // expected-error{{return type of global function 'returnUninhabited()' requires that 'Never' conform to 'P'}} } func mismatchedReturnTypes(_ x: Bool, _ y: Int, _ z: String) -> some P { // expected-error{{do not have matching underlying types}} {{educational-notes=opaque-type-inference}} if x { return y // expected-note{{underlying type 'Int'}} } else { return z // expected-note{{underlying type 'String'}} } } var mismatchedReturnTypesProperty: some P { // expected-error{{do not have matching underlying types}} if true { return 0 // expected-note{{underlying type 'Int'}} } else { return "" // expected-note{{underlying type 'String'}} } } struct MismatchedReturnTypesSubscript { subscript(x: Bool, y: Int, z: String) -> some P { // expected-error{{do not have matching underlying types}} if x { return y // expected-note{{underlying type 'Int'}} } else { return z // expected-note{{underlying type 'String'}} } } } func jan() -> some P { return [marcia(), marcia(), marcia()] } func marcia() -> some P { return [marcia(), marcia(), marcia()] // expected-error{{defines the opaque type in terms of itself}} {{educational-notes=opaque-type-inference}} } protocol R { associatedtype S: P, Q // expected-note*{{}} func r_out() -> S func r_in(_: S) } extension Int: R { func r_out() -> String { return "" } func r_in(_: String) {} } func candace() -> some R { return 0 } func doug() -> some R { return 0 } func gary<T: R>(_ x: T) -> some R { return x } func sameType<T>(_: T, _: T) {} func associatedTypeIdentity() { let c = candace() let d = doug() var cr = c.r_out() cr = candace().r_out() cr = doug().r_out() // expected-error{{}} var dr = d.r_out() dr = candace().r_out() // expected-error{{}} dr = doug().r_out() c.r_in(cr) c.r_in(c.r_out()) c.r_in(dr) // expected-error{{}} c.r_in(d.r_out()) // expected-error{{}} d.r_in(cr) // expected-error{{}} d.r_in(c.r_out()) // expected-error{{}} d.r_in(dr) d.r_in(d.r_out()) cr.paul() cr.priscilla() cr.quinn() dr.paul() dr.priscilla() dr.quinn() sameType(cr, c.r_out()) sameType(dr, d.r_out()) sameType(cr, dr) // expected-error {{conflicting arguments to generic parameter 'T' ('(some R).S' (result type of 'candace') vs. '(some R).S' (result type of 'doug'))}} sameType(gary(candace()).r_out(), gary(candace()).r_out()) sameType(gary(doug()).r_out(), gary(doug()).r_out()) // TODO(diagnostics): This is not great but the problem comes from the way solver discovers and attempts bindings, if we could detect that // `(some R).S` from first reference to `gary()` in inconsistent with the second one based on the parent type of `S` it would be much easier to diagnose. sameType(gary(doug()).r_out(), gary(candace()).r_out()) // expected-error@-1:12 {{conflicting arguments to generic parameter 'T' ('some R' (result type of 'doug') vs. 'some R' (result type of 'candace'))}} // expected-error@-2:34 {{conflicting arguments to generic parameter 'T' ('some R' (result type of 'doug') vs. 'some R' (result type of 'candace'))}} } func redeclaration() -> some P { return 0 } // expected-note 2{{previously declared}} func redeclaration() -> some P { return 0 } // expected-error{{redeclaration}} func redeclaration() -> some Q { return 0 } // expected-error{{redeclaration}} func redeclaration() -> P { return 0 } func redeclaration() -> Any { return 0 } var redeclaredProp: some P { return 0 } // expected-note 3{{previously declared}} var redeclaredProp: some P { return 0 } // expected-error{{redeclaration}} var redeclaredProp: some Q { return 0 } // expected-error{{redeclaration}} var redeclaredProp: P { return 0 } // expected-error{{redeclaration}} struct RedeclarationTest { func redeclaration() -> some P { return 0 } // expected-note 2{{previously declared}} func redeclaration() -> some P { return 0 } // expected-error{{redeclaration}} func redeclaration() -> some Q { return 0 } // expected-error{{redeclaration}} func redeclaration() -> P { return 0 } var redeclaredProp: some P { return 0 } // expected-note 3{{previously declared}} var redeclaredProp: some P { return 0 } // expected-error{{redeclaration}} var redeclaredProp: some Q { return 0 } // expected-error{{redeclaration}} var redeclaredProp: P { return 0 } // expected-error{{redeclaration}} subscript(redeclared _: Int) -> some P { return 0 } // expected-note 2{{previously declared}} subscript(redeclared _: Int) -> some P { return 0 } // expected-error{{redeclaration}} subscript(redeclared _: Int) -> some Q { return 0 } // expected-error{{redeclaration}} subscript(redeclared _: Int) -> P { return 0 } } func diagnose_requirement_failures() { struct S { var foo: some P { return S() } // expected-note {{declared here}} // expected-error@-1 {{return type of property 'foo' requires that 'S' conform to 'P'}} subscript(_: Int) -> some P { // expected-note {{declared here}} return S() // expected-error@-1 {{return type of subscript 'subscript(_:)' requires that 'S' conform to 'P'}} } func bar() -> some P { // expected-note {{declared here}} return S() // expected-error@-1 {{return type of instance method 'bar()' requires that 'S' conform to 'P'}} } static func baz(x: String) -> some P { // expected-note {{declared here}} return S() // expected-error@-1 {{return type of static method 'baz(x:)' requires that 'S' conform to 'P'}} } } func fn() -> some P { // expected-note {{declared here}} return S() // expected-error@-1 {{return type of local function 'fn()' requires that 'S' conform to 'P'}} } } func global_function_with_requirement_failure() -> some P { // expected-note {{declared here}} return 42 as Double // expected-error@-1 {{return type of global function 'global_function_with_requirement_failure()' requires that 'Double' conform to 'P'}} } func recursive_func_is_invalid_opaque() { func rec(x: Int) -> some P { // expected-error@-1 {{function declares an opaque return type, but has no return statements in its body from which to infer an underlying type}} if x == 0 { return rec(x: 0) } return rec(x: x - 1) } } func closure() -> some P { _ = { return "test" } return 42 } protocol HasAssocType { associatedtype Assoc func assoc() -> Assoc } struct GenericWithOpaqueAssoc<T>: HasAssocType { func assoc() -> some Any { return 0 } } struct OtherGeneric<X, Y, Z> { var x: GenericWithOpaqueAssoc<X>.Assoc var y: GenericWithOpaqueAssoc<Y>.Assoc var z: GenericWithOpaqueAssoc<Z>.Assoc } protocol P_51641323 { associatedtype T var foo: Self.T { get } } func rdar_51641323() { struct Foo: P_51641323 { var foo: some P_51641323 { // expected-note {{required by opaque return type of property 'foo'}} {} // expected-error {{type '() -> ()' cannot conform to 'P_51641323'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}} } } } // Protocol requirements cannot have opaque return types protocol OpaqueProtocolRequirement { // expected-error@+1 {{cannot be the return type of a protocol requirement}}{{3-3=associatedtype <#AssocType#>: P\n}}{{21-27=<#AssocType#>}} func method1() -> some P // expected-error@+1 {{cannot be the return type of a protocol requirement}}{{3-3=associatedtype <#AssocType#>: C & P & Q\n}}{{21-35=<#AssocType#>}} func method2() -> some C & P & Q // expected-error@+1 {{cannot be the return type of a protocol requirement}}{{3-3=associatedtype <#AssocType#>: Nonsense\n}}{{21-34=<#AssocType#>}} func method3() -> some Nonsense // expected-error@+1 {{cannot be the return type of a protocol requirement}}{{3-3=associatedtype <#AssocType#>: P\n}}{{13-19=<#AssocType#>}} var prop: some P { get } // expected-error@+1 {{cannot be the return type of a protocol requirement}}{{3-3=associatedtype <#AssocType#>: P\n}}{{18-24=<#AssocType#>}} subscript() -> some P { get } } func testCoercionDiagnostics() { var opaque = foo() opaque = bar() // expected-error {{cannot assign value of type 'some P' (result of 'bar()') to type 'some P' (result of 'foo()')}} {{none}} opaque = () // expected-error {{cannot assign value of type '()' to type 'some P'}} {{none}} opaque = computedProperty // expected-error {{cannot assign value of type 'some P' (type of 'computedProperty') to type 'some P' (result of 'foo()')}} {{none}} opaque = SubscriptTest()[0] // expected-error {{cannot assign value of type 'some P' (result of 'SubscriptTest.subscript(_:)') to type 'some P' (result of 'foo()')}} {{none}} var opaqueOpt: Optional = opaque opaqueOpt = bar() // expected-error {{cannot assign value of type 'some P' (result of 'bar()') to type 'some P' (result of 'foo()')}} {{none}} opaqueOpt = () // expected-error {{cannot assign value of type '()' to type 'some P'}} {{none}} } var globalVar: some P = 17 let globalLet: some P = 38 struct Foo { static var staticVar: some P = 17 static let staticLet: some P = 38 var instanceVar: some P = 17 let instanceLet: some P = 38 } protocol P_52528543 { init() associatedtype A: Q_52528543 var a: A { get } } protocol Q_52528543 { associatedtype B // expected-note 2 {{associated type 'B'}} var b: B { get } } extension P_52528543 { func frob(a_b: A.B) -> some P_52528543 { return self } } func foo<T: P_52528543>(x: T) -> some P_52528543 { return x .frob(a_b: x.a.b) .frob(a_b: x.a.b) // expected-error {{cannot convert}} } struct GenericFoo<T: P_52528543, U: P_52528543> { let x: some P_52528543 = T() let y: some P_52528543 = U() mutating func bump() { var xab = f_52528543(x: x) xab = f_52528543(x: y) // expected-error{{cannot assign}} } } func f_52528543<T: P_52528543>(x: T) -> T.A.B { return x.a.b } func opaque_52528543<T: P_52528543>(x: T) -> some P_52528543 { return x } func invoke_52528543<T: P_52528543, U: P_52528543>(x: T, y: U) { let x2 = opaque_52528543(x: x) let y2 = opaque_52528543(x: y) var xab = f_52528543(x: x2) xab = f_52528543(x: y2) // expected-error{{cannot assign}} } protocol Proto {} struct I : Proto {} dynamic func foo<S>(_ s: S) -> some Proto { return I() } @_dynamicReplacement(for: foo) func foo_repl<S>(_ s: S) -> some Proto { return I() } protocol SomeProtocolA {} protocol SomeProtocolB {} protocol SomeProtocolC {} struct SomeStructC: SomeProtocolA, SomeProtocolB, SomeProtocolC {} let someProperty: SomeProtocolA & some SomeProtocolB = SomeStructC() // expected-error {{'some' should appear at the beginning of a composition}}{{35-40=}}{{19-19=some }} let someOtherProperty: some SomeProtocolA & some SomeProtocolB = SomeStructC() // expected-error {{'some' should appear at the beginning of a composition}}{{45-50=}} let someThirdProperty: some SomeProtocolA & SomeProtocolB & some SomeProtocolC = SomeStructC() // expected-error {{'some' should appear at the beginning of a composition}}{{61-66=}} // An opaque result type on a protocol extension member effectively // contains an invariant reference to 'Self', and therefore cannot // be referenced on an existential type. protocol OpaqueProtocol {} extension OpaqueProtocol { var asSome: some OpaqueProtocol { return self } func getAsSome() -> some OpaqueProtocol { return self } subscript(_: Int) -> some OpaqueProtocol { return self } } func takesOpaqueProtocol(existential: OpaqueProtocol) { // These are okay because we erase to the opaque type bound let a = existential.asSome let _: Int = a // expected-error{{cannot convert value of type 'any OpaqueProtocol' to specified type 'Int'}} _ = existential.getAsSome() _ = existential[0] } func takesOpaqueProtocol<T : OpaqueProtocol>(generic: T) { // these are all OK: _ = generic.asSome _ = generic.getAsSome() _ = generic[0] } func opaquePlaceholderFunc() -> some _ { 1 } // expected-error {{type placeholder not allowed here}} var opaquePlaceholderVar: some _ = 1 // expected-error {{type placeholder not allowed here}} // rdar://90456579 - crash in `OpaqueUnderlyingTypeChecker` func test_diagnostic_with_contextual_generic_params() { struct S { func test<T: Q>(t: T) -> some Q { // expected-error@-1 {{function declares an opaque return type 'some Q', but the return statements in its body do not have matching underlying types}} if true { return t // expected-note {{return statement has underlying type 'T'}} } return "" // String conforms to `Q` // expected-note@-1 {{return statement has underlying type 'String'}} } } } // https://github.com/apple/swift/issues/53378 // Suggest `return` when the last statement of a multi-statement function body // would be a valid return value protocol P1 { } protocol P2 { } do { func test() -> some Numeric { // expected-error@-1 {{function declares an opaque return type, but has no return statements in its body from which to infer an underlying type}} let x = 0 x // expected-note {{did you mean to return the last expression?}} {{5-5=return }} // expected-warning@-1 {{expression of type 'Int' is unused}} } func test2() -> some Numeric { // expected-error@-1 {{function declares an opaque return type, but has no return statements in its body from which to infer an underlying type}} let x = "s" x // expected-warning {{expression of type 'String' is unused}} } struct S1: P1, P2 { } struct S2: P1 { } func test3() -> some P1 & P2 { // expected-error@-1 {{function declares an opaque return type, but has no return statements in its body from which to infer an underlying type}} let x = S1() x // expected-note {{did you mean to return the last expression?}} {{5-5=return }} // expected-warning@-1 {{expression of type 'S1' is unused}} } func test4() -> some P1 & P2 { // expected-error@-1 {{function declares an opaque return type, but has no return statements in its body from which to infer an underlying type}} let x = S2() x // expected-warning {{expression of type 'S2' is unused}} } func test5() -> some P1 { // expected-error@-1 {{function declares an opaque return type, but has no return statements in its body from which to infer an underlying type}} let x = invalid // expected-error {{cannot find 'invalid' in scope}} x } }
apache-2.0
d6c7afa9d87074c960237afb3e0b8ae8
32.489655
220
0.646932
3.486627
false
false
false
false
alobanov/ALFormBuilder
Sources/RxFormBuilder/Components/cells/ALFBTextViewCell.swift
1
7801
// // FormTextViewCell.swift // Plus // // Created by Aleksey Lobanov on 15.03.17. // Copyright © 2017 Aleksey Lobanov All rights reserved. // import UIKit import RxSwift import RxCocoa open class ALFBTextViewCell: UITableViewCell, RxCellReloadeble, UITextFieldDelegate { @IBOutlet weak var textField: ALValidatedTextField! @IBOutlet weak var descriptionValueLabel: UILabel! @IBOutlet weak var validateBtn: UIButton! @IBOutlet weak var cleareBtn: UIButton! @IBOutlet weak var errorHighlightView: UIView! fileprivate var storedModel: RowFormTextCompositeOutput! fileprivate var alreadyInitialized = false fileprivate var validationState: BehaviorSubject<ALFB.ValidationState>! fileprivate var didChangeValidation: DidChangeValidation! let bag = DisposeBag() open override func awakeFromNib() { super.awakeFromNib() // base configuration validateBtn.setImage(ALFBStyle.imageOfTfAlertIconStar, for: UIControlState()) cleareBtn.setImage(ALFBStyle.imageOfCloseBtn(customColor: ALFBStyle.fbGray), for: UIControlState()) errorHighlightView.alpha = 0 errorHighlightView.isUserInteractionEnabled = false validateBtn.isHidden = true cleareBtn.isHidden = true clipsToBounds = true self.didChangeValidation = { [weak self] _ in if let state = self?.storedModel.validation.state { self?.validationState.onNext(state) } } textField.accessibilityIdentifier = "rrrr" self.layoutIfNeeded() } public func reload(with model: RxCellModelDatasoursable) { // check visuzlization model guard let vm = model as? RowFormTextCompositeOutput else { return } // check type of model data switch vm.base.dataType { case .string, .decimal, .integer, .password: self.storedModel = vm break default: return } // Configurate text field // keybord type textField.keyboardType = vm.visualisation.keyboardType?.value ?? .default // Additional placeholder above the input text textField.textPlaceholder = vm.visualisation.placeholderTopText textField.autocapitalizationType = vm.visualisation.autocapitalizationType?.value ?? .none // Just place holder textField.placeholder = vm.visualisation.placeholderText // Can editable textField.isUserInteractionEnabled = !vm.visible.isDisabled self.textField.textColor = textField.isUserInteractionEnabled ? ALFBStyle.fbDarkGray : ALFBStyle.fbLightGray self.backgroundColor = textField.isUserInteractionEnabled ? UIColor.white : ALFBStyle.fbUltraLightGray // is password type textField.isSecureTextEntry = vm.visualisation.isPassword ?? false // Set value textField.text = vm.value.transformForDisplay() ?? "" // Fill by color for validation state textField.validate(vm.validation.state) // addidional description information field under the text field descriptionValueLabel.text = vm.visualisation.detailsText // // Configure buttons and components // cleareBtn.isHidden = true validateBtn.isHidden = !vm.validation.state.isVisibleValidationUI if !validateBtn.isHidden { validateBtn.isHidden = !vm.visible.isMandatory } if let s = self.storedModel as? FormItemCompositeProtocol { self.storedModel.didChangeValidation[s.identifier] = didChangeValidation } // Configurate next only one if !alreadyInitialized { configureRx() textField.delegate = self accessoryType = UITableViewCellAccessoryType.none alreadyInitialized = true } textField.isAccessibilityElement = true textField.accessibilityIdentifier = vm.identifier textField.accessibilityLabel = textField.text validateBtn.accessibilityIdentifier = "validate_\(vm.identifier)" cleareBtn.accessibilityIdentifier = "clear_\(vm.identifier)" } // MARK: - UITextFieldDelegate public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return textField.filtred(self.storedModel.visualisation.keyboardOptions.options, string: string, range: range, maxLeng: self.storedModel.validation.maxLength, maxFractionDigits: self.storedModel.visualisation.keyboardOptions.maxFractionDigits) } // MARK: - Additional helpers open func showValidationWarning(text: String) { // need override } func highlightField() { UIView.animate(withDuration: 0.4, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: { self.errorHighlightView.alpha = 0.3 }, completion: { _ in UIView.animate(withDuration: 0.4, animations: { self.errorHighlightView.alpha = 0 }) }) } } extension ALFBTextViewCell { func change(value: String?) { var newValue: ALValueTransformable switch self.storedModel.base.dataType { case .decimal: let value = (value ?? "").replace(string: ",", replacement: ".") newValue = ALFloatValue(value: Float(value)) case .integer: newValue = ALIntValue(value: Int(value ?? "")) default: newValue = ALStringValue(value: value) } self.storedModel.update(value: newValue) } func configureRx() { self.validationState = BehaviorSubject<ALFB.ValidationState>(value: self.storedModel.validation.state) // Check validation all of text stream textField.rx.text.asDriver().skip(1) .filter({ [weak self] text -> Bool in return (text != self?.storedModel.value.transformForDisplay()) }).drive(onNext: { [weak self] text in self?.change(value: text) }).disposed(by: bag) // Show validation only on end editing let endEditing = textField.rx.controlEvent(.editingDidEnd).asObservable() .withLatestFrom(validationState) // Show cleare button on start editting textfield textField.rx.controlEvent(.editingDidBegin).asDriver().drive(onNext: {[weak self] _ in self?.storedModel.base.changeisEditingNow(true) self?.validateBtn.isHidden = true self?.cleareBtn.isHidden = false }).disposed(by: bag) validationState.scan(ALFB.ValidationState.typing) { (oldState, newState) -> ALFB.ValidationState? in guard let old = oldState else { return .valid } if old == newState { return old } return newState }.subscribe(onNext: { [weak self] state in self?.textField.validate(state ?? .valid) }) .disposed(by: bag) // validate value on end editing text field endEditing.subscribe(onNext: {[weak self] valid in // guard let v = valid else { return } self?.storedModel.base.changeisEditingNow(false) self?.validateBtn.isHidden = valid.isValidWithTyping let isMandatory = self?.storedModel.visible.isMandatory ?? false if !isMandatory { self?.validateBtn.isHidden = !isMandatory } self?.cleareBtn.isHidden = true if !valid.isValidWithTyping { // self?.highlightField() } }).disposed(by: bag) // Clear text cleareBtn.rx.tap.subscribe(onNext: {[weak self] _ in self?.textField.text = "" self?.textField.sendActions(for: UIControlEvents.valueChanged) }).disposed(by: bag) // Show warning on tap validateBtn.rx.tap.subscribe(onNext: {[unowned self] _ in if self.storedModel.validation.state.message != "" { self.showValidationWarning(text: self.storedModel.validation.state.message) self.highlightField() } }).disposed(by: bag) } }
mit
290a44cae94edc84f0a986962cc2f1c0
32.766234
113
0.683333
4.642857
false
false
false
false
bsorrentino/slidesOnTV
slides/SlideViewerController+AutoLayout.swift
1
1505
// // PDFCollectionViewController+AutoLayout.swift // slides // // Created by softphone on 12/09/16. // Copyright © 2016 soulsoftware. All rights reserved. // import Foundation let layoutAttrs = ( cellSize: CGSize(width: 400,height: 250), numCols: 1, minSpacingForCell: CGFloat(25.0), minSpacingForLine: CGFloat(35.0) ) extension UIPDFCollectionViewController { var thumbnailsWidth:CGFloat { get { return CGFloat(layoutAttrs.numCols) * CGFloat(layoutAttrs.cellSize.width + (CGFloat(layoutAttrs.numCols - 1) * layoutAttrs.minSpacingForCell)) } } override func updateViewConstraints() { let frame_width = view.frame.size.width - 60 // ignore insets let w = (self.fullpage) ? 0 : self.thumbnailsWidth let pageViewWidth = frame_width - w pageView.snp.updateConstraints { make in make.width.equalTo( pageViewWidth ).priority( 1000 ) // required } thumbnailsView.snp.updateConstraints { make in make.width.equalTo( w ).priority( 750 ) // high } pageView.pageImageView.snp.updateConstraints { make in let delta = pageViewWidth * 0.10 let newWidth = pageViewWidth - delta make.width.equalTo(newWidth).priority( 1000 ) // required } super.updateViewConstraints() } }
mit
f33f15a0f794a7398cc3fdb30a9ac1b8
25.857143
120
0.589761
4.641975
false
false
false
false
zhangjk4859/MyWeiBoProject
sinaWeibo/sinaWeibo/Classes/Home/JKStatus.swift
1
6661
// // JKStatus.swift // sinaWeibo // // Created by 张俊凯 on 16/7/13. // Copyright © 2016年 张俊凯. All rights reserved. // import UIKit import SDWebImage class JKStatus: NSObject { // 微博创建时间 var created_at: String? { didSet{ // 1.将字符串转换为时间 let createdDate = NSDate.dateWithStr(created_at!) // 2.获取格式化之后的时间字符串 created_at = createdDate.descDate } } // 微博ID var id: Int = 0 // 微博信息内容 var text: String? // 微博来源 var source: String? { didSet{ // 1.截取字符串 if let str = source { if str == "" { return } // 1.1获取开始截取的位置 let startLocation = (str as NSString).rangeOfString(">").location + 1 // 1.2获取截取的长度 let length = (str as NSString).rangeOfString("<", options: NSStringCompareOptions.BackwardsSearch).location - startLocation // 1.3截取字符串 source = "来自:" + (str as NSString).substringWithRange(NSMakeRange(startLocation, length)) } } } // 配图数组 var pic_urls: [[String: AnyObject]]? { didSet{ // 1.初始化数组 storedPicURLS = [NSURL]() storedLargePicURLS = [NSURL]() // 2遍历取出所有的图片路径字符串 for dict in pic_urls! { if let urlStr = dict["thumbnail_pic"] as? String { // 1.将字符串转换为URL保存到数组中 storedPicURLS!.append(NSURL(string: urlStr)!) // 2.处理大图 let largeURLStr = urlStr.stringByReplacingOccurrencesOfString("thumbnail", withString: "large") storedLargePicURLS!.append(NSURL(string: largeURLStr)!) } } } } // 保存当前微博所有配图的URL var storedPicURLS: [NSURL]? // 保存当前微博所有配图"大图"的URL var storedLargePicURLS: [NSURL]? // 用户信息 var user: JKUser? // 转发微博 var retweeted_status: JKStatus? // 如果有转发, 原创就没有配图 // 定义一个计算属性, 用于返回原创获取转发配图的URL数组 var pictureURLS:[NSURL]? { return retweeted_status != nil ? retweeted_status?.storedPicURLS : storedPicURLS } // 定义一个计算属性, 用于返回原创或者转发配图的大图URL数组 var LargePictureURLS:[NSURL]? { return retweeted_status != nil ? retweeted_status?.storedLargePicURLS : storedLargePicURLS } // 加载微博数据 class func loadStatuses(since_id: Int, max_id: Int, finished: (models:[JKStatus]?, error:NSError?)->()){ JKStatusDAO.loadStatuses(since_id, max_id: max_id) { (array, error) -> () in if array == nil { finished(models: nil, error: error) } if error != nil { finished(models: nil, error: error) } // 2.遍历数组, 将字典转换为模型 let models = dict2Model(array!) // 3.缓存微博配图 cacheStatusImages(models, finished: finished) } } // 缓存配图 class func cacheStatusImages(list: [JKStatus], finished: (models:[JKStatus]?, error:NSError?)->()) { if list.count == 0 { finished(models: list, error: nil) return } // 1.创建一个组 let group = dispatch_group_create() // 1.缓存图片 for status in list { // 1.1判断当前微博是否有配图, 如果没有就直接跳过 // 如果条件为nil, 那么就会执行else后面的语句 guard let _ = status.pictureURLS else { continue } for url in status.pictureURLS! { // 将当前的下载操作添加到组中 dispatch_group_enter(group) // 缓存图片 SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, _, _, _, _) -> Void in // 离开当前组 dispatch_group_leave(group) }) } } // 2.当所有图片都下载完毕再通过闭包通知调用者 dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in // 图片下载完毕 finished(models: list, error: nil) } } // 将字典数组转换为模型数组 class func dict2Model(list: [[String: AnyObject]]) -> [JKStatus] { var models = [JKStatus]() for dict in list { models.append(JKStatus(dict: dict)) } return models } // 字典转模型 init(dict: [String: AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) } // setValuesForKeysWithDictionary内部会调用以下方法 override func setValue(value: AnyObject?, forKey key: String) { // 1.判断当前是否正在给微博字典中的user字典赋值 if "user" == key { // 2.根据user key对应的字典创建一个模型 user = JKUser(dict: value as! [String : AnyObject]) return } // 2.判断是否是转发微博, 如果是就自己处理 if "retweeted_status" == key { retweeted_status = JKStatus(dict: value as! [String : AnyObject]) return } // 3,调用父类方法, 按照系统默认处理 super.setValue(value, forKey: key) } override func setValue(value: AnyObject?, forUndefinedKey key: String) { } // 打印当前模型 var properties = ["created_at", "id", "text", "source", "pic_urls"] override var description: String { let dict = dictionaryWithValuesForKeys(properties) return "\(dict)" } }
mit
791ca4635c6fd9abe7fbc58070295be3
26.295775
171
0.488648
4.585174
false
false
false
false
cdmx/MiniMancera
miniMancera/Model/Option/WhistlesVsZombies/Whistle/Type/MOptionWhistlesVsZombiesWhistleTypeOrange.swift
1
852
import UIKit class MOptionWhistlesVsZombiesWhistleTypeOrange:MOptionWhistlesVsZombiesWhistleTypeProtocol { private(set) var whistle:MOptionWhistlesVsZombiesWhistleProtocol private(set) var boardItemType:MOptionWhistlesVsZombiesBoardItemProtocol.Type private(set) var texture:MGameTexture private(set) var colour:UIColor private(set) var barrelLength:CGFloat private let kBarrelLength:CGFloat = 18 init(textures:MOptionWhistlesVsZombiesTextures) { whistle = MOptionWhistlesVsZombiesWhistleOrange() boardItemType = MOptionWhistlesVsZombiesBoardItemOrange.self texture = textures.whistleOrange colour = UIColor( red:0.96078431372549, green:0.650980392156863, blue:0.137254901960784, alpha:1) barrelLength = kBarrelLength } }
mit
dfae902fd13b11a40cdca10364ab0c37
34.5
91
0.735915
4.982456
false
false
false
false
febus/SwiftWeather
Swift Weather Instant/TodayViewController.swift
1
6335
// // TodayViewController.swift // Swift Weather Instant // // Created by Marc Tarnutzer on 12.12.14. // Copyright (c) 2014 rushjet. All rights reserved. // import UIKit import NotificationCenter import CoreLocation import Alamofire import SwiftyJSON import SwiftWeatherService class TodayViewController: UIViewController, NCWidgetProviding, CLLocationManagerDelegate { let locationManager:CLLocationManager = CLLocationManager() @IBOutlet weak var time1: UILabel! @IBOutlet weak var time2: UILabel! @IBOutlet weak var time3: UILabel! @IBOutlet weak var time4: UILabel! @IBOutlet weak var image1: UIImageView! @IBOutlet weak var image2: UIImageView! @IBOutlet weak var image3: UIImageView! @IBOutlet weak var image4: UIImageView! @IBOutlet weak var temp1: UILabel! @IBOutlet weak var temp2: UILabel! @IBOutlet weak var temp3: UILabel! @IBOutlet weak var temp4: UILabel! override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() } func updateWeatherInfo(latitude: CLLocationDegrees, longitude: CLLocationDegrees) { let url = "http://api.openweathermap.org/data/2.5/forecast" let params = ["lat":latitude, "lon":longitude] print(params) Alamofire.request(.GET, url, parameters: params) .responseJSON { (request, response, result) in if(result.error != nil) { print("Error: \(result.error)") print(request) print(response) } else { print("Success: \(url)") print(request) let json = JSON(result.value!) self.updateUISuccess(json) } } } func updateUISuccess(json: JSON) { let service = SwiftWeatherService.WeatherService() // If we can get the temperature from JSON correctly, we assume the rest of JSON is correct. if let _ = json["list"][0]["main"]["temp"].double { // Get country let country = json["city"]["country"].stringValue // Get forecast for index in 0...3 { print(json["list"][index]) if let tempResult = json["list"][index]["main"]["temp"].double { // Get and convert temperature let temperature = service.convertTemperature(country, temperature: tempResult) if (index==0) { self.temp1.text = "\(temperature)°" } else if (index==1) { self.temp2.text = "\(temperature)°" } else if (index==2) { self.temp3.text = "\(temperature)°" } else if (index==3) { self.temp4.text = "\(temperature)°" } // Get forecast time let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "HH:mm" let rawDate = json["list"][index]["dt"].doubleValue let date = NSDate(timeIntervalSince1970: rawDate) let forecastTime = dateFormatter.stringFromDate(date) if (index==0) { self.time1.text = forecastTime } else if (index==1) { self.time2.text = forecastTime } else if (index==2) { self.time3.text = forecastTime } else if (index==3) { self.time4.text = forecastTime } // Get and set icon let weather = json["list"][index]["weather"][0] let condition = weather["id"].intValue let icon = weather["icon"].stringValue let nightTime = service.isNightTime(icon) service.updateWeatherIcon(condition, nightTime: nightTime, index: index, callback: self.updatePictures) } else { continue } } } else { print("Weather info is not available!") } } func updatePictures(index: Int, name: String) { if (index==0) { self.image1.image = UIImage(named: name) } if (index==1) { self.image2.image = UIImage(named: name) } if (index==2) { self.image3.image = UIImage(named: name) } if (index==3) { self.image4.image = UIImage(named: name) } } //CLLocationManagerDelegate func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location:CLLocation = locations[locations.count-1] if (location.horizontalAccuracy > 0) { self.locationManager.stopUpdatingLocation() print(location.coordinate) updateWeatherInfo(location.coordinate.latitude, longitude: location.coordinate.longitude) } } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { print(error) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) { // Perform any setup necessary in order to update the view. // If an error is encountered, use NCUpdateResult.Failed // If there's no update required, use NCUpdateResult.NoData // If there's an update, use NCUpdateResult.NewData locationManager.startUpdatingLocation() completionHandler(NCUpdateResult.NewData) } }
mit
6218baba9c36b1274b8dad7d940eba06
35.385057
123
0.541463
5.462468
false
false
false
false
japango/chiayiapp
chiayi/chiayi/MasterViewController.swift
1
9206
// // MasterViewController.swift // chiayi // // Created by gosick on 2015/10/5. // Copyright © 2015年 gosick. All rights reserved. // import UIKit import CoreData class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate { var detailViewController: DetailViewController? = nil var managedObjectContext: NSManagedObjectContext? = nil override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem() let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:") self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController } } override func viewWillAppear(animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(sender: AnyObject) { let context = self.fetchedResultsController.managedObjectContext let entity = self.fetchedResultsController.fetchRequest.entity! let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context) // If appropriate, configure the new managed object. // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template. newManagedObject.setValue(NSDate(), forKey: "timeStamp") // Save the context. do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //print("Unresolved error \(error), \(error.userInfo)") abort() } } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = self.fetchedResultsController.objectAtIndexPath(indexPath) let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.fetchedResultsController.sections?.count ?? 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionInfo = self.fetchedResultsController.sections![section] return sectionInfo.numberOfObjects } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) self.configureCell(cell, atIndexPath: indexPath) return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let context = self.fetchedResultsController.managedObjectContext context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject) do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //print("Unresolved error \(error), \(error.userInfo)") abort() } } } func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { let object = self.fetchedResultsController.objectAtIndexPath(indexPath) cell.textLabel!.text = object.valueForKey("timeStamp")!.description } // MARK: - Fetched results controller var fetchedResultsController: NSFetchedResultsController { if _fetchedResultsController != nil { return _fetchedResultsController! } let fetchRequest = NSFetchRequest() // Edit the entity name as appropriate. let entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: self.managedObjectContext!) fetchRequest.entity = entity // Set the batch size to a suitable number. fetchRequest.fetchBatchSize = 20 // Edit the sort key as appropriate. let sortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: false) fetchRequest.sortDescriptors = [sortDescriptor] // Edit the section name key path and cache name if appropriate. // nil for section name key path means "no sections". let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master") aFetchedResultsController.delegate = self _fetchedResultsController = aFetchedResultsController do { try _fetchedResultsController!.performFetch() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //print("Unresolved error \(error), \(error.userInfo)") abort() } return _fetchedResultsController! } var _fetchedResultsController: NSFetchedResultsController? = nil func controllerWillChangeContent(controller: NSFetchedResultsController) { self.tableView.beginUpdates() } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case .Insert: self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) case .Delete: self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) default: return } } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case .Delete: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) case .Update: self.configureCell(tableView.cellForRowAtIndexPath(indexPath!)!, atIndexPath: indexPath!) case .Move: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) } } func controllerDidChangeContent(controller: NSFetchedResultsController) { self.tableView.endUpdates() } /* // Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed. func controllerDidChangeContent(controller: NSFetchedResultsController) { // In the simplest, most efficient, case, reload the table view. self.tableView.reloadData() } */ }
mit
152d19ffa13b6521ed94a3213ce117fd
45.015
360
0.68858
6.277626
false
false
false
false
DanielAsher/VIPER-SWIFT
VIPER-SWIFT/Classes/Modules/List/Application Logic/Interactor/UpcomingItem.swift
1
765
// // UpcomingItem.swift // VIPER-SWIFT // // Created by Conrad Stoll on 6/5/14. // Copyright (c) 2014 Mutual Mobile. All rights reserved. // import Foundation struct UpcomingItem : Equatable { let title : String let dueDate : NSDate let dateRelation : NearTermDateRelation } func == (leftSide: UpcomingItem, rightSide: UpcomingItem) -> Bool { var hasEqualSections = false hasEqualSections = rightSide.title == leftSide.title if hasEqualSections == false { return false } hasEqualSections = rightSide.dueDate == rightSide.dueDate if hasEqualSections == false { return false } hasEqualSections = rightSide.dateRelation == rightSide.dateRelation return hasEqualSections }
mit
5bf90458d163c40ec32d5902fa2af72d
22.212121
71
0.67451
4.751553
false
false
false
false
michaelborgmann/handshake
Handshake/HandshakeViewController.swift
1
4815
// // HandshakeViewController.swift // Handshake // // Created by Michael Borgmann on 28/07/15. // Copyright (c) 2015 Michael Borgmann. All rights reserved. // import UIKit class HandshakeViewController: UITableViewController, UITableViewDelegate { var _indexPath: NSIndexPath? var _headerView: UIView? @IBOutlet var headerView: UIView! { get { if _headerView == nil { NSBundle.mainBundle().loadNibNamed("HeaderView", owner: self, options: nil) } return _headerView } set { _headerView = newValue } } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override init(style: UITableViewStyle) { super.init(style: UITableViewStyle.Plain) self.navigationItem.title = "Handshake - IOU" } required init(coder aDecoder: NSCoder) { super.init(coder: nil) //fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() let nib = UINib(nibName: "TabNameCell", bundle: nil) tableView.registerNib(nib, forCellReuseIdentifier: "TabNameCell") let header: UIView = self.headerView tableView.tableHeaderView = header } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return TabNameStore.sharedStore.allTabNames.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell let cell = tableView.dequeueReusableCellWithIdentifier("TabNameCell", forIndexPath: indexPath) as! TabNameCell let tabName = TabNameStore.sharedStore.allTabNames[indexPath.row] //cell.textLabel?.text = tabName.description cell.nameLabel.text = tabName.iou cell.emailLabel.text = tabName.email cell.priceLabel.text = "0" cell.thumbnailView = nil let count = ItemStore.sharedStore.allItems.count for var i = 0; i < count; ++i { var item = ItemStore.sharedStore.allItems[i] if cell.emailLabel.text == item.email { var cellPrice: NSString = cell.priceLabel.text! var cellFloat = cellPrice.floatValue cellFloat += item.price cell.priceLabel.text = "\(cellFloat)" } } return cell } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { var tabName = TabNameStore.sharedStore.allTabNames[indexPath.row] TabNameStore.sharedStore.removeTabName(tabName) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { TabNameStore.sharedStore.moveTabNameAtIndex(sourceIndexPath.row, toIndex: destinationIndexPath.row) } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let tabName = TabNameStore.sharedStore.allTabNames[indexPath.row] let itemsView = ItemsTableViewController(style: .Plain) itemsView.email = tabName.email self.navigationController?.pushViewController(itemsView, animated: true) } @IBAction func logout(sender: UIButton) { print("button pressed") NSUserDefaults.standardUserDefaults().setBool(false, forKey: "isLoggedIn") NSUserDefaults.standardUserDefaults().synchronize() self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func addTabName(sender: AnyObject) { let newTabName = TabNameStore.sharedStore.createTabName() let nameView = NameViewController(isNew: true) nameView.tabName = newTabName nameView.dismissBlock = { self.tableView.reloadData() println("Saving Item and asking to dismiss DetailViewController") } self.navigationController?.modalPresentationStyle = UIModalPresentationStyle.FormSheet //self.presentViewController(nameView, animated: true, completion: nil) self.navigationController?.pushViewController(nameView, animated: true) } }
gpl-2.0
b722699675fae48e9487c7167c9ae277
37.214286
157
0.668536
5.279605
false
false
false
false
infinum/iOS-Loggie
Loggie/Classes/LogDetails/LogDetailsSection.swift
1
501
// // LogDetailsSection.swift // Pods // // Created by Filip Bec on 15/03/2017. // // import UIKit enum LogDetailsItem { case subtitle(String?, String?) case text(String?) case image(UIImage?) } class LogDetailsSection: NSObject { var headerTitle: String? var footerTitle: String? var items: [LogDetailsItem] = [] init(headerTitle: String? = nil, footerTitle: String? = nil) { self.headerTitle = headerTitle self.footerTitle = footerTitle } }
mit
9e093faa99d2ea676ca2785cbb9f5bed
16.275862
66
0.646707
3.853846
false
false
false
false
jblezoray/BatonManager
OSX/MenuBar/BMMenuController.swift
1
1124
// // BMMenuController.swift // MenuBar // // Created by Jean-Baptiste Lézoray on 29/06/2014. // Copyright (c) 2014 jblezoray. All rights reserved. // import Foundation import Cocoa class BMMenuController : NSObject { let data: BMData var menu : BMMenu! init(data:BMData) { self.data = data self.menu = nil } func action_isLoadingUsers() { menu.setListIsLoading(); } func action_loadUsers() { let users : [User] = [ User(name:"Robert", nbSticks: 12), User(name:"Alfred", nbSticks: 5), User(name:"Michel", nbSticks: 74)] menu.setUsersList(users) } func action_quitApp() { NSApplication.sharedApplication().terminate(self) } func action_addStick(sender: NSMenuItem!) { let user: User = sender.representedObject as User println("Je met un bâton à \(user.name)") } func action_ignoreUser(sender: NSMenuItem!) { let user: User = sender.representedObject as User println("J'ignore \(user.name)") } }
apache-2.0
39c5d56a29256907f49a14ab5a319b39
21.44
57
0.581624
3.865517
false
false
false
false
LYM-mg/DemoTest
indexView/Extesion/Inherit(继承)/CornersLabel.swift
1
977
// // CornersLabel.swift // chart2 // // Created by i-Techsys.com on 16/11/25. // Copyright © 2016年 i-Techsys. All rights reserved. // import UIKit // MARK: - 圆角Label class CornersLabel: UILabel { // override func draw(_ rect: CGRect) { // let pathRect = self.bounds.insetBy(dx: 1, dy: 1) // let path = UIBezierPath(roundedRect: pathRect, cornerRadius: 14) // path.lineWidth = 1 // UIColor.white.setFill() // UIColor.blue.setStroke() // path.fill() // path.stroke() // } } extension CornersLabel { override open func draw(_ rect: CGRect) { let maskPath = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 0, height: 8)) let maskLayer = CAShapeLayer() maskLayer.frame = self.bounds maskLayer.path = maskPath.cgPath self.layer.mask = maskLayer } }
mit
5c78e6394d7784e9211318b11d6f4dc0
26.714286
77
0.579381
3.959184
false
false
false
false
stripe/stripe-ios
StripePayments/StripePayments/API Bindings/Models/SetupIntents/STPSetupIntent.swift
1
12837
// // STPSetupIntent.swift // StripePayments // // Created by Yuki Tokuhiro on 6/27/19. // Copyright © 2019 Stripe, Inc. All rights reserved. // import Foundation /// A SetupIntent guides you through the process of setting up a customer's payment credentials for future payments. /// - seealso: https://stripe.com/docs/api/setup_intents public class STPSetupIntent: NSObject, STPAPIResponseDecodable { /// The Stripe ID of the SetupIntent. @objc public let stripeID: String /// The client secret of this SetupIntent. Used for client-side retrieval using a publishable key. @objc public let clientSecret: String /// Time at which the object was created. @objc public let created: Date /// ID of the Customer this SetupIntent belongs to, if one exists. @objc public let customerID: String? /// An arbitrary string attached to the object. Often useful for displaying to users. @objc public let stripeDescription: String? /// Has the value `YES` if the object exists in live mode or the value `NO` if the object exists in test mode. @objc public let livemode: Bool /// If present, this property tells you what actions you need to take in order for your customer to set up this payment method. @objc public let nextAction: STPIntentAction? /// ID of the payment method used with this SetupIntent. @objc public let paymentMethodID: String? /// The optionally expanded PaymentMethod used in this SetupIntent. @objc public let paymentMethod: STPPaymentMethod? /// The list of payment method types (e.g. `[STPPaymentMethodType.card]`) that this SetupIntent is allowed to set up. @objc public let paymentMethodTypes: [NSNumber] /// Status of this SetupIntent. @objc public let status: STPSetupIntentStatus /// Indicates how the payment method is intended to be used in the future. @objc public let usage: STPSetupIntentUsage /// The setup error encountered in the previous SetupIntent confirmation. @objc public let lastSetupError: STPSetupIntentLastSetupError? /// The ordered payment method preference for this SetupIntent @_spi(STP) public let orderedPaymentMethodTypes: [STPPaymentMethodType] /// A list of payment method types that are not activated in live mode, but activated in test mode @_spi(STP) public let unactivatedPaymentMethodTypes: [STPPaymentMethodType] /// Payment-method-specific configuration for this SetupIntent. @_spi(STP) public let paymentMethodOptions: STPPaymentMethodOptions? /// Link-specific settings for this SetupIntent. @_spi(STP) public let linkSettings: LinkSettings? /// Country code of the user. @_spi(STP) public let countryCode: String? // MARK: - Deprecated /// Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. /// @deprecated Metadata is not returned to clients using publishable keys. Retrieve them on your server using yoursecret key instead. /// - seealso: https://stripe.com/docs/api#metadata @available( *, deprecated, message: "Metadata is not returned to clients using publishable keys. Retrieve them on your server using your secret key instead." ) @objc public private(set) var metadata: [String: String]? @objc public let allResponseFields: [AnyHashable: Any] required init( stripeID: String, clientSecret: String, created: Date, countryCode: String?, customerID: String?, stripeDescription: String?, linkSettings: LinkSettings?, livemode: Bool, nextAction: STPIntentAction?, orderedPaymentMethodTypes: [STPPaymentMethodType], paymentMethodID: String?, paymentMethod: STPPaymentMethod?, paymentMethodOptions: STPPaymentMethodOptions?, paymentMethodTypes: [NSNumber], status: STPSetupIntentStatus, usage: STPSetupIntentUsage, lastSetupError: STPSetupIntentLastSetupError?, allResponseFields: [AnyHashable: Any], unactivatedPaymentMethodTypes: [STPPaymentMethodType] ) { self.stripeID = stripeID self.clientSecret = clientSecret self.created = created self.countryCode = countryCode self.customerID = customerID self.stripeDescription = stripeDescription self.linkSettings = linkSettings self.livemode = livemode self.nextAction = nextAction self.orderedPaymentMethodTypes = orderedPaymentMethodTypes self.paymentMethodID = paymentMethodID self.paymentMethod = paymentMethod self.paymentMethodOptions = paymentMethodOptions self.paymentMethodTypes = paymentMethodTypes self.status = status self.usage = usage self.lastSetupError = lastSetupError self.allResponseFields = allResponseFields self.unactivatedPaymentMethodTypes = unactivatedPaymentMethodTypes super.init() } /// :nodoc: @objc override public var description: String { let props = [ // Object String(format: "%@: %p", NSStringFromClass(STPSetupIntent.self), self), // Identifier "stripeId = \(stripeID)", // SetupIntent details (alphabetical) "clientSecret = <redacted>", "created = \(String(describing: created))", "countryCode = \(String(describing: countryCode))", "customerId = \(customerID ?? "")", "description = \(stripeDescription ?? "")", "lastSetupError = \(String(describing: lastSetupError))", "linkSettings = \(String(describing: linkSettings))", "livemode = \(livemode ? "YES" : "NO")", "nextAction = \(String(describing: nextAction))", "paymentMethodId = \(paymentMethodID ?? "")", "paymentMethod = \(String(describing: paymentMethod))", "paymentMethodOptions = \(String(describing: paymentMethodOptions))", "paymentMethodTypes = \(allResponseFields.stp_array(forKey: "payment_method_types") ?? [])", "status = \(allResponseFields.stp_string(forKey: "status") ?? "")", "usage = \(allResponseFields.stp_string(forKey: "usage") ?? "")", "unactivatedPaymentMethodTypes = \(allResponseFields.stp_array(forKey: "unactivated_payment_method_types") ?? [])", ] return "<\(props.joined(separator: "; "))>" } // MARK: - STPSetupIntentEnum support class func status(from string: String) -> STPSetupIntentStatus { let map = [ "requires_payment_method": NSNumber( value: STPSetupIntentStatus.requiresPaymentMethod.rawValue ), "requires_confirmation": NSNumber( value: STPSetupIntentStatus.requiresConfirmation.rawValue ), "requires_action": NSNumber(value: STPSetupIntentStatus.requiresAction.rawValue), "processing": NSNumber(value: STPSetupIntentStatus.processing.rawValue), "succeeded": NSNumber(value: STPSetupIntentStatus.succeeded.rawValue), "canceled": NSNumber(value: STPSetupIntentStatus.canceled.rawValue), ] let key = string.lowercased() let statusNumber = map[key] ?? NSNumber(value: STPSetupIntentStatus.unknown.rawValue) return (STPSetupIntentStatus(rawValue: statusNumber.intValue))! } class func usage(from string: String) -> STPSetupIntentUsage { let map = [ "off_session": NSNumber(value: STPSetupIntentUsage.offSession.rawValue), "on_session": NSNumber(value: STPSetupIntentUsage.onSession.rawValue), ] let key = string.lowercased() let statusNumber = map[key] ?? NSNumber(value: STPSetupIntentUsage.unknown.rawValue) return (STPSetupIntentUsage(rawValue: statusNumber.intValue))! } @objc @_spi(STP) public class func id(fromClientSecret clientSecret: String) -> String? { // see parseClientSecret from stripe-js-v3 let components = clientSecret.components(separatedBy: "_secret_") if components.count >= 2 && components[0].hasPrefix("seti_") { return components[0] } else { return nil } } // MARK: - STPAPIResponseDecodable public class func decodedObject(fromAPIResponse response: [AnyHashable: Any]?) -> Self? { guard let response = response else { return nil } // Consolidates expanded setup_intent and ordered_payment_method_types into singular dict for decoding if let paymentMethodPrefDict = response["payment_method_preference"] as? [AnyHashable: Any], let setupIntentDict = paymentMethodPrefDict["setup_intent"] as? [AnyHashable: Any], let orderedPaymentMethodTypes = paymentMethodPrefDict["ordered_payment_method_types"] as? [String] { var dict = setupIntentDict dict["ordered_payment_method_types"] = orderedPaymentMethodTypes dict["unactivated_payment_method_types"] = response["unactivated_payment_method_types"] dict["link_settings"] = response["link_settings"] return decodeSTPSetupIntentObject(fromAPIResponse: dict) } else { return decodeSTPSetupIntentObject(fromAPIResponse: response) } } class func decodeSTPSetupIntentObject(fromAPIResponse response: [AnyHashable: Any]?) -> Self? { guard let response = response else { return nil } let dict = response.stp_dictionaryByRemovingNulls() // required fields guard let stripeId = dict.stp_string(forKey: "id"), let clientSecret = dict.stp_string(forKey: "client_secret"), let rawStatus = dict.stp_string(forKey: "status"), let created = dict.stp_date(forKey: "created"), let paymentMethodTypeStrings = dict["payment_method_types"] as? [String], dict["livemode"] != nil else { return nil } let countryCode = dict.stp_string(forKey: "country_code") let customerID = dict.stp_string(forKey: "customer") let stripeDescription = dict.stp_string(forKey: "description") let linkSettings = LinkSettings.decodedObject( fromAPIResponse: dict["link_settings"] as? [AnyHashable: Any] ) let livemode = dict.stp_bool(forKey: "livemode", or: true) let nextActionDict = dict.stp_dictionary(forKey: "next_action") let nextAction = STPIntentAction.decodedObject(fromAPIResponse: nextActionDict) let orderedPaymentMethodTypes = STPPaymentMethod.paymentMethodTypes( from: dict["ordered_payment_method_types"] as? [String] ?? paymentMethodTypeStrings ) let paymentMethod = STPPaymentMethod.decodedObject( fromAPIResponse: dict["payment_method"] as? [AnyHashable: Any] ) let paymentMethodID = paymentMethod?.stripeId ?? dict.stp_string(forKey: "payment_method") let paymentMethodOptions = STPPaymentMethodOptions.decodedObject( fromAPIResponse: dict["payment_method_options"] as? [AnyHashable: Any] ) let paymentMethodTypes = STPPaymentMethod.types(from: paymentMethodTypeStrings) let status = self.status(from: rawStatus) let rawUsage = dict.stp_string(forKey: "usage") let usage = rawUsage != nil ? self.usage(from: rawUsage ?? "") : .none let lastSetupError = STPSetupIntentLastSetupError.decodedObject( fromAPIResponse: dict.stp_dictionary(forKey: "last_setup_error") ) let unactivatedPaymentTypes = STPPaymentMethod.paymentMethodTypes( from: dict["unactivated_payment_method_types"] as? [String] ?? [] ) let setupIntent = self.init( stripeID: stripeId, clientSecret: clientSecret, created: created, countryCode: countryCode, customerID: customerID, stripeDescription: stripeDescription, linkSettings: linkSettings, livemode: livemode, nextAction: nextAction, orderedPaymentMethodTypes: orderedPaymentMethodTypes, paymentMethodID: paymentMethodID, paymentMethod: paymentMethod, paymentMethodOptions: paymentMethodOptions, paymentMethodTypes: paymentMethodTypes, status: status, usage: usage, lastSetupError: lastSetupError, allResponseFields: response, unactivatedPaymentMethodTypes: unactivatedPaymentTypes ) return setupIntent } }
mit
c411ae607c8a21472d6cb101aa5cc443
46.540741
159
0.661655
5.010148
false
false
false
false
zhou9734/ZCJImagePicker
ZCJImagePicker/ImagePicker/PhotoViewController.swift
1
22924
// // ImagePickerViewController.swift // 图片选择器 // // Created by zhoucj on 16/8/24. // Copyright © 2016年 zhoucj. All rights reserved. // import UIKit import AssetsLibrary let NextSetp = "NextSetp" let ClosePopoverView = "ClosePopoverView" let SwitchPhotoGroup = "SwitchPhotoGroup" let RreviewPhotoDone = "RreviewPhotoDone" class PhotoViewController: UIViewController { //从选择图片视图传来的已经选择的图片 var selectedAlassentModel:[ALAssentModel]? var previewPresentAnimator = PreviewPresentAnimator() var previewDismissAnimator = PreviewDismisssAnimator() private let PhotoIdentifier = "PhotoLibraryCell" var countPhoto = 0 var popoverView: PPopoverView? var alassetModels = [ALAssentModel]() var alassentGroups = [ALAssetsGroup]() let types: [UInt32] = [ALAssetsGroupSavedPhotos,ALAssetsGroupLibrary, ALAssetsGroupAlbum, ALAssetsGroupPhotoStream, ALAssetsGroupEvent,ALAssetsGroupFaces] static let assetsLibrary = ALAssetsLibrary() var selectAssetsGroup: ALAssetsGroup?{ didSet{ var groupName = selectAssetsGroup!.valueForProperty(ALAssetsGroupPropertyName) as! String if groupName == "Camera Roll"{ groupName = "相机胶卷" }else if groupName == "Photo Library"{ groupName = "照片图库" }else if groupName == "My Photo Stream"{ groupName = "我的照片流" } self.titleButton.setTitle(groupName, forState: .Normal) self.titleButton.sizeToFit() loadAllAssetsForGroups() } } init(selectedAlassennt: [ALAssentModel]){ super.init(nibName: nil, bundle: nil) self.selectedAlassentModel = selectedAlassennt } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupUI() NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("nextStepBtnClick:"), name: NextSetp, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("unSelectTitleBtn"), name: ClosePopoverView, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("switchGroup:"), name: SwitchPhotoGroup, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("previewPhotoDone:"), name: RreviewPhotoDone, object: nil) } //MARK: - UI组件 private func setupUI(){ navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftButton) navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton) navigationItem.titleView = titleButton view.addSubview(collectionView) view.addSubview(toolView) previewBtn.enabled = false rightButton.enabled = false collectionView.translatesAutoresizingMaskIntoConstraints = false toolView.translatesAutoresizingMaskIntoConstraints = false previewBtn.translatesAutoresizingMaskIntoConstraints = false originalBtn.translatesAutoresizingMaskIntoConstraints = false //设置toolView内的按钮约束 let toolViewdict = ["previewBtn": previewBtn, "originalBtn": originalBtn] var t_cons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-15-[previewBtn(65)]-15-[originalBtn(80)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: toolViewdict) t_cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-10-[previewBtn(35)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: toolViewdict) t_cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-10-[originalBtn(35)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: toolViewdict) toolView.addConstraints(t_cons) //设置toolView约束 let dict = ["collectionView": collectionView, "toolView": toolView] var cons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict) cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-0-[toolView(55)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict) cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict) view.addConstraints(cons) loadAssetsGroups() } //collectionView private lazy var collectionView: UICollectionView = { let flowLayout = UICollectionViewFlowLayout() let width = (UIScreen.mainScreen().bounds.size.width - 4) / 3 flowLayout.itemSize = CGSize(width: width, height: width) flowLayout.minimumLineSpacing = 2 flowLayout.minimumInteritemSpacing = 2 let clv = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout) clv.registerClass(PhotoLibraryCell.self, forCellWithReuseIdentifier: self.PhotoIdentifier) clv.backgroundColor = UIColor(red: 234.0/255.0, green: 234.0/255.0, blue: 241.0/255.0, alpha: 1) clv.dataSource = self clv.delegate = self clv.alwaysBounceVertical = true return clv }() //取消按钮 private lazy var leftButton: UIButton = { let btn = UIButton() btn.setTitle("取消", forState: .Normal) btn.addTarget(self, action: Selector("cancelBtnClick"), forControlEvents: .TouchUpInside) btn.setTitleColor(UIColor.grayColor(), forState: .Normal) btn.titleLabel?.font = UIFont.systemFontOfSize(16) btn.frame.size = CGSize(width: 60, height: 40) btn.sizeToFit() return btn }() //下一步按钮 private lazy var rightButton: UIButton = { let btn = UIButton() btn.setTitle("下一步", forState: .Normal) btn.addTarget(self, action: Selector("nextStepBtnClick2"), forControlEvents: .TouchUpInside) btn.setBackgroundImage(UIImage(named: "tabbar_compose_below_button"), forState: .Normal) btn.setBackgroundImage(UIImage(named: "common_button_big_orange"), forState: .Selected) btn.setTitleColor(UIColor.grayColor(), forState: .Normal) btn.setTitleColor(UIColor.whiteColor(), forState: .Selected) btn.frame.size = CGSize(width: 70, height: 28) btn.titleLabel?.font = UIFont.systemFontOfSize(15) return btn }() //标题按钮 private lazy var titleButton: HeadButton = { let btn = HeadButton() btn.setTitle("", forState: .Normal) btn.addTarget(self, action: Selector("titleButtonClick:"), forControlEvents: .TouchUpInside) return btn }() //底部按钮 private lazy var toolView : UIView = { let _view = UIView() _view.addSubview(self.previewBtn) _view.addSubview(self.originalBtn) _view.backgroundColor = UIColor(red: 234.0/255.0, green: 234.0/255.0, blue: 241.0/255.0, alpha: 1) return _view }() //预览按钮 private lazy var previewBtn: UIButton = { let btn = UIButton() btn.setTitle("预览", forState: .Normal) btn.addTarget(self, action: Selector("previewBtnClick"), forControlEvents: .TouchUpInside) btn.setBackgroundImage(UIImage(named: "tabbar_compose_below_background"), forState: .Normal) btn.setTitleColor(UIColor.grayColor(), forState: .Normal) btn.setTitleColor(UIColor.darkGrayColor(), forState: .Selected) btn.titleLabel?.font = UIFont.systemFontOfSize(15) btn.enabled = false return btn }() //原图按钮 private lazy var originalBtn: UIButton = { let btn = UIButton() btn.setTitle(" 原图", forState: .Normal) btn.addTarget(self, action: Selector("originalBtnClick"), forControlEvents: .TouchUpInside) btn.setBackgroundImage(UIImage(named: "compose_photo_original"), forState: .Normal) btn.setBackgroundImage(UIImage(named: "compose_photo_original"), forState: .Highlighted) btn.setBackgroundImage(UIImage(named: "compose_photo_original_highlighted"), forState: .Selected) btn.setTitleColor(UIColor.darkGrayColor(), forState: .Normal) btn.titleLabel?.font = UIFont.systemFontOfSize(15) return btn }() //MARK: - 预览点击事件 @objc private func previewBtnClick(){ var selectedAlassetModels = [ALAssentModel]() var index = 0 var isFrist = true var fristIndex = -1 for model in alassetModels{ if model.isChecked{ if isFrist{ fristIndex = model.orginIndex isFrist = false } selectedAlassetModels.append(model) } index = index + 1 } let indexPath = NSIndexPath(forItem: fristIndex, inSection: 0) let cell = collectionView.cellForItemAtIndexPath(indexPath) as! PhotoLibraryCell openBrowser(cell, indexPath: NSIndexPath(forItem: 0, inSection: 0), models: selectedAlassetModels) } //MARK: - 原图点击事件 @objc private func originalBtnClick(){ originalBtn.selected = !originalBtn.selected } //取消 @objc private func cancelBtnClick(){ // dismissViewControllerAnimated(true, completion: nil) navigationController?.popViewControllerAnimated(true) } //MARK: - 下一步 @objc private func nextStepBtnClick(notice: NSNotification){ guard let previewModel = notice.userInfo!["alassetModels"] as? [ALAssentModel] else{ return } doNextStep(previewModel) } @objc private func nextStepBtnClick2(){ doNextStep(alassetModels) } private func doNextStep(models: [ALAssentModel]){ var selectedPhoto = [ALAssentModel]() for aModel in models{ if aModel.isChecked{ selectedPhoto.append(aModel) } } NSNotificationCenter.defaultCenter().postNotificationName(SelectedPhotoDone, object: self, userInfo: ["alassentModels" : selectedPhoto]) navigationController?.popViewControllerAnimated(true) } //MARK: - 标题按钮点击事件 @objc private func titleButtonClick(btn: UIButton){ if btn.selected{ popoverView?.hide() btn.selected = false }else{ popoverView?.showInView(view) btn.selected = true } } @objc private func unSelectTitleBtn(){ titleButton.selected = false } private func calculateImageRect(image: UIImage)-> CGRect{ //图片宽高比 let scale = image.size.height/image.size.width let screenWidth = UIScreen.mainScreen().bounds.width let screenHeight = UIScreen.mainScreen().bounds.height //利用宽高比计算图片的高度 let imageHeight = scale * screenWidth //判断当前是长图还是短图 var offsetY: CGFloat = 0 if imageHeight < screenHeight{ // 短图 // 计算顶部和底部内边距 offsetY = (screenHeight - imageHeight) * 0.5 } let rect = CGRect(x: 0, y: offsetY, width: screenWidth, height: imageHeight) return rect } //MARK: - 打开图片浏览器 private func openBrowser(cell: PhotoLibraryCell, indexPath: NSIndexPath, models: [ALAssentModel]){ //用collectionView转换cell的位置 let cellRect = collectionView.convertRect(cell.frame, toView: nil) let imageRect = calculateImageRect(cell.imageView.image!) let pvc = PreviewViewController(alassetModels: models, countPhoto: countPhoto, indexPath: indexPath) pvc.transitioningDelegate = self previewPresentAnimator.originFrame = cellRect previewPresentAnimator.image = cell.imageView.image! previewPresentAnimator.lastRect = imageRect previewDismissAnimator.lastRect = imageRect previewDismissAnimator.originFrame = cellRect previewDismissAnimator.photoClv = collectionView presentViewController(pvc, animated: true, completion: nil) } //MARK: - 切换分组照片 @objc private func switchGroup(notice: NSNotification){ //注意: 但凡通过网络或者通知获取到的数据,都需要进行安全校验 guard let gTypeStr = notice.userInfo!["gType"] as? String else{ return } dealGroupData(gTypeStr) } private func dealGroupData(gType: String){ //TODO alassetModels = [ALAssentModel]() var _index = 0 for groupM in alassentGroups{ if gType == "\(groupM.valueForProperty(ALAssetsGroupPropertyType))" { selectAssetsGroup = alassentGroups[_index] break } _index = _index + 1 } } //MARK: - 拍照 private func fromPhotograph(){ //创建图片控制器 let picker = UIImagePickerController() picker.delegate = self //设置来源 picker.sourceType = .Camera //默认后置 picker.cameraDevice = .Rear //设置闪光灯 picker.cameraFlashMode = .Off //允许编辑 picker.allowsEditing = false //打开相机 presentViewController(picker, animated: true, completion: nil) } //MARK: - 选中传过来的图片 private func dealSelectAlassent(){ guard var _selectedAlassent = selectedAlassentModel where selectedAlassentModel!.count > 0 else{ return } _selectedAlassent.removeLast() var selectedCount = 0 for _alm in alassetModels { for _m in _selectedAlassent{ if _alm.orginIndex == _m.orginIndex{ _alm.isChecked = true selectedCount = selectedCount + 1 continue } } } countPhoto = selectedCount dealCountPhoto() } //MARK: - 预览图片结束 @objc private func previewPhotoDone(notice: NSNotification){ guard let previewModels = notice.userInfo!["alassetModels"] as? [ALAssentModel] else{ return } var count = 0 for _m in alassetModels{ for _p in previewModels{ if _m.orginIndex == _p.orginIndex{ _m.isChecked = _p.isChecked if _m.isChecked{ count = count + 1 } } } } countPhoto = count dealCountPhoto() collectionView.reloadData() } deinit{ NSNotificationCenter.defaultCenter().removeObserver(self) } } //MARK: - UICollectionViewDataSource代理 extension PhotoViewController: UICollectionViewDataSource{ func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return alassetModels.count ?? 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoIdentifier, forIndexPath: indexPath) as! PhotoLibraryCell cell.delegate = self cell.assent = alassetModels[indexPath.item] cell.index = indexPath.item return cell } } //MARK: - UICollectionViewDelegate代理 extension PhotoViewController: UICollectionViewDelegate{ func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let cell = collectionView.cellForItemAtIndexPath(indexPath) as! PhotoLibraryCell if alassetModels[indexPath.item].isFirst { fromPhotograph() return } let currentIndexPath = NSIndexPath(forItem: indexPath.item - 1, inSection: indexPath.section) openBrowser(cell, indexPath: currentIndexPath, models: alassetModels) } } //MARK: - PhotoLibraryCellDelegate代理 extension PhotoViewController: PhotoLibraryCellDelegate{ func countCanSelected() -> Bool { return countPhoto < 9 ? true : false } func doSelectedPhoto(index: Int, checked: Bool) { if checked{ countPhoto = countPhoto + 1 alassetModels[index].isChecked = true }else{ countPhoto = countPhoto - 1 alassetModels[index].isChecked = false } dealCountPhoto() } func dealCountPhoto(){ if countPhoto > 0{ rightButton.setTitle("下一步(\(countPhoto))", forState: .Normal) rightButton.frame.size = CGSize(width: 90, height: 28) rightButton.selected = true rightButton.enabled = true previewBtn.enabled = true }else{ rightButton.frame.size = CGSize(width: 70, height: 28) rightButton.setTitle("下一步", forState: .Normal) rightButton.selected = false rightButton.enabled = false previewBtn.enabled = false } } } //MARK: - UIViewControllerTransitioningDelegate代理 extension PhotoViewController: UIViewControllerTransitioningDelegate{ func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return previewPresentAnimator } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return previewDismissAnimator } } //MARK: - UIImagePickerControllerDelegate代理 extension PhotoViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{ func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { //TODO 待完善 var _selectedPhoto = [ALAssentModel]() let aModel = ALAssentModel(alsseet: nil) aModel.takePhtoto = image _selectedPhoto.append(aModel) NSNotificationCenter.defaultCenter().postNotificationName(SelectedPhotoDone, object: self, userInfo: ["alassentModels" : _selectedPhoto]) picker.dismissViewControllerAnimated(true, completion: nil) navigationController?.popViewControllerAnimated(true) } } //MARK: - 读取相册 extension PhotoViewController { func loadAssetsGroups(){ loadAssetsGroupsWithTypes(types) { [unowned self] (groups) -> () in if groups.count > 0{ self.titleButton.enabled = true self.selectAssetsGroup = groups.first self.alassentGroups = groups self.popoverView = PPopoverView(alasentGroupModels: groups) }else{ self.titleButton.enabled = false } } } //MARK: - 读取所有组 func loadAssetsGroupsWithTypes(types:[UInt32], completion: (groups: [ALAssetsGroup])->()){ var assentGroups = [ALAssetsGroup]() var numberOfFinishedTypes = 0 for _type in types{ PhotoViewController.assetsLibrary.enumerateGroupsWithTypes(_type, usingBlock: { (assentGroup, stop) -> Void in if let _group = assentGroup { _group.setAssetsFilter(ALAssetsFilter.allPhotos()) if (_group.numberOfAssets() > 0) { assentGroups.append(_group) } }else{ numberOfFinishedTypes++ } if (numberOfFinishedTypes == self.types.count) { completion(groups: assentGroups) } }, failureBlock: { (error) -> Void in print(error.description) }) } } //MARK: - 读取组的所有图片 func loadAllAssetsForGroups(){ //alassetModels ALAssentModel //TODO self.alassetModels = [ALAssentModel]() let assentCount = selectAssetsGroup!.numberOfAssets() selectAssetsGroup!.enumerateAssetsUsingBlock({ (result, index, stop) -> Void in if let assent = result { let assentModel = ALAssentModel(alsseet: assent) self.alassetModels.append(assentModel) } if index == (assentCount - 1){ self.alassetModels = self.alassetModels.reverse() var _index = 1 for aModel in self.alassetModels{ aModel.orginIndex = _index _index = _index + 1 } //添加一条空数据 let alassentModel = ALAssentModel(alsseet: nil) alassentModel.isFirst = true self.alassetModels.insert(alassentModel, atIndex: 0) //处理已经选中的图片 self.dealSelectAlassent() self.collectionView.reloadData() stop } }) } } //MARK: - 标题按钮 class HeadButton: UIButton { //通过纯代码调用 override init(frame: CGRect) { super.init(frame: frame) setupUI() } //通过xib/storyboard调用 required init?(coder aDecoder: NSCoder) { //系统对initWithCoder的默认实现是报一个致命错误 // fatalError("init(coder:) has not been implemented") super.init(coder: aDecoder) setupUI() } private func setupUI(){ setImage(UIImage(named: "navigationbar_arrow_down"), forState: .Normal) setImage(UIImage(named: "navigationbar_arrow_up"), forState: .Selected) setTitleColor(UIColor.grayColor(), forState: .Normal) sizeToFit() } override func setTitle(title: String?, forState state: UIControlState) { super.setTitle((title ?? "") + " ", forState: state) } override func layoutSubviews() { super.layoutSubviews() /* //offsetInPlace用于控制控件移位(有时候可能不对,系统肯能会调用多次layoutSubviews) titleLabel?.frame.offsetInPlace(dx: -imageView!.frame.width, dy: 0) imageView?.frame.offsetInPlace(dx: titleLabel!.frame.width, dy: 0) */ titleLabel?.frame.origin.x = 0 imageView?.frame.origin.x = titleLabel!.frame.width } }
mit
ffc57e0b49e124f7b4ad13f6e3896e74
41.026465
217
0.643201
4.821297
false
false
false
false
tensorflow/swift-apis
Sources/Tensor/Random.swift
1
19761
// Copyright 2019 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #elseif os(Windows) import ucrt #else import Glibc #endif public typealias TensorFlowSeed = (graph: Int32, op: Int32) /// Generates a new random seed for TensorFlow. public func randomSeedForTensorFlow(using seed: TensorFlowSeed? = nil) -> TensorFlowSeed { var strongSeed = UInt64(0) if let s = seed { let bytes = (s.graph.bytes() + s.op.bytes())[...] let singleSeed = UInt64(bytes: bytes, startingAt: bytes.startIndex) strongSeed = UInt64(pow(Double(singleSeed % 2), Double(8 * 8))) } else { strongSeed = UInt64.random(in: UInt64.min..<UInt64.max) } // Many machine learning systems are likely to have many random number generators active at // once (e.g., in reinforcement learning we may have an environment running in multiple // processes). There is literature indicating that having linear correlations between seeds of // multiple PRNG's can correlate the outputs: // - http://blogs.unity3d.com/2015/01/07/a-primer-on-repeatable-random-numbers // - http://stackoverflow.com/questions/1554958/how-different-do-random-seeds-need-to-be // - http://dl.acm.org/citation.cfm?id=1276928 // Thus, for sanity we hash the generated seed before using it, This scheme is likely not // crypto-strength, but it should be good enough to get rid of simple correlations. // Reference: https://github.com/openai/gym/blob/master/gym/utils/seeding.py let hash = strongSeed.bytes().sha512() let graph = Int32(bytes: [hash[0], hash[1], hash[2], hash[3]], startingAt: 0) let op = Int32(bytes: [hash[4], hash[5], hash[6], hash[7]], startingAt: 0) return (graph: graph, op: op) } //===------------------------------------------------------------------------------------------===// // Random Number Generators //===------------------------------------------------------------------------------------------===// /// A type-erased random number generator. /// /// The `AnyRandomNumberGenerator` type forwards random number generating operations to an /// underlying random number generator, hiding its specific underlying type. public struct AnyRandomNumberGenerator: RandomNumberGenerator { @usableFromInline var _rng: RandomNumberGenerator /// - Parameter rng: A random number generator. @inlinable public init(_ rng: RandomNumberGenerator) { self._rng = rng } @inlinable public mutating func next() -> UInt64 { return self._rng.next() } } /// A type that provides seedable deterministic pseudo-random data. /// /// A SeedableRandomNumberGenerator can be used anywhere where a /// RandomNumberGenerator would be used. It is useful when the pseudo-random /// data needs to be reproducible across runs. /// /// Conforming to the SeedableRandomNumberGenerator Protocol /// ======================================================== /// /// To make a custom type conform to the `SeedableRandomNumberGenerator` /// protocol, implement the `init(seed: [UInt8])` initializer, as well as the /// requirements for `RandomNumberGenerator`. The values returned by `next()` /// must form a deterministic sequence that depends only on the seed provided /// upon initialization. public protocol SeedableRandomNumberGenerator: RandomNumberGenerator { init(seed: [UInt8]) init<T: BinaryInteger>(seed: T) } extension SeedableRandomNumberGenerator { public init<T: BinaryInteger>(seed: T) { var newSeed: [UInt8] = [] for i in 0..<seed.bitWidth / UInt8.bitWidth { newSeed.append(UInt8(truncatingIfNeeded: seed >> (UInt8.bitWidth * i))) } self.init(seed: newSeed) } } /// An implementation of `SeedableRandomNumberGenerator` using ARC4. /// /// ARC4 is a stream cipher that generates a pseudo-random stream of bytes. This /// PRNG uses the seed as its key. /// /// ARC4 is described in Schneier, B., "Applied Cryptography: Protocols, /// Algorithms, and Source Code in C", 2nd Edition, 1996. /// /// An individual generator is not thread-safe, but distinct generators do not /// share state. The random data generated is of high-quality, but is not /// suitable for cryptographic applications. @frozen public struct ARC4RandomNumberGenerator: SeedableRandomNumberGenerator { public static var global = ARC4RandomNumberGenerator(seed: UInt32(time(nil))) var state: [UInt8] = Array(0...255) var iPos: UInt8 = 0 var jPos: UInt8 = 0 /// Initialize ARC4RandomNumberGenerator using an array of UInt8. The array /// must have length between 1 and 256 inclusive. public init(seed: [UInt8]) { precondition(seed.count > 0, "Length of seed must be positive") precondition(seed.count <= 256, "Length of seed must be at most 256") var j: UInt8 = 0 for i: UInt8 in 0...255 { j &+= S(i) &+ seed[Int(i) % seed.count] swapAt(i, j) } } // Produce the next random UInt64 from the stream, and advance the internal // state. public mutating func next() -> UInt64 { var result: UInt64 = 0 for _ in 0..<UInt64.bitWidth / UInt8.bitWidth { result <<= UInt8.bitWidth result += UInt64(nextByte()) } return result } // Helper to access the state. private func S(_ index: UInt8) -> UInt8 { return state[Int(index)] } // Helper to swap elements of the state. private mutating func swapAt(_ i: UInt8, _ j: UInt8) { state.swapAt(Int(i), Int(j)) } // Generates the next byte in the keystream. private mutating func nextByte() -> UInt8 { iPos &+= 1 jPos &+= S(iPos) swapAt(iPos, jPos) return S(S(iPos) &+ S(jPos)) } } private typealias UInt32x2 = (UInt32, UInt32) private typealias UInt32x4 = (UInt32, UInt32, UInt32, UInt32) /// An implementation of `SeedableRandomNumberGenerator` using Threefry. /// Salmon et al. SC 2011. Parallel random numbers: as easy as 1, 2, 3. /// http://www.thesalmons.org/john/random123/papers/random123sc11.pdf /// /// This struct implements a 20-round Threefry2x32 PRNG. It must be seeded with /// a 64-bit value. /// /// An individual generator is not thread-safe, but distinct generators do not /// share state. The random data generated is of high-quality, but is not /// suitable for cryptographic applications. public struct ThreefryRandomNumberGenerator: SeedableRandomNumberGenerator { public static var global = ThreefryRandomNumberGenerator( uint64Seed: UInt64(time(nil)) ) private let rot: (UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32, UInt32) = ( 13, 15, 26, 6, 17, 29, 16, 24 ) private func rotl32(value: UInt32, n: UInt32) -> UInt32 { return (value << (n & 31)) | (value >> ((32 - n) & 31)) } private var ctr: UInt64 = 0 private let key: UInt32x2 private func random(forCtr ctr: UInt32x2, key: UInt32x2) -> UInt32x2 { let skeinKsParity32: UInt32 = 0x1BD1_1BDA let ks0 = key.0 let ks1 = key.1 let ks2 = skeinKsParity32 ^ key.0 ^ key.1 var X0 = ctr.0 var X1 = ctr.1 // 20 rounds // Key injection (r = 0) X0 &+= ks0 X1 &+= ks1 // R1 X0 &+= X1 X1 = rotl32(value: X1, n: rot.0) X1 ^= X0 // R2 X0 &+= X1 X1 = rotl32(value: X1, n: rot.1) X1 ^= X0 // R3 X0 &+= X1 X1 = rotl32(value: X1, n: rot.2) X1 ^= X0 // R4 X0 &+= X1 X1 = rotl32(value: X1, n: rot.3) X1 ^= X0 // Key injection (r = 1) X0 &+= ks1 X1 &+= (ks2 + 1) // R5 X0 &+= X1 X1 = rotl32(value: X1, n: rot.4) X1 ^= X0 // R6 X0 &+= X1 X1 = rotl32(value: X1, n: rot.5) X1 ^= X0 // R7 X0 &+= X1 X1 = rotl32(value: X1, n: rot.6) X1 ^= X0 // R8 X0 &+= X1 X1 = rotl32(value: X1, n: rot.7) X1 ^= X0 // Key injection (r = 2) X0 &+= ks2 X1 &+= (ks0 + 2) // R9 X0 &+= X1 X1 = rotl32(value: X1, n: rot.0) X1 ^= X0 // R10 X0 &+= X1 X1 = rotl32(value: X1, n: rot.1) X1 ^= X0 // R11 X0 &+= X1 X1 = rotl32(value: X1, n: rot.2) X1 ^= X0 // R12 X0 &+= X1 X1 = rotl32(value: X1, n: rot.3) X1 ^= X0 // Key injection (r = 3) X0 &+= ks0 X1 &+= (ks1 + 3) // R13 X0 &+= X1 X1 = rotl32(value: X1, n: rot.4) X1 ^= X0 // R14 X0 &+= X1 X1 = rotl32(value: X1, n: rot.5) X1 ^= X0 // R15 X0 &+= X1 X1 = rotl32(value: X1, n: rot.6) X1 ^= X0 // R16 X0 &+= X1 X1 = rotl32(value: X1, n: rot.7) X1 ^= X0 // Key injection (r = 4) X0 &+= ks1 X1 &+= (ks2 + 4) // R17 X0 &+= X1 X1 = rotl32(value: X1, n: rot.0) X1 ^= X0 // R18 X0 &+= X1 X1 = rotl32(value: X1, n: rot.1) X1 ^= X0 // R19 X0 &+= X1 X1 = rotl32(value: X1, n: rot.2) X1 ^= X0 // R20 X0 &+= X1 X1 = rotl32(value: X1, n: rot.3) X1 ^= X0 // Key injection (r = 5) X0 &+= ks2 X1 &+= (ks0 + 5) return (X0, X1) } internal init(uint64Seed seed: UInt64) { key = seed.vector2 } public init(seed: [UInt8]) { precondition(seed.count > 0, "Length of seed must be positive") precondition(seed.count <= 8, "Length of seed must be at most 8") var combinedSeed: UInt64 = 0 for (i, byte) in seed.enumerated() { combinedSeed += UInt64(byte) << UInt64(8 * i) } self.init(uint64Seed: combinedSeed) } public mutating func next() -> UInt64 { defer { ctr += 1 } return UInt64(vector: random(forCtr: ctr.vector2, key: key)) } } /// An implementation of `SeedableRandomNumberGenerator` using Philox. /// Salmon et al. SC 2011. Parallel random numbers: as easy as 1, 2, 3. /// http://www.thesalmons.org/john/random123/papers/random123sc11.pdf /// /// This struct implements a 10-round Philox4x32 PRNG. It must be seeded with /// a 64-bit value. /// /// An individual generator is not thread-safe, but distinct generators do not /// share state. The random data generated is of high-quality, but is not /// suitable for cryptographic applications. public struct PhiloxRandomNumberGenerator: SeedableRandomNumberGenerator { public static var global = PhiloxRandomNumberGenerator(uint64Seed: UInt64(time(nil))) private var ctr: UInt64 = 0 private let key: UInt32x2 // Since we generate two 64-bit values at a time, we only need to run the // generator every other invocation. private var useNextValue = false private var nextValue: UInt64 = 0 private func bump(key: UInt32x2) -> UInt32x2 { let bumpConstantHi: UInt32 = 0x9E37_79B9 let bumpConstantLo: UInt32 = 0xBB67_AE85 return (key.0 &+ bumpConstantHi, key.1 &+ bumpConstantLo) } private func round(ctr: UInt32x4, key: UInt32x2) -> UInt32x4 { let roundConstant0: UInt64 = 0xD251_1F53 let roundConstant1: UInt64 = 0xCD9E_8D57 let product0: UInt64 = roundConstant0 &* UInt64(ctr.0) let hi0 = UInt32(truncatingIfNeeded: product0 >> 32) let lo0 = UInt32(truncatingIfNeeded: (product0 & 0x0000_0000_FFFF_FFFF)) let product1: UInt64 = roundConstant1 &* UInt64(ctr.2) let hi1 = UInt32(truncatingIfNeeded: product1 >> 32) let lo1 = UInt32(truncatingIfNeeded: (product1 & 0x0000_0000_FFFF_FFFF)) return (hi1 ^ ctr.1 ^ key.0, lo1, hi0 ^ ctr.3 ^ key.1, lo0) } private func random(forCtr initialCtr: UInt32x4, key initialKey: UInt32x2) -> UInt32x4 { var ctr = initialCtr var key = initialKey // 10 rounds // R1 ctr = round(ctr: ctr, key: key) // R2 key = bump(key: key) ctr = round(ctr: ctr, key: key) // R3 key = bump(key: key) ctr = round(ctr: ctr, key: key) // R4 key = bump(key: key) ctr = round(ctr: ctr, key: key) // R5 key = bump(key: key) ctr = round(ctr: ctr, key: key) // R6 key = bump(key: key) ctr = round(ctr: ctr, key: key) // R7 key = bump(key: key) ctr = round(ctr: ctr, key: key) // R8 key = bump(key: key) ctr = round(ctr: ctr, key: key) // R9 key = bump(key: key) ctr = round(ctr: ctr, key: key) // R10 key = bump(key: key) ctr = round(ctr: ctr, key: key) return ctr } public init(uint64Seed seed: UInt64) { key = seed.vector2 } public init(seed: [UInt8]) { precondition(seed.count > 0, "Length of seed must be positive") precondition(seed.count <= 8, "Length of seed must be at most 8") var combinedSeed: UInt64 = 0 for (i, byte) in seed.enumerated() { combinedSeed += UInt64(byte) << UInt64(8 * i) } self.init(uint64Seed: combinedSeed) } public mutating func next() -> UInt64 { if useNextValue { useNextValue = false return nextValue } let (this, next) = makeUInt64Pair(random(forCtr: ctr.vector4, key: key)) useNextValue = true nextValue = next ctr += 1 return this } } /// Private helpers. extension UInt64 { fileprivate var vector2: UInt32x2 { let msb = UInt32(truncatingIfNeeded: self >> 32) let lsb = UInt32(truncatingIfNeeded: self & 0x0000_0000_FFFF_FFFF) return (msb, lsb) } fileprivate var vector4: UInt32x4 { let msb = UInt32(truncatingIfNeeded: self >> 32) let lsb = UInt32(truncatingIfNeeded: self & 0x0000_0000_FFFF_FFFF) return (0, 0, msb, lsb) } fileprivate init(vector: UInt32x2) { self = (UInt64(vector.0) << 32) + UInt64(vector.1) } } private func makeUInt64Pair(_ vector: UInt32x4) -> (UInt64, UInt64) { let a = (UInt64(vector.0) << 32) + UInt64(vector.1) let b = (UInt64(vector.2) << 32) + UInt64(vector.3) return (a, b) } //===------------------------------------------------------------------------------------------===// // Distributions //===------------------------------------------------------------------------------------------===// public protocol RandomDistribution { associatedtype Sample func next<G: RandomNumberGenerator>(using generator: inout G) -> Sample } @frozen public struct UniformIntegerDistribution<T: FixedWidthInteger>: RandomDistribution { public let lowerBound: T public let upperBound: T public init(lowerBound: T = T.self.min, upperBound: T = T.self.max) { self.lowerBound = lowerBound self.upperBound = upperBound } public func next<G: RandomNumberGenerator>(using rng: inout G) -> T { return T.random(in: lowerBound...upperBound, using: &rng) } } @frozen public struct UniformFloatingPointDistribution<T: BinaryFloatingPoint>: RandomDistribution where T.RawSignificand: FixedWidthInteger { public let lowerBound: T public let upperBound: T public init(lowerBound: T = 0, upperBound: T = 1) { self.lowerBound = lowerBound self.upperBound = upperBound } public func next<G: RandomNumberGenerator>(using rng: inout G) -> T { return T.random(in: lowerBound..<upperBound, using: &rng) } } @frozen public struct NormalDistribution<T: BinaryFloatingPoint>: RandomDistribution where T.RawSignificand: FixedWidthInteger { public let mean: T public let standardDeviation: T private let uniformDist = UniformFloatingPointDistribution<T>() public init(mean: T = 0, standardDeviation: T = 1) { self.mean = mean self.standardDeviation = standardDeviation } public func next<G: RandomNumberGenerator>(using rng: inout G) -> T { // FIXME: Box-Muller can generate two values for only a little more than the // cost of one. let u1 = uniformDist.next(using: &rng) let u2 = uniformDist.next(using: &rng) let r = (-2 * T(log(Double(u1)))).squareRoot() let theta: Double = 2 * Double.pi * Double(u2) let normal01 = r * T(cos(theta)) return mean + standardDeviation * normal01 } } @frozen public struct BetaDistribution: RandomDistribution { public let alpha: Float public let beta: Float private let uniformDistribution = UniformFloatingPointDistribution<Float>() public init(alpha: Float = 0, beta: Float = 1) { self.alpha = alpha self.beta = beta } public func next<G: RandomNumberGenerator>(using rng: inout G) -> Float { // Generate a sample using Cheng's sampling algorithm from: // R. C. H. Cheng, "Generating beta variates with nonintegral shape // parameters.". Communications of the ACM, 21, 317-322, 1978. let a = min(alpha, beta) let b = max(alpha, beta) if a > 1 { return BetaDistribution.chengsAlgorithmBB(alpha, a, b, using: &rng) } else { return BetaDistribution.chengsAlgorithmBC(alpha, b, a, using: &rng) } } /// Returns one sample from a Beta(alpha, beta) distribution using Cheng's BB /// algorithm, when both alpha and beta are greater than 1. /// /// - Parameters: /// - alpha: First Beta distribution shape parameter. /// - a: `min(alpha, beta)`. /// - b: `max(alpha, beta)`. /// - rng: Random number generator. /// /// - Returns: Sample obtained using Cheng's BB algorithm. private static func chengsAlgorithmBB<G: RandomNumberGenerator>( _ alpha0: Float, _ a: Float, _ b: Float, using rng: inout G ) -> Float { let alpha = a + b let beta = sqrtf((alpha - 2.0) / (2 * a * b - alpha)) let gamma = a + 1 / beta var r: Float = 0.0 var w: Float = 0.0 var t: Float = 0.0 repeat { let u1 = Float.random(in: 0.0...1.0, using: &rng) let u2 = Float.random(in: 0.0...1.0, using: &rng) let v = beta * (logf(u1) - log1pf(-u1)) r = gamma * v - 1.3862944 let z = u1 * u1 * u2 w = a * expf(v) let s = a + r - w if s + 2.609438 >= 5 * z { break } t = logf(z) if s >= t { break } } while r + alpha * (logf(alpha) - logf(b + w)) < t w = min(w, Float.greatestFiniteMagnitude) return a == alpha0 ? w / (b + w) : b / (b + w) } /// Returns one sample from a Beta(alpha, beta) distribution using Cheng's BC /// algorithm, when at least one of alpha and beta is less than 1. /// /// - Parameters: /// - alpha: First Beta distribution shape parameter. /// - a: `max(alpha, beta)`. /// - b: `min(alpha, beta)`. /// - rng: Random number generator. /// /// - Returns: Sample obtained using Cheng's BB algorithm. private static func chengsAlgorithmBC<G: RandomNumberGenerator>( _ alpha0: Float, _ a: Float, _ b: Float, using rng: inout G ) -> Float { let alpha = a + b let beta = 1 / b let delta = 1 + a - b let k1 = delta * (0.0138889 + 0.0416667 * b) / (a * beta - 0.777778) let k2 = 0.25 + (0.5 + 0.25 / delta) * b var w: Float = 0.0 while true { let u1 = Float.random(in: 0.0...1.0, using: &rng) let u2 = Float.random(in: 0.0...1.0, using: &rng) let y = u1 * u2 let z = u1 * y if u1 < 0.5 { if 0.25 * u2 + z - y >= k1 { continue } } else { if z <= 0.25 { let v = beta * (logf(u1) - log1pf(-u1)) w = a * expf(v) break } if z >= k2 { continue } } let v = beta * (logf(u1) - log1pf(-u1)) w = a * expf(v) if alpha * (logf(alpha) - logf(b + 1) + v) - 1.3862944 >= logf(z) { break } } w = min(w, Float.greatestFiniteMagnitude) return a == alpha0 ? w / (b + w) : b / (b + w) } }
apache-2.0
5818f3a51882e00a19b9c1b6a0ac11bf
29.49537
100
0.617378
3.351594
false
false
false
false
natecook1000/swift
test/Interpreter/formal_access.swift
1
1900
// RUN: %target-run-simple-swift-swift3 | %FileCheck %s // REQUIRES: executable_test // REQUIRES: swift_test_mode_optimize_none class C: CustomStringConvertible { var value: Int init(_ v: Int) { value = v } var description: String { return String(value) } } var global = [C(1), C(2)] print("Begin") print("1. global[0] == \(global[0])") // CHECK: Begin // CHECK-NEXT: 1. global[0] == 1 func doit(_ local: inout C) { print("2. local == \(local)") print("2. global[0] == \(global[0])") // CHECK-NEXT: 2. local == 1 // CHECK-NEXT: 2. global[0] == 1 // There's a connection between 'local' and 'global[0]'. local = C(4) print("3. local == \(local)") print("3. global[0] == \(global[0])") // CHECK-NEXT: 3. local == 4 // CHECK-NEXT: 3. global[0] == 4 // This assignment is to a different index and so is // not allowed to cause unspecified behavior. global[1] = C(5) print("4. local == \(local)") print("4. global[0] == \(global[0])") // CHECK-NEXT: 4. local == 4 // CHECK-NEXT: 4. global[0] == 4 // The connection is not yet broken. local = C(2) print("5. local == \(local)") print("5. global[0] == \(global[0])") // CHECK-NEXT: 5. local == 2 // CHECK-NEXT: 5. global[0] == 4 // This assignment structurally changes 'global' while a // simultaneous modification is occurring to it. This is // allowed to have unspecified behavior but not to crash. global.append(C(3)) print("6. local == \(local)") print("6. global[0] == \(global[0])") // CHECK-NEXT: 6. local == 2 // CHECK-NEXT: 6. global[0] == 4 // Note that here the connection is broken. local = C(7) print("7. local == \(local)") print("7. global[0] == \(global[0])") // CHECK-NEXT: 7. local == 7 // CHECK-NEXT: 7. global[0] == 4 } doit(&global[0]) print("8. global[0] == \(global[0])") print("End") // CHECK-NEXT: 8. global[0] == 4 // CHECK-NEXT: End
apache-2.0
34a15936a7ba81b7820c8c44d9af95eb
26.941176
59
0.588421
3.030303
false
false
false
false
arvedviehweger/swift
test/DebugInfo/guard-let.swift
4
1131
// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s // RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s --check-prefix=CHECK2 func use<T>(_ t: T) {} public func f(_ i : Int?) { // CHECK: define {{.*}}@_T04main1fySiSgF // CHECK: %[[PHI:.*]] = phi // The shadow copy store should not have a location. // CHECK: store {{(i32|i64)}} %[[PHI]], {{(i32|i64)}}* %val.addr, align {{(4|8)}}, !dbg ![[DBG0:.*]] // CHECK: @llvm.dbg.declare(metadata {{(i32|i64)}}* %val.addr, {{.*}}, !dbg ![[DBG1:.*]] // CHECK: ![[F:.*]] = distinct !DISubprogram(name: "f", // CHECK: ![[DBG0]] = !DILocation(line: 0, scope: ![[F]]) // CHECK: ![[DBG1]] = !DILocation(line: [[@LINE+1]], guard let val = i else { return } use(val) } public func g(_ s : String?) { // CHECK2: define {{.*}}@_T04main1gySSSgF // The shadow copy store should not have a location. // CHECK2: getelementptr inbounds {{.*}} %s.debug, {{.*}}, !dbg ![[DBG0:.*]] // CHECK2: ![[G:.*]] = distinct !DISubprogram(name: "g", // CHECK2: ![[DBG0]] = !DILocation(line: 0, scope: ![[G]]) guard let val = s else { return } use(val) }
apache-2.0
d3ea50860ad5a4a4a8df289b4f34324e
39.392857
102
0.554377
2.992063
false
false
false
false
barijaona/vienna-rss
Vienna/Sources/Main window/TabbedBrowserViewController.swift
1
13312
// // TabbedBrowserViewController.swift // Vienna // // Copyright 2018 Tassilo Karge // // 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 // // https://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 Cocoa import MMTabBarView import WebKit class TabbedBrowserViewController: NSViewController, RSSSource { @IBOutlet private(set) weak var tabBar: MMTabBarView? { didSet { guard let tabBar = self.tabBar else { return } tabBar.setStyleNamed("Mojave") tabBar.onlyShowCloseOnHover = true tabBar.canCloseOnlyTab = false tabBar.disableTabClose = false tabBar.allowsBackgroundTabClosing = true tabBar.hideForSingleTab = true tabBar.showAddTabButton = true tabBar.buttonMinWidth = 120 tabBar.useOverflowMenu = true tabBar.automaticallyAnimates = true // TODO: figure out what this property means tabBar.allowsScrubbing = true } } @IBOutlet private(set) weak var tabView: NSTabView? /// The tab view item configured with the view that shall be in the first /// fixed (e.g. bookmarks). This method will set the primary tab the first /// time it is called. var primaryTab: NSTabViewItem? { didSet { // Temove from tabView if there was a prevous primary tab if let primaryTab = oldValue { self.closeTab(primaryTab) } if let primaryTab = self.primaryTab { tabView?.insertTabViewItem(primaryTab, at: 0) tabBar?.select(primaryTab) } } } var restoredTabs = false var activeTab: Tab? { tabView?.selectedTabViewItem?.viewController as? Tab } var browserTabCount: Int { tabView?.numberOfTabViewItems ?? 0 } weak var rssSubscriber: RSSSubscriber? { didSet { for source in tabView?.tabViewItems ?? [] { (source as? RSSSource)?.rssSubscriber = self.rssSubscriber } } } weak var contextMenuDelegate: BrowserContextMenuDelegate? override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder: NSCoder) { guard let tabBar = coder.decodeObject(of: MMTabBarView.self, forKey: "tabBar"), let tabView = coder.decodeObject(of: NSTabView.self, forKey: "tabView"), let primaryTab = coder.decodeObject(of: NSTabViewItem.self, forKey: "primaryTab") else { return nil } self.tabBar = tabBar self.tabView = tabView self.primaryTab = primaryTab super.init(coder: coder) } override func encode(with aCoder: NSCoder) { aCoder.encode(tabBar, forKey: "tabBar") aCoder.encode(tabBar, forKey: "tabView") aCoder.encode(tabBar, forKey: "primaryTab") } override func viewWillAppear() { super.viewWillAppear() if !restoredTabs { // Defer to avoid loading first tab, because primary tab is set // after view load. restoreTabs() restoredTabs = true } } func restoreTabs() { guard let tabLinks = Preferences.standard.array(forKey: "TabList") as? [String] else { return } let tabTitles = Preferences.standard.object(forKey: "TabTitleDict") as? [String: String] for urlString in tabLinks { guard let url = URL(string: urlString) else { continue } let tab = createNewTab(url, inBackground: true, load: false) as? BrowserTab tab?.title = tabTitles?[urlString] } } func saveOpenTabs() { let tabsOptional = tabBar?.tabView.tabViewItems.compactMap { $0.viewController as? BrowserTab } guard let tabs = tabsOptional else { return } let tabLinks = tabs.compactMap { $0.tabUrl?.absoluteString } let tabTitleList: [(String, String)] = tabs.filter { $0.tabUrl != nil && $0.title != nil }.map { ($0.tabUrl?.absoluteString ?? "", $0.title ?? "") } let tabTitles = Dictionary(tabTitleList) { $1 } Preferences.standard.setArray(tabLinks as [Any], forKey: "TabList") Preferences.standard.setObject(tabTitles, forKey: "TabTitleDict") Preferences.standard.save() } func closeTab(_ tabViewItem: NSTabViewItem) { self.tabBar?.close(tabViewItem) } } extension TabbedBrowserViewController: Browser { func createNewTab(_ url: URL?, inBackground: Bool, load: Bool) -> Tab { createNewTab(url, inBackground: inBackground, load: load, insertAt: nil) } func createNewTab(_ request: URLRequest, config: WKWebViewConfiguration, inBackground: Bool, insertAt index: Int? = nil) -> Tab { let newTab = BrowserTab(request, config: config) return initNewTab(newTab, request.url, false, inBackground, insertAt: index) } func createNewTab(_ url: URL? = nil, inBackground: Bool = false, load: Bool = false, insertAt index: Int? = nil) -> Tab { let newTab = BrowserTab() return initNewTab(newTab, url, load, inBackground, insertAt: index) } private func initNewTab(_ newTab: BrowserTab, _ url: URL?, _ load: Bool, _ inBackground: Bool, insertAt index: Int? = nil) -> Tab { newTab.rssSubscriber = self.rssSubscriber let newTabViewItem = TitleChangingTabViewItem(viewController: newTab) newTabViewItem.hasCloseButton = true // This must be executed after setup of titleChangingTabViewItem to // observe new title properly. newTab.tabUrl = url if load { newTab.loadTab() } if let index = index { tabView?.insertTabViewItem(newTabViewItem, at: index) } else { tabView?.addTabViewItem(newTabViewItem) } if !inBackground { tabBar?.select(newTabViewItem) if load { newTab.webView.becomeFirstResponder() } else { newTab.activateAddressBar() } // TODO: make first responder? } newTab.webView.contextMenuProvider = self // TODO: tab view order return newTab } func switchToPrimaryTab() { if self.primaryTab != nil { self.tabView?.selectTabViewItem(at: 0) } } func showPreviousTab() { self.tabView?.selectPreviousTabViewItem(nil) } func showNextTab() { self.tabView?.selectNextTabViewItem(nil) } func closeActiveTab() { if let selectedTabViewItem = self.tabView?.selectedTabViewItem { self.closeTab(selectedTabViewItem) } } func closeAllTabs() { self.tabView?.tabViewItems.filter { $0 != primaryTab } .forEach(closeTab) } func getTextSelection() -> String { // TODO: implement return "" } func getActiveTabHTML() -> String { // TODO: implement return "" } func getActiveTabURL() -> URL? { // TODO: implement return URL(string: "") } } extension TabbedBrowserViewController: MMTabBarViewDelegate { func tabView(_ aTabView: NSTabView, shouldClose tabViewItem: NSTabViewItem) -> Bool { tabViewItem != primaryTab } func tabView(_ aTabView: NSTabView, willClose tabViewItem: NSTabViewItem) { guard let tab = tabViewItem.viewController as? Tab else { return } tab.closeTab() } func tabView(_ aTabView: NSTabView, selectOnClosing tabViewItem: NSTabViewItem) -> NSTabViewItem? { // Select tab item on the right of currently selected item. Cannot // select tab on the right, if selected tab is rightmost one. if let tabView = self.tabBar?.tabView, let selected = tabBar?.selectedTabViewItem, selected == tabViewItem, tabViewItem != tabView.tabViewItems.last, let indexToSelect = tabView.tabViewItems.firstIndex(of: selected)?.advanced(by: 1) { return tabView.tabViewItems[indexToSelect] } else { // Default (left of currently selected item / no change if deleted // item not selected) return nil } } func tabView(_ aTabView: NSTabView, menuFor tabViewItem: NSTabViewItem) -> NSMenu { // TODO: return menu corresponding to browser or primary tab view item return NSMenu() } func tabView(_ aTabView: NSTabView, shouldDrag tabViewItem: NSTabViewItem, in tabBarView: MMTabBarView) -> Bool { tabViewItem != primaryTab } func tabView(_ aTabView: NSTabView, validateDrop sender: NSDraggingInfo, proposedItem tabViewItem: NSTabViewItem, proposedIndex: UInt, in tabBarView: MMTabBarView) -> NSDragOperation { proposedIndex != 0 ? [.every] : [] } func tabView(_ aTabView: NSTabView, validateSlideOfProposedItem tabViewItem: NSTabViewItem, proposedIndex: UInt, in tabBarView: MMTabBarView) -> NSDragOperation { (tabViewItem != primaryTab && proposedIndex != 0) ? [.every] : [] } func addNewTab(to aTabView: NSTabView) { _ = self.createNewTab() } func tabView(_ tabView: NSTabView, willSelect tabViewItem: NSTabViewItem?) { let tab = (tabViewItem?.viewController as? BrowserTab) if let loaded = tab?.loadedTab, !loaded { tab?.loadTab() } } func tabView(_ tabView: NSTabView, didSelect tabViewItem: NSTabViewItem?) { NotificationCenter.default.post(name: NSNotification.Name(rawValue: "MA_Notify_TabChanged"), object: tabViewItem?.view) } } // MARK: WKUIDelegate + BrowserContextMenuDelegate extension TabbedBrowserViewController: CustomWKUIDelegate { // TODO: implement functionality for alerts and maybe peek actions func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { let newTab = self.createNewTab(navigationAction.request, config: configuration, inBackground: false, insertAt: getIndexAfterSelected()) if let webView = webView as? CustomWKWebView { // The listeners are removed from the old webview userContentController on creating the new one, restore them webView.resetScriptListeners() } return (newTab as? BrowserTab)?.webView } func contextMenuItemsFor(purpose: WKWebViewContextMenuContext, existingMenuItems: [NSMenuItem]) -> [NSMenuItem] { var menuItems = existingMenuItems switch purpose { case .page(url: _): break case .link(let url): addLinkMenuCustomizations(&menuItems, url) case .picture: break case .pictureLink(image: _, link: let link): addLinkMenuCustomizations(&menuItems, link) case .text: break } return self.contextMenuDelegate? .contextMenuItemsFor(purpose: purpose, existingMenuItems: menuItems) ?? menuItems } private func addLinkMenuCustomizations(_ menuItems: inout [NSMenuItem], _ url: (URL)) { guard let index = menuItems.firstIndex(where: { $0.identifier == .WKMenuItemOpenLinkInNewWindow }) else { return } menuItems[index].title = NSLocalizedString("Open Link in New Tab", comment: "") let openInBackgroundTitle = NSLocalizedString("Open Link in Background", comment: "") let openInBackgroundItem = NSMenuItem(title: openInBackgroundTitle, action: #selector(openLinkInBackground(menuItem:)), keyEquivalent: "") openInBackgroundItem.identifier = .WKMenuItemOpenLinkInBackground openInBackgroundItem.representedObject = url menuItems.insert(openInBackgroundItem, at: menuItems.index(after: index)) } @objc func openLinkInBackground(menuItem: NSMenuItem) { if let url = menuItem.representedObject as? URL { _ = self.createNewTab(url, inBackground: true, load: true, insertAt: getIndexAfterSelected()) } } @objc func contextMenuItemAction(menuItem: NSMenuItem) { self.contextMenuDelegate?.contextMenuItemAction(menuItem: menuItem) } private func getIndexAfterSelected() -> Int { guard let tabView = tabView, let selectedItem = tabView.selectedTabViewItem else { return 0 } let selectedIndex = tabView.tabViewItems.firstIndex(of: selectedItem) ?? 0 return tabView.tabViewItems.index(after: selectedIndex) } }
apache-2.0
4badbdacfc0e40b869ff802ea515b635
34.404255
188
0.637169
4.809249
false
false
false
false
huangboju/Moots
UICollectionViewLayout/SpreadsheetView-master/Framework/Sources/ScrollPosition.swift
3
1850
// // ScrollPosition.swift // SpreadsheetView // // Created by Kishikawa Katsumi on 4/23/17. // Copyright © 2017 Kishikawa Katsumi. All rights reserved. // import Foundation public struct ScrollPosition: OptionSet { // The vertical positions are mutually exclusive to each other, but are bitwise or-able with the horizontal scroll positions. // Combining positions from the same grouping (horizontal or vertical) will result in an NSInvalidArgumentException. public static var top = ScrollPosition(rawValue: 1 << 0) public static var centeredVertically = ScrollPosition(rawValue: 1 << 1) public static var bottom = ScrollPosition(rawValue: 1 << 2) // Likewise, the horizontal positions are mutually exclusive to each other. public static var left = ScrollPosition(rawValue: 1 << 3) public static var centeredHorizontally = ScrollPosition(rawValue: 1 << 4) public static var right = ScrollPosition(rawValue: 1 << 5) public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } } extension ScrollPosition: CustomStringConvertible, CustomDebugStringConvertible { public var description: String { var options = [String]() if contains(.top) { options.append(".top") } if contains(.centeredVertically) { options.append(".centeredVertically") } if contains(.bottom) { options.append(".bottom") } if contains(.left) { options.append(".left") } if contains(.centeredHorizontally) { options.append(".centeredHorizontally") } if contains(.right) { options.append(".right") } return options.description } public var debugDescription: String { return description } }
mit
a48b948e2592b475a16192d5a908b5eb
31.438596
129
0.655489
4.94385
false
false
false
false
forgo/BabySync
bbsync/mobile/iOS/Baby Sync/Baby Sync/AuthGoogle.swift
1
7026
// // AuthGoogle.swift // SignInBase // // Created by Elliott Richerson on 10/24/15. // Copyright © 2015 Elliott Richerson. All rights reserved. // import UIKit import Google import GoogleSignIn // MARK: - AuthGoogle Delegate Protocol protocol AuthGoogleDelegate { func didLogin(_ jwt: String, email: String) func didEncounterLogin(_ errorsAPI: [ErrorAPI]) } // MARK: - Google Info Struct struct AuthGoogleInfo { var userId: String = "" var accessToken: String = "" var name: String = "" var email: String = "" var pic: UIImage = AuthConstant.Default.ProfilePic init() { self.userId = "" self.accessToken = "" self.name = "" self.email = "" self.pic = AuthConstant.Default.ProfilePic } } // MARK: - AuthGoogle class AuthGoogle: NSObject, AuthAppMethod, AuthMethod, GIDSignInDelegate, GIDSignInUIDelegate, AuthGoogleDelegate { // Singleton static let sharedInstance = AuthGoogle() fileprivate override init() { self.signIn = GIDSignIn.sharedInstance() self.signIn.shouldFetchBasicProfile = true self.info = AuthGoogleInfo() } // Auth method classes invokes AuthDelegate methods to align SDK differences var delegate: AuthDelegate? // Google provided managers var signIn: GIDSignIn fileprivate var signInButton: GIDSignInButton! // To keep track of internally until login process resolves fileprivate var info: AuthGoogleInfo // MARK: - AuthAppMethod Protocol func configure(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [AnyHashable: Any]?) -> Bool { var configureError: NSError? GGLContext.sharedInstance().configureWithError(&configureError) assert(configureError == nil, "Error configuring Google services: \(configureError)") self.signIn.delegate = self self.delegate = Auth.sharedInstance return true } func openURL(_ application: UIApplication, openURL url: URL, sourceApplication: String?, annotation: AnyObject) -> Bool { return self.signIn.handle(url, sourceApplication: sourceApplication, annotation: annotation) } // MARK: - AuthMethod Protocol func isLoggedIn() -> Bool { if(self.signIn.currentUser != nil) { return true } else { return false } } func login(_ email: String? = nil, password: String? = nil) { self.signIn.signIn(); } func logout() { // Revokes authentication, token removed from keychain self.signIn.signOut() self.signIn.disconnect() } // MARK: - GIDSignInDelegate /* ------------------------------------------------------------------------- Note: The Sign-In SDK automatically acquires access tokens, but the access tokens will be refreshed only when you call signIn or signInSilently. To explicitly refresh the access token, call the refreshAccessTokenWithHandler: method. If you need the access token and want the SDK to automatically handle refreshing it, you can use the getAccessTokenWithHandler: method. Important: If you need to pass the currently signed-in user to a backend server, send the user's ID token to your backend server and validate the token on the server. */ func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) { if (error == nil) { // TODO: Can we leverage user.serverAuthCode for token validation? self.info.userId = user.userID // For client-side use only! self.info.accessToken = user.authentication.idToken // Safe to sendn to the server self.info.name = user.profile.name self.info.email = user.profile.email if(user.profile.hasImage) { // TODO: Profile pic retrieval is synchronous, do we care for login? let picURL: URL = user.profile.imageURL(withDimension: 256) let picData: Data = try! Data(contentsOf: picURL) self.info.pic = UIImage(data: picData)! } else { self.info.pic = AuthConstant.Default.ProfilePic } // We got some Google data, now let's validate on our own server! BabySync.service.login(.Google, email: self.info.email, password: nil, accessToken: self.info.accessToken) } else { self.delegate?.loginError(.Google, error: error) } } func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) { // Perform any operations when the user disconnects from app here. if (error == nil) { self.delegate?.didLogout(.Google) } else { self.delegate?.didFailToLogout(.Google, error: error) } } // MARK: - GIDSignInUIDelegate // The sign-in flow has finished selecting how to proceed, and the UI should no longer display // a spinner or other "please wait" element. func sign(inWillDispatch signIn: GIDSignIn!, error: Error!) { print("signInWillDispatch (Google)") // stop animating spinner } // If implemented, this method will be invoked when sign in needs to display a view controller. // The view controller should be displayed modally (via UIViewController's |presentViewController| // method, and not pushed unto a navigation controller's stack. func sign(_ signIn: GIDSignIn!, present viewController: UIViewController!) { print("signIn presentViewController (Google)") Auth.sharedInstance.loginViewController?.present(viewController, animated: true, completion: nil) } // If implemented, this method will be invoked when sign in needs to dismiss a view controller. // Typically, this should be implemented by calling |dismissViewController| on the passed // view controller. func sign(_ signIn: GIDSignIn!, dismiss viewController: UIViewController!) { print("signIn dismissViewController (Google)") Auth.sharedInstance.loginViewController?.dismiss(animated: true, completion: nil) } // MARK: - AuthGoogleDelegate func didLogin(_ jwt: String, email: String) { let authUser = AuthUser(service: .Google, userId: self.info.userId, accessToken: self.info.accessToken, name: self.info.name, email: self.info.email, pic: self.info.pic, jwt: jwt) self.delegate?.loginSuccess(.Google, user: authUser, wasAlreadyLoggedIn: false) } func didEncounterLogin(_ errorsAPI: [ErrorAPI]) { // TODO: Do we need to take into account errors past one if they exist? if(errorsAPI.count > 0) { let e: Error? = BabySync.errorFrom(errorsAPI[0]) self.delegate?.loginError(.Google, error: e) } } }
mit
47e204cff6a8bd9868ddea5a8b49dc10
37.812155
187
0.641993
4.805062
false
false
false
false
DannyvanSwieten/SwiftSignals
SwiftEngine/Scale.swift
1
2275
// // Scale.swift // SwiftEngine // // Created by Danny van Swieten on 2/18/16. // Copyright © 2016 Danny van Swieten. All rights reserved. // import Foundation enum Degree: String { case First = "I" case Second = "ii" case Third = "iii" case Fourth = "IV" case Fifth = "V" case Sixth = "vi" case Seventh = "vii" } class Scale { var notes = [Int]() var root = 0 init(notes: Int...) { self.notes = notes } subscript(degree: String) -> Chord { guard let d = Degree(rawValue: degree) else { return Chord(notes: 0) } switch(d) { case .First: return Chord(notes: notes[root], notes[(2 + root) % 7], notes[(4 + root) % 7]) case .Second: let offset = root + 1 return Chord(notes: notes[offset], notes[(2 + offset) % 7], notes[(4 + offset) % 7]) case .Third: let offset = root + 2 return Chord(notes: notes[offset], notes[(2 + offset) % 7], notes[(4 + offset) % 7]) case .Fourth: let offset = root + 3 return Chord(notes: notes[offset], notes[(2 + offset) % 7], notes[(4 + offset) % 7]) case .Fifth: let offset = root + 4 return Chord(notes: notes[offset], notes[(2 + offset) % 7], notes[(4 + offset) % 7]) case .Sixth: let offset = root + 5 return Chord(notes: notes[offset], notes[(2 + offset) % 7], notes[(4 + offset) % 7]) case .Seventh: let offset = root + 6 return Chord(notes: notes[offset], notes[(2 + offset) % 7], notes[(4 + offset) % 7]) } } } class MajorScale: Scale { init() { super.init(notes: 0, 2, 4, 5, 7, 9, 11) } func toMajor() { root = 0 } func toDorian() { root = 1 } func toPhrygian() { root = 2 } func toLydian() { root = 3 } func toMixolydian() { root = 4 } func toAeolian() { root = 5 } func toLocrian() { root = 6 } }
gpl-3.0
7744aea0919093f63b4f63e2fcdaa6f3
21.75
96
0.455585
3.777409
false
false
false
false
austinzheng/swift
test/decl/protocol/special/coding/struct_codable_simple.swift
34
1161
// RUN: %target-typecheck-verify-swift -verify-ignore-unknown // Simple structs with all Codable properties should get derived conformance to // Codable. struct SimpleStruct : Codable { var x: Int var y: Double static var z: String = "foo" // These lines have to be within the SimpleStruct type because CodingKeys // should be private. func foo() { // They should receive a synthesized CodingKeys enum. let _ = SimpleStruct.CodingKeys.self // The enum should have a case for each of the vars. let _ = SimpleStruct.CodingKeys.x let _ = SimpleStruct.CodingKeys.y // Static vars should not be part of the CodingKeys enum. let _ = SimpleStruct.CodingKeys.z // expected-error {{type 'SimpleStruct.CodingKeys' has no member 'z'}} } } // They should receive synthesized init(from:) and an encode(to:). let _ = SimpleStruct.init(from:) let _ = SimpleStruct.encode(to:) // The synthesized CodingKeys type should not be accessible from outside the // struct. let _ = SimpleStruct.CodingKeys.self // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}}
apache-2.0
dc318b4fa25ad0f75b89a5850cca653a
36.451613
121
0.692506
4.431298
false
false
false
false
seandavidmcgee/HumanKontactBeta
src/Pods/LiquidLoader/Pod/Classes/SimpleCircleLiquidEngine.swift
1
5633
// // SimpleCircleLiquidEngine.swift // LiquidLoading // // Created by Takuma Yoshida on 2015/08/19. // Copyright (c) 2015年 yoavlt. All rights reserved. // import Foundation import UIKit /** * This class is so fast, but allowed only same color. */ class SimpleCircleLiquidEngine { let radiusThresh: CGFloat private var layer: CALayer = CAShapeLayer() var color = UIColor.redColor() let ConnectThresh: CGFloat = 0.3 var angleThresh: CGFloat = 0.5 init(radiusThresh: CGFloat, angleThresh: CGFloat) { self.radiusThresh = radiusThresh self.angleThresh = angleThresh } func push(circle: LiquittableCircle, other: LiquittableCircle) -> [LiquittableCircle] { if let paths = generateConnectedPath(circle, other: other) { let layers = paths.map(self.constructLayer) layers.each(layer.addSublayer) return [circle, other] } return [] } func draw(parent: UIView) { parent.layer.addSublayer(layer) } func clear() { layer.removeFromSuperlayer() layer.sublayers?.each{ $0.removeFromSuperlayer() } layer = CAShapeLayer() } func constructLayer(path: UIBezierPath) -> CALayer { let pathBounds = CGPathGetBoundingBox(path.CGPath); let shape = CAShapeLayer() shape.fillColor = self.color.CGColor shape.path = path.CGPath shape.frame = CGRect(x: 0, y: 0, width: pathBounds.width, height: pathBounds.height) return shape } private func circleConnectedPoint(circle: LiquittableCircle, other: LiquittableCircle, angle: CGFloat) -> (CGPoint, CGPoint) { let vec = other.center.minus(circle.center) let radian = atan2(vec.y, vec.x) let p1 = circle.circlePoint(radian + angle) let p2 = circle.circlePoint(radian - angle) return (p1, p2) } private func circleConnectedPoint(circle: LiquittableCircle, other: LiquittableCircle) -> (CGPoint, CGPoint) { var ratio = circleRatio(circle, other: other) ratio = (ratio + ConnectThresh) / (1.0 + ConnectThresh) let angle = CGFloat(M_PI_2) * ratio return circleConnectedPoint(circle, other: other, angle: angle) } private func generateConnectedPath(circle: LiquittableCircle, other: LiquittableCircle) -> [UIBezierPath]? { if isConnected(circle, other: other) { let ratio = circleRatio(circle, other: other) switch ratio { case angleThresh...1.0: if let path = normalPath(circle, other: other) { return [path] } return nil case 0.0..<angleThresh: return splitPath(circle, other: other, ratio: ratio) default: return nil } } else { return nil } } private func normalPath(circle: LiquittableCircle, other: LiquittableCircle) -> UIBezierPath? { let (p1, p2) = circleConnectedPoint(circle, other: other) let (p3, p4) = circleConnectedPoint(other, other: circle) if let crossed = CGPoint.intersection(p1, to: p3, from2: p2, to2: p4) { return withBezier { path in let r = self.circleRatio(circle, other: other) path.moveToPoint(p1) let mul = p1.plus(p4).div(2).split(crossed, ratio: r * 1.25 - 0.25) path.addQuadCurveToPoint(p4, controlPoint: mul) path.addLineToPoint(p3) let mul2 = p2.plus(p3).div(2).split(crossed, ratio: r * 1.25 - 0.25) path.addQuadCurveToPoint(p2, controlPoint: mul2) } } return nil } private func splitPath(circle: LiquittableCircle, other: LiquittableCircle, ratio: CGFloat) -> [UIBezierPath] { let (p1, p2) = circleConnectedPoint(circle, other: other, angle: CGMath.degToRad(40)) let (p3, p4) = circleConnectedPoint(other, other: circle, angle: CGMath.degToRad(40)) if let crossed = CGPoint.intersection(p1, to: p3, from2: p2, to2: p4) { let (d1, _) = self.circleConnectedPoint(circle, other: other, angle: 0) let (d2, _) = self.circleConnectedPoint(other, other: circle, angle: 0) let r = (ratio - ConnectThresh) / (angleThresh - ConnectThresh) let a1 = d1.split(crossed.mid(d2), ratio: 1 - r) let part = withBezier { path in path.moveToPoint(p1) _ = a1.split(p1, ratio: ratio) _ = a1.split(p2, ratio: ratio) path.addQuadCurveToPoint(p2, controlPoint: a1) } let a2 = d2.split(crossed.mid(d1), ratio: 1 - r) let part2 = withBezier { path in path.moveToPoint(p3) _ = a2.split(p3, ratio: ratio) _ = a2.split(p4, ratio: ratio) path.addQuadCurveToPoint(p4, controlPoint: a2) } return [part, part2] } return [] } private func circleRatio(circle: LiquittableCircle, other: LiquittableCircle) -> CGFloat { let distance = other.center.minus(circle.center).length() let ratio = 1.0 - (distance - radiusThresh) / (circle.radius + other.radius + radiusThresh) return min(max(ratio, 0.0), 1.0) } func isConnected(circle: LiquittableCircle, other: LiquittableCircle) -> Bool { let distance = circle.center.minus(other.center).length() return distance - circle.radius - other.radius < radiusThresh } }
mit
d52a5648976f568b71efa560cad7ce51
36.54
130
0.597762
4.211668
false
false
false
false
nakau1/Formations
Formations/Sources/Modules/Team/Views/Edit/TeamEditHelpViewController.swift
1
858
// ============================================================================= // Formations // Copyright 2017 yuichi.nakayasu All rights reserved. // ============================================================================= import UIKit import Rswift // MARK: - Controller Definition - class TeamEditHelpViewController: UIViewController { enum Mode: String { case emblemImage, teamImage } private var delete: (() -> Void)! // MARK: ファクトリメソッド class func create(mode: Mode, delete: @escaping () -> Void) -> UIViewController { return R.storyboard.teamEditViewController().instatiate(self, id: mode.rawValue) { vc in vc.delete = delete } } @IBAction private func didTapDeleteButton() { dismiss() { self.delete() } } }
apache-2.0
44076cb0cd2cf70c5e27fc7c45fada0a
27.965517
96
0.494048
5.185185
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Keychain/Sources/KeychainKit/Query/GenericPasswordQuery.swift
1
1647
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation public struct GenericPasswordQuery: KeychainQueryProvider, Equatable { let itemClass: KeychainItemClass = .genericPassword let service: String let permission: KeychainPermission let accessGroup: String? let synchronizable: Bool public init( service: String ) { self.service = service accessGroup = nil permission = .afterFirstUnlock synchronizable = false } public init( service: String, accessGroup: String ) { self.service = service self.accessGroup = accessGroup permission = .afterFirstUnlock synchronizable = false } public init( service: String, accessGroup: String?, permission: KeychainPermission, synchronizable: Bool ) { self.service = service self.accessGroup = accessGroup self.permission = permission self.synchronizable = synchronizable } // MARK: - KeychainQuery public func query() -> [String: Any] { var query = [String: Any]() query[kSecClass as String] = itemClass.queryValue query[kSecAttrService as String] = service query[kSecAttrAccessible as String] = permission.queryValue if synchronizable { query[kSecAttrSynchronizable as String] = kCFBooleanTrue } #if !targetEnvironment(simulator) if let accessGroup = accessGroup { query[kSecAttrAccessGroup as String] = accessGroup } #endif return query } }
lgpl-3.0
4668f3ba3ce81ff31b39630a2805dd00
25.126984
70
0.630012
5.52349
false
false
false
false
yarshure/Surf
Surf/SFRuleWriter.swift
1
480
// // SFRuleWriter.swift // Surf // // Created by networkextension on 16/5/8. // Copyright © 2016年 yarshure. All rights reserved. // import Foundation //import SQLite //let rules = Table("rules") // //let id = Expression<Int64>("id") //let name = Expression<String>("name")//domain or IP/mask // //let type = Expression<Int64>("type") //let policy = Expression<Int64>("policy") //let proxyName = Expression<String>("proxyName") class SFRuleWriter { }
bsd-3-clause
356a6d9a16e43526819703ed1e52d0ff
16.035714
58
0.649895
3.359155
false
false
false
false
daaavid/TIY-Assignments
07--Jackpot/jackpot/jackpot/WinningNumberViewController.swift
1
1849
// // WinningNumberViewController.swift // jackpot // // Created by david on 10/14/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit class WinningNumberViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet var picker: UIPickerView! var delegate: PickerDelegate? var winningNumber: Array<Int> = [] 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 viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) delegate?.numberWasChosen(getWinningNumbers()) } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { //how many wheels return 6 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int //must return Int { //how many rows return 53 } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? //must return String { return "\(row)" } func getWinningNumbers() -> Array<Int> { for var x = 0; x <= 5; x++ { winningNumber.append(picker.selectedRowInComponent(x)) } let tempArray = winningNumber winningNumber = [] return tempArray } func formatTicket(ticketArray: Array<Int>) -> String { var ticketAsString = "" for number in ticketArray { ticketAsString = ticketAsString + "\(number)" + " " } return ticketAsString } }
cc0-1.0
680744f70f6a0779a5ec793e03a6490f
23.64
128
0.616883
4.994595
false
false
false
false
FutureXInc/kulture
Kultur/Kulture/RequestedContentTableViewCell.swift
1
1445
// // RequestedContentTableViewCell.swift // Kulture // // Created by bis on 5/13/17. // Copyright © 2017 FutureXInc. All rights reserved. // import UIKit import ParseUI import Parse class RequestedContentTableViewCell: UITableViewCell { @IBOutlet weak var kidNameLabel: UILabel! @IBOutlet weak var kidProfileImageView: PFImageView! @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var tagLabel: UILabel! var _contentRequest: PFObject? var contentRequest: PFObject? { set { _contentRequest = newValue let kid = UserCache.sharedInstance.getUser(newValue!["kidUserId"] as! String)! kidNameLabel.text = API.sharedInstance.toUpperCase(kid.firstName) kidProfileImageView.setImageWith(kid.profileImageURL) messageLabel.text = newValue!["message"] as? String tagLabel.text = newValue!["tag"] as? String kidProfileImageView.layer.cornerRadius = kidProfileImageView.frame.width / 2.0 kidProfileImageView.layer.masksToBounds = true } get { return _contentRequest } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
apache-2.0
a1db53b5dd1da68a8856b6cdc6f5fabe
27.313725
90
0.657895
4.861953
false
false
false
false
blinksh/blink
Blink/Commands/browse.swift
1
2663
////////////////////////////////////////////////////////////////////////////////// // // B L I N K // // Copyright (C) 2016-2019 Blink Mobile Shell Project // // This file is part of Blink. // // Blink 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. // // Blink 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 Blink. If not, see <http://www.gnu.org/licenses/>. // // In addition, Blink is also subject to certain additional terms under // GNU GPL version 3 section 7. // // You should have received a copy of these additional terms immediately // following the terms and conditions of the GNU General Public License // which accompanied the Blink Source Code. If not, see // <http://www.github.com/blinksh/blink>. // //////////////////////////////////////////////////////////////////////////////// import Foundation import NonStdIO import ArgumentParser import BlinkCode import Network struct BrowseCommand: NonStdIOCommand { static var configuration = CommandConfiguration( commandName: "browser", abstract: "Opens web page", discussion: discussion ) static let discussion = """ """ @OptionGroup var verboseOptions: VerboseOptions var io = NonStdIO.standart @Argument( help: "Path to connect to or http(s) vscode like editor url", transform: { guard let url = URL(string: $0) else { throw ArgumentParser.ValidationError("Invalid vscode url") } return url } ) var url: URL? mutating func run() throws { let session = Unmanaged<MCPSession>.fromOpaque(thread_context).takeUnretainedValue() let url = url ?? URL(string: "https://google.com")! DispatchQueue.main.async { session.device.view.addBrowserWebView(url, agent: "", injectUIO: false) } } } @_cdecl("browse_main") public func browse_main(argc: Int32, argv: Argv) -> Int32 { setvbuf(thread_stdin, nil, _IONBF, 0) setvbuf(thread_stdout, nil, _IONBF, 0) setvbuf(thread_stderr, nil, _IONBF, 0) let io = NonStdIO.standart io.in_ = InputStream(file: thread_stdin) io.out = OutputStream(file: thread_stdout) io.err = OutputStream(file: thread_stderr) return BrowseCommand.main(Array(argv.args(count: argc)[1...]), io: io) }
gpl-3.0
b0ea6f252bc0fb97023fbc386ba96659
29.609195
88
0.660533
4.071865
false
false
false
false
IAskWind/IAWExtensionTool
Pods/Easy/Easy/Classes/Core/EasyExtension.swift
1
69519
// // EasyExtension.swift // Easy // // Created by OctMon on 2018/9/28. // import UIKit public extension Optional { /// 是否为nil var isNone: Bool { switch self { case .none: return true default: return false } } /// 是否不为nil var isSome: Bool { switch self { case .some(_): return true default: return false } } /// 值不为空返回当前值, 没有返回defualt /// /// - Parameter default: 默认值 /// - Returns: 值 func or(_ default: Wrapped) -> Wrapped { return self ?? `default` } /// 有值则传递至闭包进行处理, 否则返回nil func and<T>(then: (Wrapped) throws -> T?) rethrows -> T? { guard let unwrapped = self else { return nil } return try then(unwrapped) } /// 弱解析 /// /// - Parameters: /// - do: 有值则处理事件 func unwrapped(_ do: (Wrapped) -> Void) { guard let unwapped = self else { return } `do`(unwapped) } /// 弱解析 /// /// - Parameters: /// - do: 有值则处理事件 /// - else: 值为 nil 则执行 else func unwrapped(_ do: (Wrapped) -> Void, else: (() -> Void)? = nil) -> Void { guard let unwapped = self else { `else`?() return } `do`(unwapped) } } public extension Optional where Wrapped == String { /// 为空返回 "" var orEmpty: String { return self ?? "" } } public extension Bool { /// 或 func or(_ other: @autoclosure () -> Bool) -> Bool { return self || other() } /// 或 func or(_ other: (() -> Bool)) -> Bool { return self || other() } /// 且 func and(_ other: @autoclosure () -> Bool) -> Bool { return self && other() } /// 且 func and(_ other: (() -> Bool)) -> Bool { return self && other() } } public extension Double { var digits: [Int] { var digits: [Int] = [] for char in String(self) { if let int = Int(String(char)) { digits.append(int) } } return digits } var abs: Double { return Swift.abs(self) } /// 本身的四舍五入 /** let num = 5.67 EasyLog.debug(num.round) // -> 6.0 */ var round: Double { return Foundation.round(self) } /// 大于本身的最小整数 /** let num = 5.67 EasyLog.debug(num.ceil) // -> 6.0 */ var ceil: Double { return Foundation.ceil(self) } /// 小于本身最大整数 /** let num = 5.67 EasyLog.debug(num.floor) // -> 5.0 */ var floor: Double { return Foundation.floor(self) } var displayPriceDivide100: String { return (self / 100).displayPrice } var displayPrice: String { return String(format: "%.2f", self) } } public extension String { var dispayPriceAutoZero: String { var price = self if price.hasSuffix(".00") { price.subString(to: price.count - 3) } return price } } public extension CGFloat { /// 本身的四舍五入 /** let num = 5.67 EasyLog.debug(num.round) // -> 6.0 */ var round: CGFloat { return Foundation.round(self) } /// 大于本身的最小整数 /** let num = 5.67 EasyLog.debug(num.ceil) // -> 6.0 */ var ceil: CGFloat { return Foundation.ceil(self) } /// 小于本身最大整数 /** let num = 5.67 EasyLog.debug(num.floor) // -> 5.0 */ var floor: CGFloat { return Foundation.floor(self) } /// CGSize /** CGSize(width: .screenWidth, height: 0) */ static var screenWidth: CGFloat { return EasyApp.screenWidth } /// CGSize /** CGSize(width: 0, height: .screenHeight) */ static var screenHeight: CGFloat { return EasyApp.screenHeight } } public extension Int { var abs: Int { return Swift.abs(self) } } public extension CGSize { var isEmpty: Bool { return isWidthEmpty || isHeightEmpty } var isWidthEmpty: Bool { return self.width <= 0 } var isHeightEmpty: Bool { return self.height <= 0 } func calcFlowHeight(in viewWidth: CGFloat) -> CGFloat { return height / width * viewWidth } } public extension CGRect { static var screenBounds: CGRect { return EasyApp.screenBounds } } public extension String { mutating func trimmedWithoutSpacesAndNewLines() { self = trimmingWithoutSpacesAndNewLines } var trimmingWithoutSpacesAndNewLines: String { return trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } mutating func trimmedAllWithoutSpacesAndNewLines() { self = trimmingAllWithoutSpacesAndNewLines } var trimmingAllWithoutSpacesAndNewLines: String { return replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "\n", with: "") } func replace(_ string: String, to: String) -> String { return self.replacingOccurrences(of: string, with: to) } func remove(_ string: String) -> String { return replace(string, to: "") } func remove(_ strings: [String]) -> String { var temp = self strings.forEach({ temp = temp.replace($0, to: "") }) return temp } /// 数组中是否包含该self /** let result1 = "octmon".is(in: ["oct_mon1234567", "89"]) EasyLog.debug(result1) // -> false let result2 = "octmon1234567".is(in: ["octmon1234567", "def"]) EasyLog.debug(result2) // -> true */ func `is`(in equleTo: [String]) -> Bool { return equleTo.contains(where: { self == $0 }) } /// 数组中是否包含该前缀 /** let result1 = "octmon".hasPrefixs(in: ["_octmon1234567", "89"]) EasyLog.debug(result1) // -> false let result2 = "octmon1234567".hasPrefixs(in: ["octmon1234567", "def"]) EasyLog.debug(result2) // -> true */ func hasPrefixs(in prefixs: [String]) -> Bool { return prefixs.contains(where: { self.hasPrefix($0) }) } /// 数组中是否包含该后缀 /** let result1 = "octmon".hasSuffixs(in: ["_octmon1234567", "mon8"]) EasyLog.debug(result1) // -> false let result2 = "octmon1234567".hasSuffixs(in: ["octmon1234567", "89"]) EasyLog.debug(result2) // -> true */ func hasSuffixs(in suffixs: [String]) -> Bool { return suffixs.contains(where: { self.hasSuffix($0) }) } /** let result1 = "octmon1234567".contains(in: ["abc", "d"]) EasyLog.debug(result1) // -> false let result2 = "octmon1234567".contains(in: ["abc", "1"]) EasyLog.debug(result2) // -> true */ func contains(in contains: [String]) -> Bool { return contains.contains(where: { self.contains($0) }) } mutating func reverse() { self = reversing } var reversing: String { return String(reversed()) } func components(_ separator: String) -> [String] { return components(separatedBy: separator).filter { return !$0.trimmingWithoutSpacesAndNewLines.isEmpty } } func contain(_ subStirng: String, caseSensitive: Bool = true) -> Bool { if !caseSensitive { return range(of: subStirng, options: .caseInsensitive) != nil } return range(of: subStirng) != nil } func count(of subString: String, caseSensitive: Bool = true) -> Int { if !caseSensitive { return lowercased().components(separatedBy: subString).count - 1 } return components(separatedBy: subString).count - 1 } func hasPrefix(_ prefix: String, caseSensitive: Bool = true) -> Bool { if !caseSensitive { return lowercased().hasPrefix(prefix.lowercased()) } return hasPrefix(prefix) } func hasSuffix(_ suffix: String, caseSensitive: Bool = true) -> Bool { if !caseSensitive { return lowercased().hasSuffix(suffix.lowercased()) } return hasSuffix(suffix) } func joined(separator: String) -> String { return map({ "\($0)" }).joined(separator: separator) } mutating func joining(_ separator: String) { self = joined(separator: separator) } /// 字符串截取 /// /// - Parameters: /// - from: 从下标from开始截取 /// - to: 截取多少位 mutating func subString(from: Int = 0, to: Int) { let fromIndex = index(startIndex, offsetBy: from) let toIndex = index(fromIndex, offsetBy: to) self = String(self[fromIndex..<toIndex]) } func copyToPasteboard() { UIPasteboard.general.string = self } var urlEncode: String? { return addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) } var urlEncodeValue: String { return urlEncode ?? self } var urlDecode: String? { return removingPercentEncoding } var urlDecodeValue: String { return urlDecode ?? self } } public extension String { var getAttributedString: NSMutableAttributedString { return NSMutableAttributedString(string: self) } func getAttributedString(font: UIFont) -> NSMutableAttributedString { return NSMutableAttributedString(string: self, attributes: [.font: font]) } func getAttributedString(font: UIFont, foregroundColor: UIColor) -> NSMutableAttributedString { return NSMutableAttributedString(string: self, attributes: [.font: font, .foregroundColor: foregroundColor]) } func getAttributedString(foregroundColor: UIColor) -> NSMutableAttributedString { return NSMutableAttributedString(string: self, attributes: [.foregroundColor: foregroundColor]) } func getAttributedString(_ attrs: [NSAttributedString.Key : Any]) -> NSMutableAttributedString { return NSMutableAttributedString(string: self, attributes: attrs) } func getWidth(forConstrainedHeight: CGFloat, font: UIFont, options: NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesFontLeading]) -> CGFloat { return ceil(getSize(forConstrainedSize: CGSize(width: CGFloat(Double.greatestFiniteMagnitude), height: forConstrainedHeight), font: font).width) } func getHeight(forConstrainedWidth: CGFloat, font: UIFont, options: NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesFontLeading]) -> CGFloat { return ceil(getSize(forConstrainedSize: CGSize(width: forConstrainedWidth, height: CGFloat(Double.greatestFiniteMagnitude)), font: font).height) } func getSize(forConstrainedSize: CGSize, font: UIFont, options: NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesFontLeading]) -> CGSize { return self.boundingRect(with: forConstrainedSize, options: options, attributes: [.font: font], context: nil).size } } public extension NSAttributedString { func getSize(forConstrainedSize: CGSize, options: NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesFontLeading]) -> CGSize { return self.boundingRect(with: forConstrainedSize, options: options, context: nil).size } } public extension NSMutableAttributedString { func append(title: String) -> NSMutableAttributedString { let mutableAttributedString = NSMutableAttributedString(attributedString: self) mutableAttributedString.append(title.getAttributedString) return mutableAttributedString } func append(title: String, font: UIFont, foregroundColor: UIColor) -> NSMutableAttributedString { let mutableAttributedString = NSMutableAttributedString(attributedString: self) mutableAttributedString.append(title.getAttributedString(font: font, foregroundColor: foregroundColor)) return mutableAttributedString } func append(title: String, foregroundColor: UIColor) -> NSMutableAttributedString { let mutableAttributedString = NSMutableAttributedString(attributedString: self) mutableAttributedString.append(title.getAttributedString(foregroundColor: foregroundColor)) return mutableAttributedString } func append(title: String, attrs: [NSAttributedString.Key : Any]) -> NSMutableAttributedString { let mutableAttributedString = NSMutableAttributedString(attributedString: self) mutableAttributedString.append(title.getAttributedString(attrs)) return mutableAttributedString } func append(lineSpacing: CGFloat) -> NSMutableAttributedString { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = lineSpacing addAttributes([.paragraphStyle: paragraphStyle], range: NSMakeRange(0, length)) return self } func append(font: UIFont) -> NSMutableAttributedString { addAttributes([.font: font], range: NSMakeRange(0, length)) return self } } public extension String { var toQRcode: UIImage? { return toCodeGenerator(filterName: "CIQRCodeGenerator") } var toBarcode: UIImage? { return toCodeGenerator(filterName: "CICode128BarcodeGenerator") } func toCodeGenerator(filterName: String) -> UIImage? { guard let filter = CIFilter(name: filterName) else { return nil } filter.setDefaults() guard let data = self.data(using: .utf8) else { return nil } filter.setValue(data, forKey: "inputMessage") if let outputImage = filter.outputImage { return UIImage(ciImage: outputImage) } return nil } } public extension URLRequest { private var easyRequestSeparator: String { return "\n->->->->->->->->->->Request->->->->->->->->->\n" } private func easyStatusCodeSeparator(statusCode: Int = NSURLErrorNotConnectedToInternet) -> String { return "\n----------------------\(statusCode)------------------->" } private var easyResponseSeparator: String { return "\n->->->->->->->->->->Response->->->->->->->->->\n" } @discardableResult func printRequestLog(isPrintBase64DecodeBody: Bool = false) -> String { return printRequestLog(isPrintBase64DecodeBody: isPrintBase64DecodeBody, separator: [easyRequestSeparator, easyRequestSeparator]) } @discardableResult private func printRequestLog(isPrintBase64DecodeBody: Bool = false, separator: [String]) -> String { var separator = Array(separator.reversed()) let _url = url?.absoluteString ?? "" let _httpMethod = httpMethod ?? "" let _timeout = timeoutInterval let _httpBody = httpBody?.toJsonString var log = "\(separator.popLast() ?? "")[URL]\t\t\(_url)\n[Method]\t\t\(_httpMethod)\n[Timeout]\t\(_timeout)" if let allHTTPHeaderFields = allHTTPHeaderFields, allHTTPHeaderFields.count > 0, let header = JSONSerialization.toJsonString(withJSONObject: allHTTPHeaderFields) { log += "\n[Header]\n\(header)" } if let body = _httpBody { log += "\n[Body]\n\(body)" if let json = Data(base64Encoded: body, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)?.toJsonString, isPrintBase64DecodeBody { log += "\n[Body -> Base64Decode]\n\(json)" } } log += "\(separator.popLast() ?? "")" EasyLog.print(log) return log } @discardableResult func printResponseLog(_ isPrintHeader: Bool = false, isPrintBase64DecodeBody: Bool = false, response: HTTPURLResponse?, data: Data?, error: Error?, requestDuration: TimeInterval?) -> (requestLog: String, responseLog: String) { var requestLog = "" var responseLog = "" if let response = response { requestLog = printRequestLog(isPrintBase64DecodeBody: isPrintBase64DecodeBody, separator: [easyResponseSeparator, easyStatusCodeSeparator(statusCode: response.statusCode)]) if let requestDuration = requestDuration { responseLog += "[Duration]\t\(requestDuration)" } if isPrintHeader, let header = JSONSerialization.toJsonString(withJSONObject: response.allHeaderFields) { responseLog += "\n[Header]\n\(header)" } } else { requestLog = printRequestLog(isPrintBase64DecodeBody: isPrintBase64DecodeBody, separator: [easyResponseSeparator, easyStatusCodeSeparator()]) if let requestDuration = requestDuration { responseLog += "[Duration]\t\(requestDuration)" } } if let error = error { responseLog += "\n[Error]\t\t\(error.localizedDescription)" } if let data = data { responseLog += "\n[Size]\t\t\(data)" if let data = data.toJsonString { responseLog += "\n[Data]\n\(data)" if let json = Data(base64Encoded: data, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)?.toJsonString, isPrintBase64DecodeBody { responseLog += "\n[Data -> Base64Decode]\n\(json)" } } } responseLog += easyResponseSeparator EasyLog.print(responseLog) return (requestLog, responseLog) } } public extension URLRequest { mutating func setHTTPHeaderFields(_ fields: [String: String?]) { fields.forEach({ setValue($0.value, forHTTPHeaderField: $0.key) }) } } public extension Dictionary { private static func value(for json: EasyParameters, in path: [String]) -> Any? { if path.count == 1 { return json[path[0]] as Any } var path = path return value(for: json, in: &path) } private static func value(for json: EasyParameters, in path: inout [String]) -> Any? { if let first = path.first, let json = json[first] as? EasyParameters { path.removeFirst() return value(for: json, in: &path) } if let last = path.last { return json[last] as Any } return nil } subscript(path: [String]) -> Any? { if let json = self as? EasyParameters { return Dictionary.value(for: json, in: path) } return nil } } public extension UIImage { convenience init?(for aClass: AnyClass, forResource bundleName: String, forImage imageName: String) { var resource = bundleName if !bundleName.hasSuffix(".bundle") { resource = bundleName + ".bundle" } if let url = Bundle(for: aClass).url(forResource: resource, withExtension: nil) { var file = "" if let tmp = Bundle(url: url)?.path(forResource: imageName, ofType: nil) { file = tmp } else if let tmp = Bundle(url: url)?.path(forResource: imageName + ".png", ofType: nil) { file = tmp } else if let tmp = Bundle(url: url)?.path(forResource: imageName + "@2x.png", ofType: nil) { file = tmp } self.init(contentsOfFile: file) } else { self.init() } } } public extension UIColor { static var hex333333: UIColor { return .hex(0x333333) } static var hex666666: UIColor { return .hex(0x666666) } static var hex999999: UIColor { return .hex(0x999999) } static var hexCCCCCC: UIColor { return .hex(0xCCCCCC) } static var textFieldPlaceholder: UIColor { struct Once { private init() { if let placeholderColor = (UITextField().then { $0.placeholder = " " }.value(forKeyPath: "_placeholderLabel.textColor")) as? UIColor { color = placeholderColor } } static var shared = Once() var color: UIColor! } return Once.shared.color } } public extension UIColor { var red: Int { var red: CGFloat = 0 getRed(&red, green: nil, blue: nil, alpha: nil) return Int(red * 255) } var green: Int { var green: CGFloat = 0 getRed(nil, green: &green, blue: nil, alpha: nil) return Int(green * 255) } var blue: Int { var blue: CGFloat = 0 getRed(nil, green: nil, blue: &blue, alpha: nil) return Int(blue * 255) } var alpha: CGFloat { var alpha: CGFloat = 0 getRed(nil, green: nil, blue: nil, alpha: &alpha) return alpha } var isLight: Bool { var white: CGFloat = 0.0 getWhite(&white, alpha: nil) return white >= 0.5 } var invertColor: UIColor { var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: nil) return UIColor(red:1.0 - r, green: 1.0 - g, blue: 1.0 - b, alpha: 1) } static var random: UIColor { return .rgb(red: Int(arc4random_uniform(255)), green: Int(arc4random_uniform(255)), blue: Int(arc4random_uniform(255))) } static func rgb(red: Int, green: Int, blue: Int, alpha: CGFloat = 1.0) -> UIColor { return UIColor(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(alpha)) } static func hex(_ hex: Int, alpha: CGFloat = 1.0) -> UIColor { return UIColor(red: CGFloat(((hex & 0xFF0000) >> 16)) / 255.0, green: CGFloat(((hex & 0xFF00) >> 8)) / 255.0, blue: CGFloat((hex & 0xFF)) / 255.0, alpha: alpha) } static func hex(_ hex: String) -> UIColor { let colorString: String = hex.replacingOccurrences(of: "#", with: "").uppercased() var alpha: CGFloat = 0.0, red: CGFloat = 0.0, green: CGFloat = 0.0, blue: CGFloat = 0.0 switch colorString.count { case 3: // #RGB alpha = 1.0 red = UIColor.colorComponentFrom(colorString, start: 0, lenght: 1) green = UIColor.colorComponentFrom(colorString, start: 1, lenght: 1) blue = UIColor.colorComponentFrom(colorString, start: 2, lenght: 1) case 4: // #ARGB alpha = UIColor.colorComponentFrom(colorString, start: 0, lenght: 1) red = UIColor.colorComponentFrom(colorString, start: 1, lenght: 1) green = UIColor.colorComponentFrom(colorString, start: 2, lenght: 1) blue = UIColor.colorComponentFrom(colorString, start: 3, lenght: 1) case 6: // #RRGGBB alpha = 1.0 red = UIColor.colorComponentFrom(colorString, start: 0, lenght: 2) green = UIColor.colorComponentFrom(colorString, start: 2, lenght: 2) blue = UIColor.colorComponentFrom(colorString, start: 4, lenght: 2) case 8: // #AARRGGBB alpha = UIColor.colorComponentFrom(colorString, start: 0, lenght: 2) red = UIColor.colorComponentFrom(colorString, start: 2, lenght: 2) green = UIColor.colorComponentFrom(colorString, start: 4, lenght: 2) blue = UIColor.colorComponentFrom(colorString, start: 6, lenght: 2) default: break } return UIColor(red:red, green:green, blue:blue, alpha:alpha) } private static func colorComponentFrom(_ string: String, start: Int, lenght: Int) -> CGFloat { var substring: NSString = string as NSString substring = substring.substring(with: NSMakeRange(start, lenght)) as NSString let fullHex = lenght == 2 ? substring as String : "\(substring)\(substring)" var hexComponent: CUnsignedInt = 0 Scanner(string: fullHex).scanHexInt32(&hexComponent) return CGFloat(hexComponent) / 255.0 } } public extension UIImage { static func setColor(_ color: UIColor, frame: CGRect = CGRect(x: 0, y: 0, width: 1, height: 1)) -> UIImage? { UIGraphicsBeginImageContext(frame.size) let context = UIGraphicsGetCurrentContext() context?.setFillColor(color.cgColor) context?.fill(frame) guard let cgImage = UIGraphicsGetImageFromCurrentImageContext()?.cgImage else { return nil } UIGraphicsEndImageContext() return UIImage(cgImage: cgImage, scale: 1.0, orientation: UIImage.Orientation.up) } func tint(_ color: UIColor) -> UIImage? { UIGraphicsBeginImageContextWithOptions(size, false, scale) let context = UIGraphicsGetCurrentContext() context?.translateBy(x: 0, y: size.height) context?.scaleBy(x: 1.0, y: -1.0) context?.setBlendMode(CGBlendMode.normal) let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) as CGRect guard let cgImage = cgImage else { return nil } context?.clip(to: rect, mask: cgImage) color.setFill() context?.fill(rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } /// 平铺 /// /// - Parameter size: 渲染尺寸 /// - Returns: 图片平铺生成指定大小图片 func tile(size: CGSize) -> UIImage? { return UIImage.setColor(UIColor(patternImage: self), frame: CGRect(origin: CGPoint.zero, size: size)) } /// 将图片缩放成指定尺寸(多余部分自动删除) /** let image = UIColor.red.toImage let newImage = image?.crop(to: CGSize(width: 400, height: 300)) */ func crop(to newSize: CGSize) -> UIImage? { let aspectWidth = newSize.width / size.width let aspectHeight = newSize.height / size.height let aspectRatio = max(aspectWidth, aspectHeight) var scaledImageRect = CGRect.zero scaledImageRect.size.width = size.width * aspectRatio scaledImageRect.size.height = size.height * aspectRatio scaledImageRect.origin.x = (newSize.width - size.width * aspectRatio) / 2.0 scaledImageRect.origin.y = (newSize.height - size.height * aspectRatio) / 2.0 UIGraphicsBeginImageContext(newSize) draw(in: scaledImageRect) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage } /// 将图片裁剪成指定比例(多余部分自动删除) /** // 将图片转成 4:3 比例 let newImage = image?.crop(ratio: 4/3) */ func crop(ratio: CGFloat) -> UIImage? { var newSize: CGSize if size.width / size.height > ratio { newSize = CGSize(width: size.height * ratio, height: size.height) } else { newSize = CGSize(width: size.width, height: size.width / ratio) } var rect = CGRect.zero rect.size.width = size.width rect.size.height = size.height rect.origin.x = (newSize.width - size.width ) / 2.0 rect.origin.y = (newSize.height - size.height ) / 2.0 UIGraphicsBeginImageContext(newSize) draw(in: rect) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage } func resize(to size: CGSize) -> UIImage { let resizedImage: UIImage UIGraphicsBeginImageContext(CGSize(width: size.width, height: size.height)) UIGraphicsGetCurrentContext()?.interpolationQuality = .none draw(in: CGRect(origin: CGPoint.zero, size: size)) resizedImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return resizedImage } static var launchImage: UIImage? { if let launchImage = launchImageInStoryboard { return launchImage } return launchImageInAssets } static var launchImageInAssets: UIImage? { guard let info = Bundle.main.infoDictionary else { return nil } if let imagesDict = info["UILaunchImages"] as? [[String: String]] { for dict in imagesDict { if EasyApp.screenSize.equalTo(NSCoder.cgSize(for: dict["UILaunchImageSize"]!)) { return UIImage(named: dict["UILaunchImageName"]!) } } let launchImageName = (info["UILaunchImageFile"] as? String) ?? "" if UIDevice.current.userInterfaceIdiom == .pad { if UIApplication.shared.statusBarOrientation.isPortrait { return UIImage(named: launchImageName + "-Portrait") } if UIDevice.current.orientation.isLandscape { return UIImage(named: launchImageName + "-Landscape") } } return UIImage(named: launchImageName) } return nil } static var launchImageInStoryboard: UIImage? { guard let launchStoryboardName = Bundle.main.infoDictionary?["UILaunchStoryboardName"] as? String else { return nil } let xib = Bundle.main.path(forResource: launchStoryboardName, ofType: "nib") if let path = xib, FileManager.default.fileExists(atPath: path), let view = UINib(nibName: launchStoryboardName, bundle: Bundle.main).instantiate(withOwner: nil, options: nil).first as? UIView { return view.toImage } guard let vc = UIStoryboard(name: launchStoryboardName, bundle: nil).instantiateInitialViewController() else { return nil } let view = vc.view view?.frame = EasyApp.screenBounds return view?.toImage } } public extension UIImage { var detectorQRCode: [CIQRCodeFeature]? { guard let cgImage = cgImage else { return nil } let ciImage = CIImage(cgImage: cgImage) guard let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh]) else { return nil } guard let features = detector.features(in: ciImage) as? [CIQRCodeFeature], features.count > 0 else { return nil } return features } } public extension UIFont { static var size6: UIFont { return UIFont.systemFont(ofSize: 6) } static var size7: UIFont { return UIFont.systemFont(ofSize: 7) } static var size8: UIFont { return UIFont.systemFont(ofSize: 8) } static var size9: UIFont { return UIFont.systemFont(ofSize: 9) } static var size10: UIFont { return UIFont.systemFont(ofSize: 10) } static var size11: UIFont { return UIFont.systemFont(ofSize: 11) } static var size12: UIFont { return UIFont.systemFont(ofSize: 12) } static var size13: UIFont { return UIFont.systemFont(ofSize: 13) } static var size14: UIFont { return UIFont.systemFont(ofSize: 14) } static var size15: UIFont { return UIFont.systemFont(ofSize: 15) } static var size16: UIFont { return UIFont.systemFont(ofSize: 16) } static var size17: UIFont { return UIFont.systemFont(ofSize: 17) } static var size18: UIFont { return UIFont.systemFont(ofSize: 18) } static var size19: UIFont { return UIFont.systemFont(ofSize: 19) } static var size20: UIFont { return UIFont.systemFont(ofSize: 20) } static var size21: UIFont { return UIFont.systemFont(ofSize: 21) } static var size22: UIFont { return UIFont.systemFont(ofSize: 22) } static var size23: UIFont { return UIFont.systemFont(ofSize: 23) } static var size24: UIFont { return UIFont.systemFont(ofSize: 24) } static var size28: UIFont { return UIFont.systemFont(ofSize: 28) } static var size32: UIFont { return UIFont.systemFont(ofSize: 32) } static var size36: UIFont { return UIFont.systemFont(ofSize: 36) } static var size48: UIFont { return UIFont.systemFont(ofSize: 48) } static var size64: UIFont { return UIFont.systemFont(ofSize: 64) } var semibold: UIFont { if #available(iOS 8.2, *) { return UIFont.systemFont(ofSize: pointSize, weight: .semibold) } else { return self } } var medium: UIFont { if #available(iOS 8.2, *) { return UIFont.systemFont(ofSize: pointSize, weight: .medium) } else { return self } } var regular: UIFont { if #available(iOS 8.2, *) { return UIFont.systemFont(ofSize: pointSize, weight: .regular) } else { return self } } } public extension UIButton { func setBackgroundImage(_ backgroundImage: UIImage?, cornerRadius: CGFloat, `for` state: UIControl.State = .normal) { setBackgroundImage(backgroundImage, for: state) clipsToBounds = true layer.cornerRadius = cornerRadius } func setBackgroundBorder(_ cornerRadius: CGFloat = 5, borderColor: UIColor = EasyGlobal.tint, borderWidth: CGFloat = 1) { clipsToBounds = true layer.cornerRadius = cornerRadius layer.borderColor = borderColor.cgColor layer.borderWidth = borderWidth } } public extension UITextField { /// 左内边距 func setLeft(padding: CGFloat) { let view = UIView(frame: CGRect(x: 0, y: 0, width: padding, height: 1)) view.backgroundColor = .clear leftView = view leftViewMode = .always } /// 右内边距 func setRight(padding: CGFloat) { let view = UIView(frame: CGRect(x: 0, y: 0, width: padding, height: 1)) view.backgroundColor = .clear rightView = view rightViewMode = .always } /// 左边icon func setLeftIcon(image: UIImage?, padding: CGFloat) { if let image = image { let imageView = UIImageView(image: image) imageView.contentMode = .left self.leftView = imageView self.leftView?.frame.size = CGSize(width: image.size.width + padding, height: image.size.height) self.leftViewMode = .always } } func setLimit(_ length: Int, handler: (() -> Void)? = nil) { NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: nil, queue: OperationQueue.main) { [weak self] (_) in guard let self = self else { return } if (((self.text! as NSString).length > length) && self.markedTextRange == nil) { self.text = (self.text! as NSString).substring(to: length) handler?() } } } func setDoneButton(barStyle: UIBarStyle = .default, title: String? = "完成") { let toolbar = UIToolbar() toolbar.items = [UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), UIBarButtonItem(title: title, style: .done, target: self, action: #selector(UITextField.doneAction))] toolbar.barStyle = barStyle toolbar.sizeToFit() inputAccessoryView = toolbar } @objc private func doneAction() { endEditing(true) } } public extension UITextView { func setLimit(_ length: Int, handler: (() -> Void)? = nil) { NotificationCenter.default.addObserver(forName: UITextView.textDidChangeNotification, object: nil, queue: OperationQueue.main) { [weak self] (notification) in guard let self = self else { return } if (((self.text! as NSString).length > length) && self.markedTextRange == nil) { self.text = (self.text! as NSString).substring(to: length) handler?() } } } } private var _easyPlaceholderColor: Void? private var _easyPlaceholder: Void? private var _easyPlaceholderTextView: Void? public extension UITextView { var placeholderColor: UIColor? { get { return objc_getAssociatedObject(self, &_easyPlaceholderColor) as? UIColor } set { objc_setAssociatedObject(self, &_easyPlaceholderColor, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC); setPlaceholder() } } var placeholder: String? { get { return objc_getAssociatedObject(self, &_easyPlaceholder) as? String } set { objc_setAssociatedObject(self, &_easyPlaceholder, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC); setPlaceholder() } } private var placeholderTextView: UITextView? { get { return objc_getAssociatedObject(self, &_easyPlaceholderTextView) as? UITextView } set { objc_setAssociatedObject(self, &_easyPlaceholderTextView, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private func setPlaceholder() { if placeholderTextView == nil { placeholderTextView = UITextView(frame: self.bounds).then { $0.isUserInteractionEnabled = false $0.font = font $0.frame.origin.x = 6 $0.textContainerInset = textContainerInset $0.textContainerInset.left = -5.3 addSubview($0) } } placeholderTextView?.do { $0.textColor = placeholderColor ?? UIColor.textFieldPlaceholder $0.text = placeholder } NotificationCenter.default.addObserver(self, selector: #selector(textDidChange), name: UITextView.textDidChangeNotification, object: nil) } @objc private func textDidChange() { if let placeholder = placeholderTextView { placeholder.isHidden = true if self.text != nil { if self.text == "" { placeholder.isHidden = false } } } } } public extension UITableView { func setHeaderZero() { setHeaderHeight(0.001) } func setFooterZero() { setFooterHeight(0.001) } func setHeaderHeight(_ height: CGFloat) { if height == 0 { setHeaderZero() return } let view = UIView() view.frame.size.height = height tableHeaderView = view } func setFooterHeight(_ height: CGFloat) { if height == 0 { setFooterZero() return } let view = UIView() view.frame.size.height = height tableFooterView = view } func registerReusableCell<T: UITableViewCell>(_ cell: T.Type) { let name = cell.toString let xib = Bundle.main.path(forResource: name, ofType: "nib") if let path = xib { let exists = FileManager.default.fileExists(atPath: path) if exists { register(UINib(nibName: name, bundle: Bundle.main), forCellReuseIdentifier: cell.toString) } } else { register(cell.self, forCellReuseIdentifier: cell.toString) } } func dequeueReusableCell<T: UITableViewCell>(with cell: T.Type = T.self) -> T { guard let reuseableCell = dequeueReusableCell(withIdentifier: cell.toString ) as? T else { fatalError("Failed to dequeue a cell with identifier \(cell.toString)") } return reuseableCell } func registerReusableHeaderFooterView<T: UITableViewHeaderFooterView>(_ headerFooterView: T.Type = T.self) { let name = headerFooterView.toString let xib = Bundle.main.path(forResource: name, ofType: "nib") if let path = xib { let exists = FileManager.default.fileExists(atPath: path) if exists { register(UINib(nibName: name, bundle: Bundle.main), forHeaderFooterViewReuseIdentifier: headerFooterView.toString) } } else { register(headerFooterView.self, forHeaderFooterViewReuseIdentifier: headerFooterView.toString) } } func dequeueReusableHeaderFooterView<T: UITableViewHeaderFooterView>(with type: T.Type = T.self) -> T { guard let view = dequeueReusableHeaderFooterView(withIdentifier: type.toString) as? T else { fatalError("Failed to dequeue a header footer view with identifier \(type.toString)") } return view } } public extension UICollectionView { func registerReusableCell<T: UICollectionViewCell>(_ cell: T.Type) { let name = cell.toString let xibPath = Bundle.main.path(forResource: name, ofType: "nib") if let path = xibPath { let exists = FileManager.default.fileExists(atPath: path) if exists { register(UINib(nibName: name, bundle: Bundle.main), forCellWithReuseIdentifier: cell.toString) return } } register(cell.self, forCellWithReuseIdentifier: cell.toString) } func dequeueReusableCell<T: UICollectionViewCell>(for indexPath: IndexPath, with cell: T.Type = T.self) -> T { guard let reuseableCell = dequeueReusableCell(withReuseIdentifier: cell.toString, for: indexPath) as? T else { fatalError("Failed to dequeue a cell with identifier \(cell.toString)") } return reuseableCell } func registerReusableView<T: UICollectionReusableView>(supplementaryViewType: T.Type = T.self, ofKind elementKind: String) { self.register(supplementaryViewType.self, forSupplementaryViewOfKind: elementKind, withReuseIdentifier: supplementaryViewType.toString) } func dequeueReusableSupplementaryView<T: UICollectionReusableView>(ofKind elementKind: String, for indexPath: IndexPath, viewType: T.Type = T.self) -> T { let view = self.dequeueReusableSupplementaryView(ofKind: elementKind, withReuseIdentifier: viewType.toString, for: indexPath) guard let typedView = view as? T else { fatalError( "Failed to dequeue a supplementary view with identifier \(viewType.toString) " + "matching type \(viewType.self) " ) } return typedView } } public extension UIView { var x: CGFloat { get { return self.frame.origin.x } set { self.frame.origin.x = newValue } } var y: CGFloat { get { return self.frame.origin.y } set { self.frame.origin.y = newValue } } var width: CGFloat { get { return self.frame.width } set { self.frame.size.width = newValue } } var height: CGFloat { get { return self.frame.height } set { self.frame.size.height = newValue } } var size: CGSize { get { return self.frame.size } set { self.frame.size = newValue } } var origin: CGPoint { get { return self.frame.origin } set { self.frame.origin = newValue } } var left: CGFloat { get { return self.frame.origin.x } set { self.frame.origin.x = newValue } } var right: CGFloat { get { return self.frame.origin.x + self.frame.size.width } set { self.frame.origin.x = newValue - self.frame.size.width } } var top: CGFloat { get { return self.frame.origin.y } set { self.frame.origin.y = newValue } } var bottom: CGFloat { get { return self.frame.origin.y + self.frame.size.height } set { self.frame.origin.y = newValue - self.frame.size.height } } var centerX: CGFloat { get { return self.center.x } set { self.center.x = newValue } } var centerY: CGFloat { get { return self.center.y } set { self.center.y = newValue } } func setCornerRadius(_ cornerRadius: CGFloat? = nil) { clipsToBounds = true if let cornerRadius = cornerRadius { layer.cornerRadius = cornerRadius } else { layer.cornerRadius = min(frame.size.height, frame.size.width) * 0.5 } } } public extension UIView { func superview<T>(with: T.Type) -> T? { if let view = superview as? T { return view } return nil } func view<T>(with: T.Type) -> T? { if let view = self as? T { return view } return nil } } public extension UIView { func addGradientLayer(startPoint: CGPoint, endPoint: CGPoint, colors: [UIColor], locations: [NSNumber]) { let gradientLayer = CAGradientLayer().then { $0.colors = colors.map { $0.cgColor } $0.startPoint = startPoint $0.endPoint = endPoint $0.locations = locations $0.frame = frame } layer.addSublayer(gradientLayer) } } private class EasyTapGestureRecognizer: UITapGestureRecognizer { private var handler: ((UITapGestureRecognizer) -> Void)? @objc convenience init(numberOfTapsRequired: Int = 1, numberOfTouchesRequired: Int = 1, handler: @escaping (UITapGestureRecognizer) -> Void) { self.init() self.numberOfTapsRequired = numberOfTapsRequired self.numberOfTouchesRequired = numberOfTouchesRequired self.handler = handler addTarget(self, action: #selector(EasyTapGestureRecognizer.action(_:))) } @objc private func action(_ tapGestureRecognizer: UITapGestureRecognizer) { handler?(tapGestureRecognizer) } } private class EasyLongPressGestureRecognizer: UILongPressGestureRecognizer { private var handler: ((UILongPressGestureRecognizer) -> Void)? @objc convenience init(numberOfTapsRequired: Int = 0, numberOfTouchesRequired: Int = 1, handler: @escaping (UILongPressGestureRecognizer) -> Void) { self.init() self.numberOfTapsRequired = numberOfTapsRequired self.numberOfTouchesRequired = numberOfTouchesRequired self.handler = handler addTarget(self, action: #selector(EasyLongPressGestureRecognizer.action(_:))) } @objc private func action(_ longPressGestureRecognizer: UILongPressGestureRecognizer) { handler?(longPressGestureRecognizer) } } private class EasyPanGestureRecognizer: UIPanGestureRecognizer { private var handler: ((UIPanGestureRecognizer) -> Void)? @objc convenience init(minimumNumberOfTouches: Int = 1, handler: @escaping (UIPanGestureRecognizer) -> Void) { self.init() self.minimumNumberOfTouches = minimumNumberOfTouches self.handler = handler addTarget(self, action: #selector(EasyPanGestureRecognizer.action(_:))) } @objc private func action(_ panGestureRecognizer: UIPanGestureRecognizer) { handler?(panGestureRecognizer) } } private class EasySwipeGestureRecognizer: UISwipeGestureRecognizer { private var handler: ((UISwipeGestureRecognizer) -> Void)? @objc convenience init(direction: UISwipeGestureRecognizer.Direction, numberOfTouchesRequired: Int = 1, handler: @escaping (UISwipeGestureRecognizer) -> Void) { self.init() self.direction = direction self.numberOfTouchesRequired = numberOfTouchesRequired self.handler = handler addTarget(self, action: #selector(EasySwipeGestureRecognizer.action(_:))) } @objc private func action(_ swipeGestureRecognizer: UISwipeGestureRecognizer) { handler?(swipeGestureRecognizer) } } private class EasyPinchGestureRecognizer: UIPinchGestureRecognizer { private var handler: ((UIPinchGestureRecognizer) -> Void)? @objc convenience init(handler: @escaping (UIPinchGestureRecognizer) -> Void) { self.init() self.handler = handler addTarget(self, action: #selector(EasyPinchGestureRecognizer.action(_:))) } @objc private func action(_ pinchGestureRecognizer: UIPinchGestureRecognizer) { handler?(pinchGestureRecognizer) } } private class EasyRotationGestureRecognizer: UIRotationGestureRecognizer { private var handler: ((UIRotationGestureRecognizer) -> Void)? @objc convenience init(handler: @escaping (UIRotationGestureRecognizer) -> Void) { self.init() self.handler = handler addTarget(self, action: #selector(EasyRotationGestureRecognizer.action(_:))) } @objc private func action(_ rotationGestureRecognizer: UIRotationGestureRecognizer) { handler?(rotationGestureRecognizer) } } public extension UIView { /// 点按 /// /// - Parameters: /// - numberOfTapsRequired: 手势点击数 /// - numberOfTouchesRequired: 手指个数 /// - handler: 使用 [unowned self] 或 [weak self] 避免循环引用 /// - Returns: UITapGestureRecognizer @discardableResult func tap(numberOfTapsRequired: Int = 1, numberOfTouchesRequired: Int = 1, handler: @escaping (UITapGestureRecognizer) -> Void) -> UITapGestureRecognizer { isUserInteractionEnabled = true let tapGestureRecognizer = EasyTapGestureRecognizer(numberOfTapsRequired: numberOfTapsRequired, numberOfTouchesRequired: numberOfTouchesRequired, handler: handler) addGestureRecognizer(tapGestureRecognizer) return tapGestureRecognizer } /// 长按 /// /// - Parameters: /// - numberOfTapsRequired: 手势点击数 /// - numberOfTouchesRequired: 手指个数 /// - handler: 使用 [unowned self] 或 [weak self] 避免循环引用 /// - Returns: UILongPressGestureRecognizer @discardableResult func longPress(numberOfTapsRequired: Int = 0, numberOfTouchesRequired: Int = 1, handler: @escaping (UILongPressGestureRecognizer) -> Void) -> UILongPressGestureRecognizer { isUserInteractionEnabled = true let longPressGestureRecognizer = EasyLongPressGestureRecognizer(numberOfTapsRequired: numberOfTapsRequired, numberOfTouchesRequired: numberOfTouchesRequired, handler: handler) addGestureRecognizer(longPressGestureRecognizer) return longPressGestureRecognizer } /// 拖动 /// /// - Parameters: /// - minimumNumberOfTouches: 最少手指个数 /// - handler: 使用 [unowned self] 或 [weak self] 避免循环引用 /// - Returns: UIPanGestureRecognizer @discardableResult func pan(minimumNumberOfTouches: Int = 1, handler: @escaping (UIPanGestureRecognizer) -> Void) -> UIPanGestureRecognizer { isUserInteractionEnabled = true let longPressGestureRecognizer = EasyPanGestureRecognizer(minimumNumberOfTouches: minimumNumberOfTouches, handler: handler) addGestureRecognizer(longPressGestureRecognizer) return longPressGestureRecognizer } /// 轻扫,支持四个方向的轻扫,但是不同的方向要分别定义轻扫手势 /// /// - Parameters: /// - direction: 方向 /// - numberOfTouchesRequired: 手指个数 /// - handler: 使用 [unowned self] 或 [weak self] 避免循环引用 /// - Returns: UISwipeGestureRecognizer @discardableResult func swipe(direction: UISwipeGestureRecognizer.Direction, numberOfTouchesRequired: Int = 1, handler: @escaping (UISwipeGestureRecognizer) -> Void) -> UISwipeGestureRecognizer { isUserInteractionEnabled = true let swpieGestureRecognizer = EasySwipeGestureRecognizer(direction: direction, numberOfTouchesRequired: numberOfTouchesRequired, handler: handler) addGestureRecognizer(swpieGestureRecognizer) return swpieGestureRecognizer } /// 捏合 /// /// - Parameter handler: 使用 [unowned self] 或 [weak self] 避免循环引用 /// - Returns: UIPinchGestureRecognizer @discardableResult func pinch(handler: @escaping (UIPinchGestureRecognizer) -> Void) -> UIPinchGestureRecognizer { isUserInteractionEnabled = true let pinchGestureRecognizer = EasyPinchGestureRecognizer(handler: handler) addGestureRecognizer(pinchGestureRecognizer) return pinchGestureRecognizer } /// 旋转 /// /// - Parameter handler: 使用 [unowned self] 或 [weak self] 避免循环引用 /// - Returns: UIRotationGestureRecognizer @discardableResult func rotation(handler: @escaping (UIRotationGestureRecognizer) -> Void) -> UIRotationGestureRecognizer { isUserInteractionEnabled = true let rotationGestureRecognizer = EasyRotationGestureRecognizer(handler: handler) addGestureRecognizer(rotationGestureRecognizer) return rotationGestureRecognizer } } public extension UIView { /// 摇一摇动画 func animationShake() { let shake: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform") shake.values = [NSValue(caTransform3D: CATransform3DMakeTranslation(-5.0, 0.0, 0.0)), NSValue(caTransform3D: CATransform3DMakeTranslation(5.0, 0.0, 0.0))] shake.autoreverses = true shake.repeatCount = 2.0 shake.duration = 0.07 layer.add(shake, forKey:"shake") } /// 脉冲动画 func animationPulse(_ duration: CFTimeInterval = 0.25) { UIView.animate(withDuration: TimeInterval(duration / 6), animations: { () -> Void in self.transform = CGAffineTransform(scaleX: 1.1, y: 1.1) }, completion: { (finished) -> Void in if finished { UIView.animate(withDuration: TimeInterval(duration / 6), animations: { () -> Void in self.transform = CGAffineTransform(scaleX: 0.96, y: 0.96) }, completion: { (finished: Bool) -> Void in if finished { UIView.animate(withDuration: TimeInterval(duration / 6), animations: { () -> Void in self.transform = CGAffineTransform(scaleX: 1.03, y: 1.03) }, completion: { (finished: Bool) -> Void in if finished { UIView.animate(withDuration: TimeInterval(duration / 6), animations: { () -> Void in self.transform = CGAffineTransform(scaleX: 0.985, y: 0.985) }, completion: { (finished: Bool) -> Void in if finished { UIView.animate(withDuration: TimeInterval(duration / 6), animations: { () -> Void in self.transform = CGAffineTransform(scaleX: 1.007, y: 1.007) }, completion: { (finished: Bool) -> Void in if finished { UIView.animate(withDuration: TimeInterval(duration / 6), animations: { () -> Void in self.transform = CGAffineTransform(scaleX: 1, y: 1) }) } }) } }) } }) } }) } }) } /// 心跳动画 func animationHeartbeat(_ duration: CFTimeInterval = 0.25) { let maxSize: CGFloat = 1.4, durationPerBeat: CFTimeInterval = 0.5 let animation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform") let scale1: CATransform3D = CATransform3DMakeScale(0.8, 0.8, 1) let scale2: CATransform3D = CATransform3DMakeScale(maxSize, maxSize, 1) let scale3: CATransform3D = CATransform3DMakeScale(maxSize - 0.3, maxSize - 0.3, 1) let scale4: CATransform3D = CATransform3DMakeScale(1.0, 1.0, 1) let frameValues: Array = [NSValue(caTransform3D: scale1), NSValue(caTransform3D: scale2), NSValue(caTransform3D: scale3), NSValue(caTransform3D: scale4)] animation.values = frameValues let frameTimes: Array = [NSNumber(value: 0.05 as Float), NSNumber(value: 0.2 as Float), NSNumber(value: 0.6 as Float), NSNumber(value: 1.0 as Float)] animation.keyTimes = frameTimes animation.fillMode = CAMediaTimingFillMode.forwards animation.duration = TimeInterval(durationPerBeat) animation.repeatCount = Float(duration / durationPerBeat) layer.add(animation, forKey: "heartbeat") } } public extension UIView { private var separatorTag: Int { return 990909 } private func addSeparator(isTopSeparator: Bool, color: UIColor = EasyGlobal.tableViewSeparatorColor, lineHeight: CGFloat = 0.5, left: CGFloat = 0, right: CGFloat = 0) { removeSeparator() let separatorView = UIView() separatorView.backgroundColor = color separatorView.tag = separatorTag addSubview(separatorView) separatorView.snp.makeConstraints({ (make) in make.height.equalTo(lineHeight) make.left.equalTo(self).offset(left) if isTopSeparator { make.top.equalTo(self) } else { make.bottom.equalTo(self) } make.right.equalTo(self).offset(-right) }) } func addSeparatorTop(color: UIColor = EasyGlobal.tableViewSeparatorColor, lineHeight: CGFloat = 0.5, left: CGFloat = 0, right: CGFloat = 0) { addSeparator(isTopSeparator: true, color: color, lineHeight: lineHeight, left: left, right: right) } func addSeparatorBottom(color: UIColor = EasyGlobal.tableViewSeparatorColor, lineHeight: CGFloat = 0.5, left: CGFloat = 0, right: CGFloat = 0) { addSeparator(isTopSeparator: false, color: color, lineHeight: lineHeight, left: left, right: right) } func removeSeparator() { subviews.forEach({ guard $0.tag == separatorTag else { return }; $0.removeFromSuperview() }) } func removeAllSubviews() { subviews.forEach({ $0.removeFromSuperview() }) } func removeAllSubviews(with type: AnyClass) { subviews.forEach({ if $0.isKind(of: type) { $0.removeFromSuperview() } }) } } #if canImport(SnapKit) import SnapKit public extension UIView { /// 页面底部添加按钮 /** let titles = ["确定".attributedString, "取消".attributedString] view.addBottomButton(titles: titles, height: 60, backgroundImages: titles.enumerated().map { $0.offset == 0 ? UIColor.red.toImage : UIColor.yellow.toImage }) { (offset) in Log.debug(offset) } */ func addBottomButton(titles: [NSAttributedString?], height: CGFloat, backgroundImages: [UIImage?], bottomMargin: CGFloat = 0, tap: @escaping (Int) -> Void) { var bottomButtons = [UIButton]() let count = titles.count for offset in 0..<count { let button = UIButton() button.addSeparatorTop() addSubview(button) button.snp.makeConstraints({ (make) in if offset == 0 { make.left.equalToSuperview() make.height.equalTo(height) make.bottom.equalToSuperview().offset(-bottomMargin) } else if offset > 0 { make.left.equalTo(bottomButtons[offset - 1].snp.right) make.size.equalTo(bottomButtons[offset - 1]) make.bottom.equalTo(bottomButtons[offset - 1]) if offset == count - 1 { make.right.equalToSuperview() } } if count == 1 { make.right.equalToSuperview() } }) button.setAttributedTitle(titles[offset], for: .normal) button.setBackgroundImage(backgroundImages[offset], cornerRadius: 0) button.tap { (_) in tap(offset) } bottomButtons.append(button) } } } #endif public extension UIViewController { func makeRootViewController(_ backgroundColor: UIColor = EasyGlobal.background) -> UIWindow { let main = UIWindow(frame: UIScreen.main.bounds) main.backgroundColor = backgroundColor main.rootViewController = self main.makeKeyAndVisible() return main } } public extension UIViewController { func hideKeyboardWhenTapped() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.hideKeyboard)) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } @objc private func hideKeyboard() { view.endEditing(true) } } public extension UIStackView { func addArrangedSubviews(_ views: [UIView?]) { views.compactMap({ $0 }).forEach { addArrangedSubview($0) } } /// 自定义元素后面的边距 /// /// - Parameters: /// - customSpacing: iOS11之前设置边距必须大于self.spacing,否则无效 /// - arrangedSubview: 当前元素 func addCustomSpacing(_ customSpacing: CGFloat, after arrangedSubview: UIView) { if #available(iOS 11.0, *) { self.setCustomSpacing(customSpacing, after: arrangedSubview) } else { let constant = customSpacing - spacing * 2 if constant < 0 { return } let separatorView = UIView() separatorView.translatesAutoresizingMaskIntoConstraints = false switch axis { case .horizontal: separatorView.widthAnchor.constraint(equalToConstant: constant).isActive = true case .vertical: separatorView.heightAnchor.constraint(equalToConstant: constant).isActive = true } if let index = self.arrangedSubviews.firstIndex(of: arrangedSubview) { insertArrangedSubview(separatorView, at: index + 1) } } } } public extension UIViewController { var navigationBottom: CGFloat { return EasyApp.statusBarHeight + (self.navigationController?.navigationBar.frame.height ?? 0) } var navigationBar: UINavigationBar? { return navigationController?.navigationBar } func setBackBarButtonItem(title: String? = nil) { guard title != nil else { return } let temporaryBarButtonItem = UIBarButtonItem() temporaryBarButtonItem.title = title ?? "" navigationItem.backBarButtonItem = temporaryBarButtonItem } func pushWithHidesBottomBar(to controller: UIViewController, animated: Bool = true) { controller.hidesBottomBarWhenPushed = true navigationController?.pushViewController(controller, animated: animated) } @discardableResult func pop(animated: Bool = true) -> UIViewController? { return navigationController?.popViewController(animated: animated) } @discardableResult func pop(to aClass: AnyClass) -> UIViewController { var vc = self self.navigationController?.viewControllers.forEach({ (controller) in if controller.isKind(of: aClass) { self.navigationController?.popToViewController(controller, animated: true) vc = controller } }) return vc } } private var _easyBarButtonItemStruct: Void? public extension UIBarButtonItem { private struct EasyStruct { var handler: (() -> Void)? } private var easyStruct: EasyStruct? { get { return objc_getAssociatedObject(self, &_easyBarButtonItemStruct) as? EasyStruct } set { objc_setAssociatedObject(self, &_easyBarButtonItemStruct, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) } } @objc private func tapAction() { easyStruct?.handler?() } func tap(_ handler: @escaping () -> Void) { easyStruct = EasyStruct(handler: handler) target = self action = #selector(tapAction) } } public extension UINavigationItem { @discardableResult private func appendBarButtonItem(isRight: Bool, title: String?, image: UIImage?, attributes: [NSAttributedString.Key : Any]? = [.font: UIFont.size15], tapHandler: @escaping () -> Void) -> UINavigationItem { let barButtonItem = image == nil ? UIBarButtonItem(title: title, style: .done, target: nil, action: nil) : UIBarButtonItem(image: image, style: .done, target: nil, action: nil) barButtonItem.setTitleTextAttributes(attributes, for: .normal) barButtonItem.setTitleTextAttributes(attributes, for: .highlighted) barButtonItem.tap(tapHandler) if let items = (isRight ? rightBarButtonItems : leftBarButtonItems), items.count > 0 { if isRight { rightBarButtonItems?.append(barButtonItem) } else { leftBarButtonItems?.append(barButtonItem) } } else { if isRight { rightBarButtonItem = barButtonItem } else { leftBarButtonItem = barButtonItem } } return self } @discardableResult func appendRightBarButtonTitleItem(_ title: String, attributes: [NSAttributedString.Key : Any]? = [.font: UIFont.size15], tapHandler: @escaping () -> Void) -> UINavigationItem { return appendBarButtonItem(isRight: true, title: title, image: nil, attributes: attributes, tapHandler: tapHandler) } @discardableResult func appendRightBarButtonImageItem(_ image: UIImage, tapHandler: @escaping () -> Void) -> UINavigationItem { return appendBarButtonItem(isRight: true, title: nil, image: image, attributes: nil, tapHandler: tapHandler) } @discardableResult func appendLeftBarButtonTitleItem(_ title: String, attributes: [NSAttributedString.Key : Any]? = [.font: UIFont.size15], tapHandler: @escaping () -> Void) -> UINavigationItem { return appendBarButtonItem(isRight: false, title: title, image: nil, attributes: attributes, tapHandler: tapHandler) } @discardableResult func appendLeftBarButtonImageItem(_ image: UIImage, tapHandler: @escaping () -> Void) -> UINavigationItem { return appendBarButtonItem(isRight: false, title: nil, image: image, attributes: nil, tapHandler: tapHandler) } @discardableResult private func appendBarButtonSystemItem(_ barButtonSystemItem: UIBarButtonItem.SystemItem, isRight: Bool, tapHandler: @escaping () -> Void) -> UINavigationItem { let barButtonItem = UIBarButtonItem(barButtonSystemItem: barButtonSystemItem, target: nil, action: nil) barButtonItem.tap(tapHandler) if let items = (isRight ? rightBarButtonItems : leftBarButtonItems), items.count > 0 { if isRight { rightBarButtonItems?.append(barButtonItem) } else { leftBarButtonItems?.append(barButtonItem) } } else { if isRight { rightBarButtonItem = barButtonItem } else { leftBarButtonItem = barButtonItem } } return self } @discardableResult func appendLeftBarButtonSystemItem(_ barButtonSystemItem: UIBarButtonItem.SystemItem, tapHandler: @escaping () -> Void) -> UINavigationItem { return appendBarButtonSystemItem(barButtonSystemItem, isRight: false, tapHandler: tapHandler) } @discardableResult func appendRightBarButtonSystemItem(_ barButtonSystemItem: UIBarButtonItem.SystemItem, tapHandler: @escaping () -> Void) -> UINavigationItem { return appendBarButtonSystemItem(barButtonSystemItem, isRight: true, tapHandler: tapHandler) } } public extension UINavigationBar { /// 去掉导航背景的阴影 @discardableResult func setShadowNull() -> UINavigationBar { shadowImage = UIImage() setBackgroundImage(UIImage(), for: .default) isTranslucent = false return self } /// 导航背景透明 @discardableResult func setTranslucent() -> UINavigationBar { setShadowNull() isTranslucent = true return self } @discardableResult func setBackgroundColor(_ color: UIColor) -> UINavigationBar { setBackgroundImage(color.toImage, for: .default) return self } @discardableResult func setTintColor(_ color: UIColor) -> UINavigationBar { tintColor = color titleTextAttributes = [.foregroundColor: tintColor] return self } } public extension UIViewController { func setBackIndicator(_ image: UIImage?) { navigationBar?.backIndicatorImage = image navigationBar?.backIndicatorTransitionMaskImage = image navigationItem.backBarButtonItem = UIBarButtonItem(title: EasyGlobal.backBarButtonItemTitle, style: .plain, target: nil, action: nil) } }
mit
6e2489bb445323450b8fd70411e98e8b
34.56943
230
0.613964
4.803989
false
false
false
false
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Backtracking/40_Combination Sum II.swift
1
2099
// 40_Combination Sum II // https://leetcode.com/problems/combination-sum-ii/ // // Created by Honghao Zhang on 10/6/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. // //Each number in candidates may only be used once in the combination. // //Note: // //All numbers (including target) will be positive integers. //The solution set must not contain duplicate combinations. //Example 1: // //Input: candidates = [10,1,2,7,6,1,5], target = 8, //A solution set is: //[ // [1, 7], // [1, 2, 5], // [2, 6], // [1, 1, 6] //] //Example 2: // //Input: candidates = [2,5,2,1,2], target = 5, //A solution set is: //[ // [1,2,2], // [5] //] // // 给一些一定量的数字和一个target,求出所有能sum == target的所有组合 // 数字可能会有重复,每个数字只能用一次 import Foundation class Num40 { // MARK: - Backtrack // 上一个题是每个选过的element还可以再选 // 这个题是选过的就不能再选了 // Sorted, skip same value, only chose candidates after the index func combinationSum2(_ candidates: [Int], _ target: Int) -> [[Int]] { var results: [[Int]] = [] combinationSum2Helper([], candidates.sorted(), target, &results) return results } private func combinationSum2Helper(_ chosen: [Int], _ candidates: [Int], _ target: Int, _ results: inout [[Int]]) { if target < 0 { return } // Must check target == 0 before checking the candidates // This makes sure any good results are recorded if target == 0 { results.append(chosen) return } if candidates.count == 0 { return } for i in 0..<candidates.count { // skips duplicates if i > 0, candidates[i] == candidates[i - 1] { continue } let toChoose = candidates[i] combinationSum2Helper(chosen + [toChoose], Array(candidates[(i + 1)...]), target - toChoose, &results) } } }
mit
0c8da9ffa365385031756fef5586bee4
25.133333
172
0.633673
3.37931
false
false
false
false
gdelarosa/Safe-Reach
Safe Reach/JSON.swift
1
2604
// // JSON.swift // Safe Reach // // Created by Gina De La Rosa on 9/21/16. // Copyright © 2016 Gina De La Rosa. All rights reserved. // import Foundation enum JSONValue { case jsonObject([String:JSONValue]) case jsonArray([JSONValue]) case jsonString(String) case jsonNumber(NSNumber) case jsonBool(Bool) case jsonNull var object: [String:JSONValue]? { switch self { case .jsonObject(let value): return value default: return nil } } var array: [JSONValue]? { switch self { case .jsonArray(let value): return value default: return nil } } var string: String? { switch self { case .jsonString(let value): return value default: return nil } } var integer: Int? { switch self { case .jsonNumber(let value): return value.intValue default: return nil } } var double: Double? { switch self { case .jsonNumber(let value): return value.doubleValue default: return nil } } var bool: Bool? { switch self { case .jsonBool(let value): return value case .jsonNumber(let value): return value.boolValue default: return nil } } subscript(i: Int) -> JSONValue? { get { switch self { case .jsonArray(let value): return value[i] default: return nil } } } subscript(key: String) -> JSONValue? { get { switch self { case .jsonObject(let value): return value[key] default: return nil } } } static func fromObject(_ object: AnyObject) -> JSONValue? { switch object { case let value as NSString: return JSONValue.jsonString(value as String) case let value as NSNumber: return JSONValue.jsonNumber(value) case _ as NSNull: return JSONValue.jsonNull case let value as NSDictionary: var jsonObject: [String:JSONValue] = [:] for (k, v) in value { if let k = k as? NSString { if let v = JSONValue.fromObject(v as AnyObject) { jsonObject[k as String] = v } else { return nil } } } return JSONValue.jsonObject(jsonObject) case let value as NSArray: var jsonArray: [JSONValue] = [] for v in value { if let v = JSONValue.fromObject(v as AnyObject) { jsonArray.append(v) } else { return nil } } return JSONValue.jsonArray(jsonArray) default: return nil } } }
mit
3bebcc1c1e4f14384290e70945d09b30
18.425373
61
0.568575
4.191626
false
false
false
false
MattFoley/IQKeyboardManager
IQKeybordManagerSwift/IQTextView/IQTextView.swift
1
3451
// // IQTextView.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-14 Iftekhar Qurashi. // // 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 /*! @abstract UITextView with placeholder support */ class IQTextView : UITextView { required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } private var placeholderLabel: UILabel? /*! @abstract To set textView's placeholder text. Default is ni. */ var placeholder : String? { get { return placeholderLabel?.text } set { if placeholderLabel == nil { placeholderLabel = UILabel(frame: CGRectInset(self.bounds, 5, 0)) if let unwrappedPlaceholderLabel = placeholderLabel { unwrappedPlaceholderLabel.autoresizingMask = .FlexibleWidth | .FlexibleHeight unwrappedPlaceholderLabel.lineBreakMode = .ByWordWrapping unwrappedPlaceholderLabel.numberOfLines = 0 unwrappedPlaceholderLabel.font = font? unwrappedPlaceholderLabel.backgroundColor = UIColor.clearColor() unwrappedPlaceholderLabel.textColor = UIColor(white: 0.7, alpha: 1.0) unwrappedPlaceholderLabel.alpha = 0 addSubview(unwrappedPlaceholderLabel) } } placeholderLabel?.text = newValue refreshPlaceholder() } } private func refreshPlaceholder() { if countElements(text) != 0 { placeholderLabel?.alpha = 0 } else { placeholderLabel?.alpha = 1 } } override var text: String! { didSet { refreshPlaceholder() } } override var font : UIFont? { didSet { if let unwrappedFont = font { placeholderLabel?.font = unwrappedFont } else { placeholderLabel?.font = UIFont.systemFontOfSize(12) } } } override var delegate : UITextViewDelegate? { get { refreshPlaceholder() return super.delegate } set { } } }
mit
4763d0c2a4132a661e5bce175390ecd4
30.372727
97
0.598088
5.819562
false
false
false
false
daniel-hall/TestKit
Sources/TestKit/StepDefinition.swift
1
2694
// // StepDefinition.swift // TestKit // // Created by Hall, Daniel on 7/13/19. // // 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 XCTest public struct StepDefinition { internal let regex: NSRegularExpression internal let action: (StepDefinitionInput) throws -> () public init(expression: String, action: @escaping (StepDefinitionInput) throws -> ()) { self.action = action regex = try! NSRegularExpression(pattern: "^(?:(?i)given|when|then|and|but)[\\s]+" + expression.trimmingCharacters(in: .init(charactersIn: "^$")) + "$") } } public struct StepDefinitionInput { private let result: NSTextCheckingResult public let step: Gherkin.Feature.Step internal init(step: Gherkin.Feature.Step, result: NSTextCheckingResult) { self.step = step self.result = result } public subscript(_ captureGroupName: String) -> String? { get { let range = result.range(withName: captureGroupName) return range.location == NSNotFound ? nil : (step.description as NSString).substring(with: range) } } } public func given(_ expression: String, action: @escaping (StepDefinitionInput) throws -> ()) -> StepDefinition { StepDefinition(expression: expression, action: action) } public func when(_ expression: String, action: @escaping (StepDefinitionInput) throws -> ()) -> StepDefinition { StepDefinition(expression: expression, action: action) } public func then(_ expression: String, action: @escaping (StepDefinitionInput) throws -> ()) -> StepDefinition { StepDefinition(expression: expression, action: action) }
mit
50962c698eea06916084b8a3742ecdb3
39.818182
160
0.710097
4.373377
false
false
false
false
rapthi/GT6TuneAssistant
GT6TuneAssistant/GT6TuneAssistant/ViewControllers/SpecsTableViewController.swift
1
3352
// // SpecsTableViewController.swift // GT6TuneAssistant // // Created by Thierry Rapillard on 15/10/14. // Copyright (c) 2014 Quantesys. All rights reserved. // import UIKit class SpecsTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView!) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 0 } override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return 0 } /* override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView!, moveRowAtIndexPath fromIndexPath: NSIndexPath!, toIndexPath: NSIndexPath!) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView!, canMoveRowAtIndexPath indexPath: NSIndexPath!) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
mit
1d8e7b25af9def69fa77cdc42d3bbd34
33.556701
159
0.683174
5.540496
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/InputDataDataSelectorRowItem.swift
1
4461
// // InputDataDataSelectorRowItem.swift // Telegram // // Created by Mikhail Filimonov on 21/03/2018. // Copyright © 2018 Telegram. All rights reserved. // import Cocoa import TGUIKit class InputDataDataSelectorRowItem: GeneralRowItem, InputDataRowDataValue { private let updated:()->Void fileprivate var _value: InputDataValue { didSet { if _value != oldValue { updated() } } } fileprivate let placeholderLayout: TextViewLayout var value: InputDataValue { return _value } fileprivate let values: [ValuesSelectorValue<InputDataValue>] init(_ initialSize: NSSize, stableId: AnyHashable, value: InputDataValue, error: InputDataValueError?, placeholder: String, viewType: GeneralViewType, updated: @escaping()->Void, values: [ValuesSelectorValue<InputDataValue>]) { self._value = value self.updated = updated self.placeholderLayout = TextViewLayout(.initialize(string: placeholder, color: theme.colors.text, font: .normal(.text)), maximumNumberOfLines: 1) self.values = values super.init(initialSize, height: 42, stableId: stableId, viewType: viewType, error: error) _ = makeSize(initialSize.width, oldWidth: oldWidth) } override func makeSize(_ width: CGFloat, oldWidth: CGFloat) -> Bool { let success = super.makeSize(width, oldWidth: oldWidth) placeholderLayout.measure(width: 100) return success } override func viewClass() -> AnyClass { return InputDataDataSelectorRowView.self } } final class InputDataDataSelectorRowView : GeneralContainableRowView { private let placeholderTextView = TextView() private let dataTextView = TextView() private let overlay = OverlayControl() required init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(placeholderTextView) addSubview(dataTextView) addSubview(overlay) placeholderTextView.userInteractionEnabled = false placeholderTextView.isSelectable = false dataTextView.userInteractionEnabled = false dataTextView.isSelectable = false overlay.set(handler: { [weak self] _ in guard let item = self?.item as? InputDataDataSelectorRowItem else {return} showModal(with: ValuesSelectorModalController(values: item.values, selected: item.values.first(where: {$0.value == item.value}), title: item.placeholderLayout.attributedString.string, onComplete: { [weak item] newValue in item?._value = newValue.value item?.redraw() }), for: mainWindow) }, for: .Click) } override func shakeView() { dataTextView.shake() } override func layout() { super.layout() guard let item = item as? InputDataDataSelectorRowItem else {return} placeholderTextView.setFrameOrigin(item.viewType.innerInset.left, 14) dataTextView.textLayout?.measure(width: frame.width - item.viewType.innerInset.left - item.viewType.innerInset.right - 104) dataTextView.update(dataTextView.textLayout) dataTextView.setFrameOrigin(item.viewType.innerInset.left + 104, 14) overlay.frame = containerView.bounds } override func updateColors() { super.updateColors() placeholderTextView.backgroundColor = theme.colors.background } override func set(item: TableRowItem, animated: Bool) { super.set(item: item, animated: animated) guard let item = item as? InputDataDataSelectorRowItem else {return} placeholderTextView.update(item.placeholderLayout) var selected: ValuesSelectorValue<InputDataValue>? let index:Int? = item.values.index(where: { entry -> Bool in return entry.value == item.value }) if let index = index { selected = item.values[index] } let layout = TextViewLayout(.initialize(string: selected?.localized ?? item.placeholderLayout.attributedString.string, color: selected == nil ? theme.colors.grayText : theme.colors.text, font: .normal(.text)), maximumNumberOfLines: 1) dataTextView.update(layout) needsLayout = true } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-2.0
002cce5f43e09d2f17876ad44e66358b
36.478992
242
0.662332
4.906491
false
false
false
false
prolificinteractive/IQKeyboardManager
IQKeybordManagerSwift/IQToolbar/IQUIView+IQKeyboardToolbar.swift
1
21579
// // IQUIView+IQKeyboardToolbar.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-14 Iftekhar Qurashi. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit ///* @const kIQRightButtonToolbarTag Default tag for toolbar with Right button -1001. */ //let kIQRightButtonToolbarTag : NSInteger = -1001 ///* @const kIQRightLeftButtonToolbarTag Default tag for toolbar with Right/Left buttons -1003. */ //let kIQRightLeftButtonToolbarTag : NSInteger = -1003 ///* @const kIQCancelDoneButtonToolbarTag Default tag for toolbar with Cancel/Done buttons -1004. */ //let kIQCancelDoneButtonToolbarTag : NSInteger = -1004 /** @abstract UIView category methods to add IQToolbar on UIKeyboard. */ extension UIView { /** @abstract if shouldHideTitle is YES, then title will not be added to the toolbar. Default to NO. */ var shouldHideTitle: Bool? { get { let aValue: AnyObject? = objc_getAssociatedObject(self, "shouldHideTitle")? if aValue == nil { return false } else { return aValue as? Bool } } set(newValue) { objc_setAssociatedObject(self, "shouldHideTitle", newValue, UInt(OBJC_ASSOCIATION_ASSIGN)) } } /** @method addDoneOnKeyboardWithTarget:action: @abstract Helper functions to add Done button on keyboard. @param target: Target object for selector. Usually 'self'. @param action: Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param shouldShowPlaceholder: A boolean to indicate whether to show textField placeholder on IQToolbar'. @param titleText: text to show as title in IQToolbar'. */ func addRightButtonOnKeyboardWithText (text : String, target : AnyObject?, action : Selector, titleText: String?) { //If can't set InputAccessoryView. Then return if self is UITextField || self is UITextView { // Creating a toolBar for phoneNumber keyboard let toolbar = IQToolbar() var items : [UIBarButtonItem] = [] if let unwrappedTitleText = titleText { if countElements(unwrappedTitleText) != 0 && shouldHideTitle == false { /* 50 done button frame. 24 distance maintenance */ let buttonFrame = CGRectMake(0, 0, toolbar.frame.size.width-50.0-24, 44) let title = IQTitleBarButtonItem(frame: buttonFrame, title: unwrappedTitleText) items.append(title) } } // Create a fake button to maintain flexibleSpace between doneButton and nilButton. (Actually it moves done button to right side. let nilButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) items.append(nilButton) // Create a done button to show on keyboard to resign it. Adding a selector to resign it. let doneButton = IQBarButtonItem(title: text, style: UIBarButtonItemStyle.Done, target: target, action: action) items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar } } } func addRightButtonOnKeyboardWithText (text : String, target : AnyObject?, action : Selector, shouldShowPlaceholder: Bool) { var title : String? if shouldShowPlaceholder == true { if let textField = self as? UITextField { title = textField.placeholder } else if let textView = self as? IQTextView { title = textView.placeholder } } addRightButtonOnKeyboardWithText(text, target: target, action: action, titleText: title) } func addRightButtonOnKeyboardWithText (text : String, target : AnyObject?, action : Selector) { addRightButtonOnKeyboardWithText(text, target: target, action: action, titleText: nil) } func addDoneOnKeyboardWithTarget (target : AnyObject?, action : Selector, titleText: String?) { //If can't set InputAccessoryView. Then return if self is UITextField || self is UITextView { // Creating a toolBar for phoneNumber keyboard let toolbar = IQToolbar() var items : [UIBarButtonItem] = [] if let unwrappedTitleText = titleText { if countElements(unwrappedTitleText) != 0 && shouldHideTitle == false { /* 50 done button frame. 24 distance maintenance */ let buttonFrame = CGRectMake(0, 0, toolbar.frame.size.width-64.0-12.0, 44) let title = IQTitleBarButtonItem(frame: buttonFrame, title: unwrappedTitleText) items.append(title) } } // Create a fake button to maintain flexibleSpace between doneButton and nilButton. (Actually it moves done button to right side. let nilButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) items.append(nilButton) // Create a done button to show on keyboard to resign it. Adding a selector to resign it. let doneButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: target, action: action) items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar } } } func addDoneOnKeyboardWithTarget (target : AnyObject?, action : Selector, shouldShowPlaceholder: Bool) { var title : String? if shouldShowPlaceholder == true { if let textField = self as? UITextField { title = textField.placeholder } else if let textView = self as? IQTextView { title = textView.placeholder } } addDoneOnKeyboardWithTarget(target, action: action, titleText: title) } func addDoneOnKeyboardWithTarget(target : AnyObject?, action : Selector) { addDoneOnKeyboardWithTarget(target, action: action, titleText: nil) } /** @method addCancelDoneOnKeyboardWithTarget:cancelAction:doneAction: @abstract Helper function to add Cancel and Done button on keyboard. @param target: Target object for selector. Usually 'self'. @param cancelAction: Crevious button action name. Usually 'cancelAction:(IQBarButtonItem*)item'. @param doneAction: Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param shouldShowPlaceholder: A boolean to indicate whether to show textField placeholder on IQToolbar'. @param titleText: text to show as title in IQToolbar'. */ func addRightLeftOnKeyboardWithTarget( target : AnyObject?, leftButtonTitle : String, rightButtonTitle : String, rightButtonAction : Selector, leftButtonAction : Selector, titleText: String?) { //If can't set InputAccessoryView. Then return if self is UITextField || self is UITextView { // Creating a toolBar for phoneNumber keyboard let toolbar = IQToolbar() var items : [UIBarButtonItem] = [] // Create a cancel button to show on keyboard to resign it. Adding a selector to resign it. let cancelButton = IQBarButtonItem(title: leftButtonTitle, style: UIBarButtonItemStyle.Bordered, target: target, action: leftButtonAction) items.append(cancelButton) if let unwrappedTitleText = titleText { if countElements(unwrappedTitleText) != 0 && shouldHideTitle == false { /* 66 Cancel button maximum x. 50 done button frame. 8+8 distance maintenance */ let buttonFrame = CGRectMake(0, 0, toolbar.frame.size.width-66-50.0-16, 44) let title = IQTitleBarButtonItem(frame: buttonFrame, title: unwrappedTitleText) items.append(title) } } // Create a fake button to maintain flexibleSpace between doneButton and nilButton. (Actually it moves done button to right side. let nilButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) items.append(nilButton) // Create a done button to show on keyboard to resign it. Adding a selector to resign it. let doneButton = IQBarButtonItem(title: rightButtonTitle, style: UIBarButtonItemStyle.Bordered, target: target, action: rightButtonAction) items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar } } } func addRightLeftOnKeyboardWithTarget( target : AnyObject?, leftButtonTitle : String, rightButtonTitle : String, rightButtonAction : Selector, leftButtonAction : Selector, shouldShowPlaceholder: Bool) { var title : String? if shouldShowPlaceholder == true { if let textField = self as? UITextField { title = textField.placeholder } else if let textView = self as? IQTextView { title = textView.placeholder } } addRightLeftOnKeyboardWithTarget(target, leftButtonTitle: leftButtonTitle, rightButtonTitle: rightButtonTitle, rightButtonAction: rightButtonAction, leftButtonAction: leftButtonAction, titleText: title) } func addRightLeftOnKeyboardWithTarget( target : AnyObject?, leftButtonTitle : String, rightButtonTitle : String, rightButtonAction : Selector, leftButtonAction : Selector) { addRightLeftOnKeyboardWithTarget(target, leftButtonTitle: leftButtonTitle, rightButtonTitle: rightButtonTitle, rightButtonAction: rightButtonAction, leftButtonAction: leftButtonAction, titleText: nil) } func addCancelDoneOnKeyboardWithTarget (target : AnyObject?, cancelAction : Selector, doneAction : Selector, titleText: String?) { //If can't set InputAccessoryView. Then return if self is UITextField || self is UITextView { // Creating a toolBar for phoneNumber keyboard let toolbar = IQToolbar() var items : [UIBarButtonItem] = [] // Create a cancel button to show on keyboard to resign it. Adding a selector to resign it. let cancelButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: target, action: cancelAction) items.append(cancelButton) if let unwrappedTitleText = titleText { if countElements(unwrappedTitleText) != 0 && shouldHideTitle == false { /* 66 Cancel button maximum x. 50 done button frame. 8+8 distance maintenance */ let buttonFrame = CGRectMake(0, 0, toolbar.frame.size.width-66-50.0-16, 44) let title = IQTitleBarButtonItem(frame: buttonFrame, title: unwrappedTitleText) items.append(title) } } // Create a fake button to maintain flexibleSpace between doneButton and nilButton. (Actually it moves done button to right side. let nilButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) items.append(nilButton) // Create a done button to show on keyboard to resign it. Adding a selector to resign it. let doneButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: target, action: doneAction) items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar } } } func addCancelDoneOnKeyboardWithTarget (target : AnyObject?, cancelAction : Selector, doneAction : Selector, shouldShowPlaceholder: Bool) { var title : String? if shouldShowPlaceholder == true { if let textField = self as? UITextField { title = textField.placeholder } else if let textView = self as? IQTextView { title = textView.placeholder } } addCancelDoneOnKeyboardWithTarget(target, cancelAction: cancelAction, doneAction: doneAction, titleText: title) } func addCancelDoneOnKeyboardWithTarget (target : AnyObject?, cancelAction : Selector, doneAction : Selector) { addCancelDoneOnKeyboardWithTarget(target, cancelAction: cancelAction, doneAction: doneAction, titleText: nil) } /** @method addPreviousNextDoneOnKeyboardWithTarget:previousAction:nextAction:doneAction @abstract Helper function to add SegmentedNextPrevious and Done button on keyboard. @param target: Target object for selector. Usually 'self'. @param previousAction: Previous button action name. Usually 'previousAction:(IQSegmentedNextPrevious*)segmentedControl'. @param nextAction: Next button action name. Usually 'nextAction:(IQSegmentedNextPrevious*)segmentedControl'. @param doneAction: Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'. @param shouldShowPlaceholder: A boolean to indicate whether to show textField placeholder on IQToolbar'. @param titleText: text to show as title in IQToolbar'. */ func addPreviousNextDoneOnKeyboardWithTarget ( target : AnyObject?, previousAction : Selector, nextAction : Selector, doneAction : Selector, titleText: String?) { //If can't set InputAccessoryView. Then return if self is UITextField || self is UITextView { // Creating a toolBar for phoneNumber keyboard let toolbar = IQToolbar() var items : [UIBarButtonItem] = [] // Create a done button to show on keyboard to resign it. Adding a selector to resign it. let doneButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: target, action: doneAction) let prev = IQBarButtonItem(image: UIImage(named: "IQKeyboardManager.bundle/IQButtonBarArrowLeft"), style: UIBarButtonItemStyle.Plain, target: target, action: previousAction) let fixed = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil) fixed.width = 23 let next = IQBarButtonItem(image: UIImage(named: "IQKeyboardManager.bundle/IQButtonBarArrowRight"), style: UIBarButtonItemStyle.Plain, target: target, action: nextAction) items.append(prev) items.append(fixed) items.append(next) if let unwrappedTitleText = titleText { if countElements(unwrappedTitleText) != 0 && shouldHideTitle == false { /* 72.5 next/previous maximum x. 50 done button frame. 8+8 distance maintenance */ let buttonFrame = CGRectMake(0, 0, toolbar.frame.size.width-72.5-50.0-16, 44) let title = IQTitleBarButtonItem(frame: buttonFrame, title: unwrappedTitleText) items.append(title) } } // Create a fake button to maintain flexibleSpace between doneButton and nilButton. (Actually it moves done button to right side. let nilButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) items.append(nilButton) items.append(doneButton) // Adding button to toolBar. toolbar.items = items // Setting toolbar to keyboard. if let textField = self as? UITextField { textField.inputAccessoryView = toolbar } else if let textView = self as? UITextView { textView.inputAccessoryView = toolbar } } } public func addPreviousNextDoneOnKeyboardWithTarget ( target : AnyObject?, previousAction : Selector, nextAction : Selector, doneAction : Selector, shouldShowPlaceholder: Bool) { var title : String? if shouldShowPlaceholder == true { if let textField = self as? UITextField { title = textField.placeholder } else if let textView = self as? IQTextView { title = textView.placeholder } } addPreviousNextDoneOnKeyboardWithTarget(target, previousAction: previousAction, nextAction: nextAction, doneAction: doneAction, titleText: title) } func addPreviousNextDoneOnKeyboardWithTarget ( target : AnyObject?, previousAction : Selector, nextAction : Selector, doneAction : Selector) { addPreviousNextDoneOnKeyboardWithTarget(target, previousAction: previousAction, nextAction: nextAction, doneAction: doneAction, titleText: nil) } /** @method setEnablePrevious:next: @abstract Helper function to enable and disable previous next buttons. @param isPreviousEnabled: BOOL to enable/disable previous button on keyboard. @param isNextEnabled: BOOL to enable/disable next button on keyboard.. */ func setEnablePrevious ( isPreviousEnabled : Bool, isNextEnabled : Bool) { // Getting inputAccessoryView. if let inputAccessoryView = self.inputAccessoryView as? IQToolbar { // If it is IQToolbar and it's items are greater than zero. if inputAccessoryView.items?.count > 3 { if let items = inputAccessoryView.items { if let prevButton = items[0] as? IQBarButtonItem { if let nextButton = items[2] as? IQBarButtonItem { if prevButton.enabled != isPreviousEnabled { prevButton.enabled = isPreviousEnabled } if nextButton.enabled != isNextEnabled { nextButton.enabled = isNextEnabled } } } } } } } }
mit
babc0552bd796550aec740a41464e924
44.815287
210
0.611659
5.871837
false
false
false
false
McDevon/CardBase
CardBase/Classes/Mana.swift
1
1525
// // Mana.swift // CardBase // // Created by Jussi Enroos on 5.1.2015. // Copyright (c) 2015 Jussi Enroos. All rights reserved. // import Foundation public enum ManaColor { case Colorless(Int), White, Blue, Black, Red, Green func cost() -> Int { switch self { case .Colorless(let value): return max(0, value) default: return 1 } } func symbol() -> String { switch self { case .Colorless(let value): return String(value) case .White: return "W" case .Blue: return "U" case .Black: return "B" case .Red: return "R" case .Green: return "G" } } } public class ManaSymbol { var value:ManaColor = .Colorless(0) var alternateValue:ManaColor? func convertedCost() -> Int { if let alter = alternateValue { return max(value.cost(), alter.cost()) } else { return value.cost() } } func abbreviation() -> String { return "{" + value.symbol() + (alternateValue != nil ? "/" + alternateValue!.symbol() + "}" : "}") } public init(value val:ManaColor, alternate alt:ManaColor) { value = val var altVal:ManaColor? = alt alternateValue = altVal } public init (value val:ManaColor) {value = val} public convenience init () {self.init(value: .Colorless(0))} }
mit
17328eff46b717f88a8ab9a045136105
22.461538
106
0.516721
4.002625
false
false
false
false
PlanTeam/BSON
Sources/BSON/Document/Document+Mutations.swift
1
9023
import Foundation extension Document { /// Calls `changeCapacity` on `storage` and updates the document header private mutating func changeCapacity(_ requiredCapacity: Int) { storage.reserveCapacity(requiredCapacity) self.usedCapacity = Int32(requiredCapacity) } /// Moves the bytes with the given length at the position `from` to the position at `to` mutating func moveBytes(from: Int, to: Int, length: Int) { let initialReaderIndex = storage.readerIndex let initialWriterIndex = storage.writerIndex storage.moveReaderIndex(to: 0) storage.moveWriterIndex(to: Int(self.usedCapacity)) defer { storage.moveReaderIndex(to: initialReaderIndex) storage.moveWriterIndex(to: initialWriterIndex) } _ = storage.withUnsafeMutableReadableBytes { pointer in memmove( pointer.baseAddress! + to, // dst pointer.baseAddress! + from, // src length // len ) } } func skipKey(at index: inout Int) -> Bool { if let length = storage.firstRelativeIndexOf(startingAt: index) { index += length + 1 // including null terminator return true } return false } func skipMatchingKey(_ key: String, at index: inout Int) -> Bool { let base = index if !skipKey(at: &index) { return false } let length = index - base #if compiler(>=5) let valid = key.utf8.withContiguousStorageIfAvailable { key -> Bool in if key.count != length { return false } return storage.withUnsafeReadableBytes { storage in return memcmp(key.baseAddress!, storage.baseAddress! + index, length) == 0 } } if let valid = valid { return valid } #endif if key.utf8.count != length { return false } else { return key == storage.getString(at: base, length: length) } } func skipValue(ofType type: TypeIdentifier, at index: inout Int) -> Bool { if let length = valueLength(forType: type, at: index) { index += length return true } return false } func skipKeyValuePair(at index: inout Int) -> Bool { guard let typeId = storage.getInteger(at: index, as: UInt8.self), let type = TypeIdentifier(rawValue: typeId) else { return false } index += 1 guard skipKey(at: &index) else { return false } return skipValue(ofType: type, at: &index) } func getKey(at index: Int) -> String? { guard let length = storage.firstRelativeIndexOf(startingAt: index) else { return nil } return storage.getString(at: index, length: length) } func matchesKey(_ key: String, at index: Int) -> Bool { guard let length = storage.firstRelativeIndexOf(startingAt: index) else { return false } #if compiler(>=5) let valid = key.utf8.withContiguousStorageIfAvailable { key -> Bool in if key.count != length { return false } return storage.withUnsafeReadableBytes { storage in return memcmp(key.baseAddress!, storage.baseAddress! + index, length) == 0 } } if let valid = valid { return valid } #endif if key.utf8.count != length { return false } else { return key == storage.getString(at: index, length: length) } } func value(forType type: TypeIdentifier, at offset: Int) -> Primitive? { switch type { case .double: return storage.getDouble(at: offset) case .string: guard let length = self.storage.getInteger(at: offset, endianness: .little, as: Int32.self) else { return nil } // Omit the null terminator as we don't use/need that in Swift return self.storage.getString(at: offset &+ 4, length: numericCast(length) - 1) case .binary: guard let length = self.storage.getInteger(at: offset, endianness: .little, as: Int32.self) else { return nil } guard let subType = self.storage.getByte(at: offset &+ 4), let slice = self.storage.getSlice(at: offset &+ 5, length: numericCast(length)) else { return nil } return Binary(subType: Binary.SubType(subType), buffer: slice) case .document, .array: guard let length = self.storage.getInteger(at: offset, endianness: .little, as: Int32.self), let slice = self.storage.getSlice(at: offset, length: numericCast(length)) else { return nil } return Document( buffer: slice, isArray: type == .array ) case .objectId: return storage.getObjectId(at: offset) case .boolean: return storage.getByte(at: offset) == 0x01 case .datetime: guard let timestamp = self.storage.getInteger(at: offset, endianness: .little, as: Int64.self) else { return nil } return Date(timeIntervalSince1970: Double(timestamp) / 1000) case .timestamp: guard let increment = self.storage.getInteger(at: offset, endianness: .little, as: Int32.self), let timestamp = self.storage.getInteger(at: offset &+ 4, endianness: .little, as: Int32.self) else { return nil } return Timestamp(increment: increment, timestamp: timestamp) case .int64: return self.storage.getInteger(at: offset, endianness: .little, as: Int.self) case .null: return Null() case .minKey: return MinKey() case .maxKey: // no data // Still need to check the key's size return MaxKey() case .regex: guard let patternEnd = storage.firstRelativeIndexOf(startingAt: offset), let pattern = storage.getString(at: offset, length: patternEnd - 1) else { return nil } let offset = offset + patternEnd guard let optionsEnd = storage.firstRelativeIndexOf(startingAt: offset), let options = storage.getString(at: offset, length: optionsEnd - 1) else { return nil } return RegularExpression(pattern: pattern, options: options) case .javascript: guard let length = self.storage.getInteger(at: offset, endianness: .little, as: Int32.self), let code = self.storage.getString(at: offset &+ 4, length: numericCast(length) - 1) else { return nil } return JavaScriptCode(code) case .javascriptWithScope: guard let length = self.storage.getInteger(at: offset, endianness: .little, as: Int32.self) else { return nil } guard let codeLength = self.storage.getInteger(at: offset &+ 4, endianness: .little, as: Int32.self), let code = self.storage.getString(at: offset &+ 8, length: numericCast(length) - 1) else { return nil } guard let documentLength = self.storage.getInteger(at: offset &+ 8 &+ numericCast(codeLength), endianness: .little, as: Int32.self), let slice = self.storage.getSlice(at: offset, length: numericCast(documentLength)) else { return nil } let scope = Document( buffer: slice, isArray: false ) return JavaScriptCodeWithScope(code, scope: scope) case .int32: return self.storage.getInteger(at: offset, endianness: .little, as: Int32.self) case .decimal128: guard let slice = storage.getBytes(at: offset, length: 16) else { return nil } return Decimal128(slice) } } /// Removes `length` number of bytes at `index`, and moves the bytes after over it /// Afterwards, it updates the document header mutating func removeBytes(at index: Int, length: Int) { moveBytes(from: index + length, to: index, length: numericCast(self.usedCapacity) - index - length) storage.moveWriterIndex(to: storage.readableBytes - length) self.usedCapacity -= Int32(length) } }
mit
cfdf0761bb11f95378790a11023e3abe
33.837838
159
0.549928
4.724084
false
false
false
false
tappollo/OSCKit
Source/DeviceInfo.swift
1
2361
// // DeviceInfo.swift // ThreeSixtyCamera // // Created by Zhigang Fang on 4/18/17. // Copyright © 2017 Tappollo Inc. All rights reserved. // import Foundation import SwiftyyJSON import PromiseKit import AwaitKit public struct DeviceInfo { public let model: String public let serial: String public let battery: Double public let currentAPI: Int public let supportedAPI: [Int] } extension OSCKit { public var deviceInfo: Promise<DeviceInfo> { return async { let info = try await(self.info) let state = try await(self.state) let dI = DeviceInfo( model: try info["model"].string !! SDKError.unableToParse(info), serial: try info["serialNumber"].string !! SDKError.unableToParse(info), battery: try state["state"]["batteryLevel"].double !! SDKError.unableToParse(state), currentAPI: state["state"]["_apiVersion"].int ?? 1, supportedAPI: info["apiLevel"].array?.compactMap({$0.int}) ?? [1] ) self.currentDevice = dI return dI } } public var cachedDeviceInfo: Promise<DeviceInfo> { if let cached = self.currentDevice { return Promise.value(cached) } return self.deviceInfo } public var info: Promise<JSON> { return self.requestJSON(endPoint: .info) } public var state: Promise<JSON> { return self.requestJSON(endPoint: .state) } public var latestFile: Promise<String?> { return self.state.map({ let state = $0["state"] return state["_latestFileUri"].string ?? state["_latestFileUrl"].string }) } public func watchTillLastFileChages() -> (Promise<String>, () -> Void) { var stop = false func recursion(currentURL: String?) -> Promise<String> { return async { if stop { throw SDKError.fetchTimeout } try await(after(seconds: 2).asVoid()) let newFile = try await(self.latestFile) if let newFile = newFile, newFile != currentURL { return newFile } return try await(recursion(currentURL: newFile)) } } return (self.latestFile.then({recursion(currentURL: $0)}), {stop = true}) } }
mit
87a21d7f29b6f31e46f0641331500618
30.891892
100
0.586864
4.444444
false
true
false
false
Geor9eLau/WorkHelper
Carthage/Checkouts/SwiftCharts/SwiftCharts/Layers/ChartCandleStickLayer.swift
1
2938
// // ChartCandleStickLayer.swift // SwiftCharts // // Created by ischuetz on 28/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit open class ChartCandleStickLayer<T: ChartPointCandleStick>: ChartPointsLayer<T> { fileprivate var screenItems: [CandleStickScreenItem] = [] fileprivate let itemWidth: CGFloat fileprivate let strokeWidth: CGFloat public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], itemWidth: CGFloat = 10, strokeWidth: CGFloat = 1) { self.itemWidth = itemWidth self.strokeWidth = strokeWidth super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints) self.screenItems = self.chartPointsModels.map {model in let chartPoint = model.chartPoint let x = model.screenLoc.x let highScreenY = self.modelLocToScreenLoc(x: Double(x), y: Double(chartPoint.high)).y let lowScreenY = self.modelLocToScreenLoc(x: Double(x), y: Double(chartPoint.low)).y let openScreenY = self.modelLocToScreenLoc(x: Double(x), y: Double(chartPoint.open)).y let closeScreenY = self.modelLocToScreenLoc(x: Double(x), y: Double(chartPoint.close)).y let (rectTop, rectBottom, fillColor) = closeScreenY < openScreenY ? (closeScreenY, openScreenY, UIColor.white) : (openScreenY, closeScreenY, UIColor.black) return CandleStickScreenItem(x: x, lineTop: highScreenY, lineBottom: lowScreenY, rectTop: rectTop, rectBottom: rectBottom, width: self.itemWidth, fillColor: fillColor) } } override open func chartViewDrawing(context: CGContext, chart: Chart) { for screenItem in self.screenItems { context.setLineWidth(self.strokeWidth) context.setStrokeColor(UIColor.black.cgColor) context.move(to: CGPoint(x: screenItem.x, y: screenItem.lineTop)) context.addLine(to: CGPoint(x: screenItem.x, y: screenItem.lineBottom)) context.strokePath() context.setFillColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.0) context.setFillColor(screenItem.fillColor.cgColor) context.fill(screenItem.rect) context.stroke(screenItem.rect) } } } private struct CandleStickScreenItem { let x: CGFloat let lineTop: CGFloat let lineBottom: CGFloat let fillColor: UIColor let rect: CGRect init(x: CGFloat, lineTop: CGFloat, lineBottom: CGFloat, rectTop: CGFloat, rectBottom: CGFloat, width: CGFloat, fillColor: UIColor) { self.x = x self.lineTop = lineTop self.lineBottom = lineBottom self.rect = CGRect(x: x - (width / 2), y: rectTop, width: width, height: rectBottom - rectTop) self.fillColor = fillColor } }
mit
008be5f4e4fc6d155b12d972a7b6920a
38.702703
179
0.653165
4.251809
false
false
false
false
ChinaPicture/ZXYRefresh
RefreshDemo/Refresh/UIScrollViewRefresh.swift
1
3489
// // UIScrollViewRefresh.swift // RefreshDemo // // Created by developer on 15/03/2017. // Copyright © 2017 developer. All rights reserved. // import UIKit extension UIScrollView { var headerView: RefreshBaseHeaderView? { set { if newValue == nil { self.removeHeaderView() ; return} newValue?.frame = CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: newValue!.activeOff) var container: RefreshHeaderContainerView? = objc_getAssociatedObject(self, &ZXYRefreshHeaderContainerKey) as? RefreshHeaderContainerView if container == nil { container = RefreshHeaderContainerView.init(frame: CGRect.init(x: 0, y: -(newValue?.activeOff ?? 0), width: self.frame.size.width, height: newValue?.activeOff ?? 0)) container?.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleWidth] self.addSubview(container!) } else { container?.frame = CGRect.init(x: 0, y: -(newValue?.activeOff ?? 0), width: self.frame.size.width, height: newValue?.activeOff ?? 0) } container?.setHeaderView(header: newValue) objc_setAssociatedObject(self, &ZXYRefreshHeaderContainerKey, container, .OBJC_ASSOCIATION_ASSIGN) } get { let c = objc_getAssociatedObject(self, &ZXYRefreshHeaderContainerKey) as? RefreshHeaderContainerView return c?.getHeader() } } var footerView: RefreshBaseFooterView? { set { if newValue == nil { self.removeFooterView() ; return } var container: RefreshFooterContainerView? = objc_getAssociatedObject(self, &ZXYRefreshFooterContainerKey) as? RefreshFooterContainerView if container == nil { container = RefreshFooterContainerView.init(frame: CGRect.init(x: 0, y: max(self.contentSize.height, self.frame.size.height) , width: self.frame.size.width, height: newValue?.activeOff ?? 0)) container?.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleWidth] self.addSubview(container!) } else { container?.frame = CGRect.init(x: 0, y: max(self.contentSize.height, self.frame.size.height) , width: self.frame.size.width, height: newValue?.activeOff ?? 0) } container?.setFooterView(footer: newValue) objc_setAssociatedObject(self, &ZXYRefreshFooterContainerKey, container, .OBJC_ASSOCIATION_ASSIGN) } get { let c = objc_getAssociatedObject(self, &ZXYRefreshFooterContainerKey) as? RefreshFooterContainerView return c?.getFooter() } } private func removeHeaderView() { var container: RefreshHeaderContainerView? = objc_getAssociatedObject(self, &ZXYRefreshHeaderContainerKey) as? RefreshHeaderContainerView if container != nil { container?.removeFromSuperview() ; container = nil ; } objc_setAssociatedObject(self, &ZXYRefreshHeaderContainerKey, nil, .OBJC_ASSOCIATION_ASSIGN) } private func removeFooterView() { var container: RefreshFooterContainerView? = objc_getAssociatedObject(self, &ZXYRefreshFooterContainerKey) as? RefreshFooterContainerView if container != nil { container?.removeFromSuperview() ; container = nil ; } objc_setAssociatedObject(self, &ZXYRefreshFooterContainerKey, nil, .OBJC_ASSOCIATION_ASSIGN) } }
apache-2.0
400833620d8bd8488eaa11ee3b430179
52.661538
207
0.667144
4.752044
false
false
false
false
rzrasel/iOS-Swift-2016-01
SwiftCameraGalleryOne/SwiftCameraGallery/AppDelegate.swift
2
6109
// // AppDelegate.swift // SwiftCameraGallery // // Created by NextDot on 2/3/16. // Copyright © 2016 RzRasel. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "rz.rasel.SwiftCameraGallery" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("SwiftCameraGallery", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
apache-2.0
41fcc9539a0e397330f5e5df4b9d4a26
54.027027
291
0.72053
5.890068
false
false
false
false
rzrasel/iOS-Swift-2016-01
SwiftTableViewTwo/SwiftTableViewTwo/AppDelegate.swift
2
6106
// // AppDelegate.swift // SwiftTableViewTwo // // Created by NextDot on 2/4/16. // Copyright © 2016 RzRasel. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "rz.rasel.SwiftTableViewTwo" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("SwiftTableViewTwo", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
apache-2.0
25dfa194141d1087022d502b7f35d458
54
291
0.720393
5.887175
false
false
false
false
benlangmuir/swift
test/Compatibility/protocol_composition.swift
9
1759
// RUN: %empty-directory(%t) // RUN: %{python} %utils/split_file.py -o %t %s // RUN: %target-swift-frontend -typecheck -primary-file %t/swift4.swift %t/common.swift -verify -swift-version 4 // BEGIN common.swift protocol P1 { static func p1() -> Int } protocol P2 { static var p2: Int { get } } // BEGIN swift3.swift // Warning for mistakenly accepted protocol composition production. func foo(x: P1 & Any & P2.Type?) { // expected-warning @-1 {{protocol-constrained type with postfix '.Type' is ambiguous and will be rejected in future version of Swift}} {{13-13=(}} {{26-26=)}} let _: (P1 & P2).Type? = x let _: (P1 & P2).Type = x! let _: Int = x!.p1() let _: Int? = x?.p2 } // Type expression func bar() -> ((P1 & P2)?).Type { let x = (P1 & P2?).self // expected-warning @-1 {{protocol-constrained type with postfix '?' is ambiguous and will be rejected in future version of Swift}} {{12-12=(}} {{19-19=)}} return x } // Non-ident type at non-last position are rejected anyway. typealias A1 = P1.Type & P2 // expected-error {{non-protocol, non-class type 'P1.Type' cannot be used within a protocol-constrained type}} // BEGIN swift4.swift func foo(x: P1 & Any & P2.Type?) { // expected-error {{non-protocol, non-class type '(any P2.Type)?' cannot be used within a protocol-constrained type}} let _: (P1 & P2).Type? = x let _: (P1 & P2).Type = x! let _: Int = x!.p1() let _: Int? = x?.p2 } func bar() -> ((P1 & P2)?).Type { let x = (P1 & P2?).self // expected-error {{non-protocol, non-class type '(any P2)?' cannot be used within a protocol-constrained type}} return x } typealias A1 = P1.Type & P2 // expected-error {{non-protocol, non-class type 'any P1.Type' cannot be used within a protocol-constrained type}}
apache-2.0
1a5f73832be1b85275680f6e7b8d2050
34.897959
161
0.64639
3.05913
false
false
false
false
alexth/VIPER-test
ViperTest/ViperTest/Flows/Master/DataSource/FetchedTableViewDataSource.swift
1
4760
// // FetchedTableViewDataSource.swift // ViperTest // // Created by Alex Golub on 10/30/16. // Copyright © 2016 Alex Golub. All rights reserved. // import UIKit import CoreData class FetchedTableViewDataSource: NSObject, UITableViewDataSource, NSFetchedResultsControllerDelegate { weak var tableView: UITableView! // MARK: TableView DataSource func numberOfSections(in tableView: UITableView) -> Int { return self.fetchedResultsController.sections?.count ?? 0 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionInfo = self.fetchedResultsController.sections![section] return sectionInfo.numberOfObjects } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let event = self.fetchedResultsController.object(at: indexPath) self.configureCell(cell, withEvent: event) return cell } // MARK: Actions func insertNewObject() { let context = self.fetchedResultsController.managedObjectContext let newEvent = Event(context: context) newEvent.timestamp = NSDate() do { try context.save() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } func deleteObjectAt(indexPath: IndexPath) { let context = self.fetchedResultsController.managedObjectContext context.delete(self.fetchedResultsController.object(at: indexPath)) do { try context.save() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } func eventAt(indexPath: IndexPath) -> Event { return self.fetchedResultsController.object(at: indexPath) } // MARK: Fetched Results Controller fileprivate var fetchedResultsController: NSFetchedResultsController<Event> { if _fetchedResultsController != nil { return _fetchedResultsController! } let fetchRequest: NSFetchRequest<Event> = Event.fetchRequest() fetchRequest.fetchBatchSize = 20 let sortDescriptor = NSSortDescriptor(key: "timestamp", ascending: false) fetchRequest.sortDescriptors = [sortDescriptor] let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: DataManager.sharedInstance.managedObjectContext, sectionNameKeyPath: nil, cacheName: "Master") aFetchedResultsController.delegate = self _fetchedResultsController = aFetchedResultsController do { try _fetchedResultsController!.performFetch() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } return _fetchedResultsController! } fileprivate var _fetchedResultsController: NSFetchedResultsController<Event>? = nil // MARK: NSFetchResultsControllerDelegate func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { self.tableView.beginUpdates() } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { switch type { case .insert: self.tableView.insertSections(IndexSet(integer: sectionIndex), with: .fade) case .delete: self.tableView.deleteSections(IndexSet(integer: sectionIndex), with: .fade) default: return } } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: tableView.insertRows(at: [newIndexPath!], with: .fade) case .delete: tableView.deleteRows(at: [indexPath!], with: .fade) case .update: self.configureCell(tableView.cellForRow(at: indexPath!)!, withEvent: anObject as! Event) case .move: tableView.moveRow(at: indexPath!, to: newIndexPath!) } } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { self.tableView.endUpdates() } // MARK: Utils func configureCell(_ cell: UITableViewCell, withEvent event: Event) { cell.textLabel!.text = event.timestamp!.description } }
mit
eb35adfafbb63fb0efc8dfa7b06532ae
37.379032
211
0.684387
5.775485
false
false
false
false
scottkawai/sendgrid-swift
Sources/SendGrid/API/V3/Mail/Send/Email.Personalization.swift
1
10244
import Foundation /// The `Personalization` struct is used by the `Email` class to add /// personalization settings to an email. The only required property is the `to` /// property, and each email must have at least one personalization. open class Personalization: Encodable, EmailHeaderRepresentable, Scheduling { // MARK: - Properties /// An array of recipients to send the email to. public var to: [Address] /// An array of recipients to add as a CC on the email. open var cc: [Address]? /// An array of recipients to add as a BCC on the email. open var bcc: [Address]? /// A personalized subject for the email. open var subject: String? /// An optional set of headers to add to the email in this personalization. /// Each key in the dictionary should represent the name of the header, and /// the values of the dictionary should be equal to the values of the /// headers. open var headers: [String: String]? /// An optional set of substitutions to replace in this personalization. The /// keys in the dictionary should represent the substitution tags that /// should be replaced, and the values should be the replacement values. open var substitutions: [String: String]? /// A set of custom arguments to add to the email. The keys of the /// dictionary should be the names of the custom arguments, while the values /// should represent the value of each custom argument. open var customArguments: [String: String]? /// An optional time to send the email at. open var sendAt: Date? // MARK: - Initialization /// Initializes the email with all the available properties. /// /// - Parameters: /// - to: An array of addresses to send the email to. /// - cc: An array of addresses to add as CC. /// - bcc: An array of addresses to add as BCC. /// - subject: A subject to use in the personalization. /// - headers: A set of additional headers to add for this /// personalization. The keys and values in the /// dictionary should represent the name of the /// headers and their values, respectively. /// - substitutions: A set of substitutions to make in this /// personalization. The keys and values in the /// dictionary should represent the substitution /// tags and their replacement values, respectively. /// - customArguments: A set of custom arguments to add to the /// personalization. The keys and values in the /// dictionary should represent the argument names /// and values, respectively. /// - sendAt: A time to send the email at. public init(to: [Address], cc: [Address]? = nil, bcc: [Address]? = nil, subject: String? = nil, headers: [String: String]? = nil, substitutions: [String: String]? = nil, customArguments: [String: String]? = nil, sendAt: Date? = nil) { self.to = to self.cc = cc self.bcc = bcc self.subject = subject self.headers = headers self.substitutions = substitutions self.customArguments = customArguments self.sendAt = sendAt } /// Initializes the personalization with a set of email addresses. /// /// - Parameter recipients: A list of email addresses to use as the "to" /// addresses. public convenience init(recipients: String...) { let list: [Address] = recipients.map { Address(email: $0) } self.init(to: list) } // MARK: - Encodable Conformance /// :nodoc: open func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: Personalization._CodingKeys.self) try container.encode(self.to, forKey: .to) try container.encodeIfPresent(self.cc, forKey: .cc) try container.encodeIfPresent(self.bcc, forKey: .bcc) try container.encodeIfPresent(self.subject, forKey: .subject) try container.encodeIfPresent(self.headers, forKey: .headers) try container.encodeIfPresent(self.substitutions, forKey: .substitutions) try container.encodeIfPresent(self.customArguments, forKey: .customArguments) try container.encodeIfPresent(self.sendAt, forKey: .sendAt) } /// :nodoc: private enum _CodingKeys: String, CodingKey { case to case cc case bcc case subject case headers case substitutions case customArguments = "custom_args" case sendAt = "send_at" } } extension Personalization: Validatable { /// Validates that the personalization has recipients and that they are /// proper email addresses as well as making sure the sendAt date is valid. open func validate() throws { guard self.to.count > 0 else { throw Exception.Mail.missingRecipients } try self.validateHeaders() try self.validateSendAt() try self.to.forEach { try $0.validate() } try self.cc?.forEach { try $0.validate() } try self.bcc?.forEach { try $0.validate() } if let s = self.subject { guard s.count > 0 else { throw Exception.Mail.missingSubject } } if let sub = self.substitutions { guard sub.count <= Constants.SubstitutionLimit else { throw Exception.Mail.tooManySubstitutions } } } } /// The `TemplatedPersonalization` class is a subclass of `Personalization`, and /// is used if you are using the Dynamic Templates feature. /// /// There is a generic /// `TemplateData` type that you can specify which represents the substitution /// data. An example of using this class might look something like this: /// /// ``` /// // First let's define our dynamic data types: /// struct CheckoutData: Encodable { /// let total: String /// let items: [String] /// let receipt: Bool /// } /// /// // Next let's create the personalization. /// let thisData = CheckoutData(total: "$239.85", /// items: ["Shoes", "Shirt"], /// receipt: true) /// let personalization = TemplatedPersonalization(dynamicTemplateData: thisData, /// recipients: "[email protected]") /// ``` open class TemplatedPersonalization<TemplateData: Encodable>: Personalization { // MARK: - Properties /// The handlebar substitutions that will be applied to the dynamic template /// specified in the `templateID` on the `Email`. open var dynamicTemplateData: TemplateData // MARK: - Initialization /// Initializes the email with all the available properties. /// /// - Parameters: /// - dynamicTemplateData: The handlebar substitution data that will be /// applied to the dynamic template. /// - to: An array of addresses to send the email to. /// - cc: An array of addresses to add as CC. /// - bcc: An array of addresses to add as BCC. /// - subject: A subject to use in the personalization. /// - headers: A set of additional headers to add for this /// personalization. The keys and values in the /// dictionary should represent the name of the /// headers and their values, respectively. /// - substitutions: A set of substitutions to make in this /// personalization. The keys and values in the /// dictionary should represent the substitution /// tags and their replacement values, /// respectively. /// - customArguments: A set of custom arguments to add to the /// personalization. The keys and values in the /// dictionary should represent the argument /// names and values, respectively. /// - sendAt: A time to send the email at. public init(dynamicTemplateData: TemplateData, to: [Address], cc: [Address]? = nil, bcc: [Address]? = nil, subject: String? = nil, headers: [String: String]? = nil, substitutions: [String: String]? = nil, customArguments: [String: String]? = nil, sendAt: Date? = nil) { self.dynamicTemplateData = dynamicTemplateData super.init(to: to, cc: cc, bcc: bcc, subject: subject, headers: headers, substitutions: substitutions, customArguments: customArguments, sendAt: sendAt) } /// Initializes the personalization with a set of email addresses. /// /// - Parameters /// - dynamicTemplateData: The handlebar substitution data that will be /// applied to the dynamic template. /// - recipients: A list of email addresses to use as the "to" /// addresses. public convenience init(dynamicTemplateData: TemplateData, recipients: String...) { let list: [Address] = recipients.map { Address(email: $0) } self.init(dynamicTemplateData: dynamicTemplateData, to: list) } // MARK: - Encodable Conformance /// :nodoc: open override func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: TemplatedPersonalization._CodingKeys.self) try container.encode(self.dynamicTemplateData, forKey: .dynamicTemplateData) try super.encode(to: encoder) } /// :nodoc: private enum _CodingKeys: String, CodingKey { case dynamicTemplateData = "dynamic_template_data" } }
mit
bd9da789ee58ddd2506af53b93cb24a1
45.144144
273
0.59059
4.972816
false
false
false
false
zmeyc/xgaf
Sources/xgaf/SimpleAreaFormatGenerator.swift
1
1749
// XGAF file format parser for Swift. // (c) 2016 Andrey Fidrya. MIT license. See LICENSE for more information. import Foundation class SimpleAreaFormatGenerator { let areas: Areas init(areas: Areas) { self.areas = areas } func save(toFileNamed filename: String) throws { let out = generateOutput() do { try out.write(toFile: filename, atomically: true, encoding: .utf8) } catch { throw SaveError(kind: .ioError(error: error)) } } private func generateOutput() -> String { var out = "" out.reserveCapacity(256 * 1024) generate(entities: areas.items, primaryField: "предмет", appendTo: &out) generate(entities: areas.mobiles, primaryField: "монстр", appendTo: &out) generate(entities: areas.rooms, primaryField: "комната", appendTo: &out) return out } private func generate(entities: [Int64: Entity], primaryField: String, appendTo out: inout String) { let sortedIds = entities.keys.sorted() for id in sortedIds { if id != sortedIds.first { out += "\n" } guard let entity = entities[id] else { continue } out += "\(primaryField.uppercased()) \(id)\n" for key in entity.orderedNames { guard key != primaryField else { continue } guard let value = entity.value(named: key) else { continue } let key = key.components(separatedBy: "[").first ?? key out += "\(key.uppercased()) \(value.toSimplifiedFormat)\n" } } } }
mit
8492b7a69147b6a6954a22fc2575843c
30.436364
104
0.550607
4.399491
false
false
false
false
matouka-suzuki/objc.io-swift-snippets
Reduce.playground/section-1.swift
1
431
// Playground - noun: a place where people can play // Reduce // http://www.objc.io/snippets/5.html let sum: [Int] -> Int = { $0.reduce(0, combine: +) } let product: [Int] -> Int = { $0.reduce(1, combine: *) } // 積 let all: [Bool] -> Bool = { $0.reduce(true, combine: {$0 && $1}) } let trueArray = [true,true,true] let isAllTrue = all(trueArray) let mixedArray = [true,true,false,true] let isAllTrue2 = all(mixedArray)
mit
bd9d3f4f273f13d19e8da93b5f4516c6
20.45
66
0.622378
2.732484
false
false
false
false
gregomni/swift
test/IRGen/MachO-objc-sections.swift
10
1135
// RUN: %swift -target arm64-apple-ios8.0 -disable-legacy-type-info -parse-stdlib -enable-objc-interop -disable-objc-attr-requires-foundation-module -I %S/Inputs/usr/include -emit-ir %s -o - | %FileCheck %s -check-prefix CHECK-MACHO // REQUIRES: OS=ios import ObjCInterop @objc class C { } extension C : P { public func method() { f(I()) } } @_objc_non_lazy_realization class D { } // CHECK-MACHO: @"$s4main1CCMf" = {{.*}}, section "__DATA,__objc_data, regular" // CHECK-MACHO: @"\01l_OBJC_LABEL_PROTOCOL_$_P" = {{.*}}, section "__DATA,__objc_protolist,coalesced,no_dead_strip" // CHECK-MACHO: @"\01l_OBJC_PROTOCOL_REFERENCE_$_P" = {{.*}}, section "__DATA,__objc_protorefs,coalesced,no_dead_strip" // CHECK-MACHO: @"objc_classes_$s4main1CCN" = {{.*}}, section "__DATA,__objc_classlist,regular,no_dead_strip" // CHECK-MACHO: @"objc_classes_$s4main1DCN" = {{.*}}, section "__DATA,__objc_classlist,regular,no_dead_strip" // CHECK-MACHO: @objc_categories = {{.*}}, section "__DATA,__objc_catlist,regular,no_dead_strip" // CHECK-MACHO: @objc_non_lazy_classes = {{.*}}, section "__DATA,__objc_nlclslist,regular,no_dead_strip"
apache-2.0
5736349c0eb46315538e7f4437c55eb0
39.535714
232
0.662555
3.018617
false
false
false
false
luanlzsn/EasyPass
EasyPass/Carthage/Checkouts/IQKeyboardManager/Demo/Swift_Demo/ViewController/ChatViewController.swift
1
2832
// // ChatViewController.swift // Demo // // Created by IEMacBook01 on 23/05/16. // Copyright © 2016 Iftekhar. All rights reserved. // class ChatViewController: UIViewController, UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate { @IBOutlet var tableView : UITableView! @IBOutlet var buttonSend : UIButton! @IBOutlet var inputTextField : UITextField! var texts = ["This is demo text chat. Enter your message and hit `Send` to add more chat."] override func viewDidLoad() { super.viewDidLoad() inputTextField.inputAccessoryView = UIView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) NotificationCenter.default.addObserver(self, selector: #selector(self.textFieldDidChange(_:)), name: NSNotification.Name.UITextFieldTextDidChange, object: inputTextField) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UITextFieldTextDidChange, object: inputTextField) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return texts.count } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return 100 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ChatTableViewCell", for: indexPath) as! ChatTableViewCell cell.chatLabel.text = texts[(indexPath as NSIndexPath).row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } @IBAction func sendAction(_ sender : UIButton) { if inputTextField.text?.characters.count != 0 { let indexPath = IndexPath(row: tableView.numberOfRows(inSection: 0), section: 0) texts.append(inputTextField.text!) inputTextField.text = "" buttonSend.isEnabled = false tableView.insertRows(at: [indexPath], with:UITableViewRowAnimation.automatic) tableView.scrollToRow(at: indexPath, at:UITableViewScrollPosition.none, animated:true) } } @objc func textFieldDidChange(_ notification: Notification) { buttonSend.isEnabled = inputTextField.text?.characters.count != 0 } func textFieldDidBeginEditing(_ textField: UITextField) { } }
mit
5adc0e61d469e76184ea1e846c326481
34.3875
181
0.683504
5.465251
false
false
false
false
phatblat/realm-cocoa
RealmSwift/Tests/ObjectSchemaInitializationTests.swift
1
36653
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import XCTest import Realm.Private import Realm.Dynamic import Foundation #if DEBUG @testable import RealmSwift #else import RealmSwift #endif @available(*, deprecated) // Silence deprecation warnings for RealmOptional class ObjectSchemaInitializationTests: TestCase { func testAllValidTypes() { let object = SwiftObject() let objectSchema = object.objectSchema let noSuchCol = objectSchema["noSuchCol"] XCTAssertNil(noSuchCol) let boolCol = objectSchema["boolCol"] XCTAssertNotNil(boolCol) XCTAssertEqual(boolCol!.name, "boolCol") XCTAssertEqual(boolCol!.type, PropertyType.bool) XCTAssertFalse(boolCol!.isIndexed) XCTAssertFalse(boolCol!.isOptional) XCTAssertNil(boolCol!.objectClassName) let intCol = objectSchema["intCol"] XCTAssertNotNil(intCol) XCTAssertEqual(intCol!.name, "intCol") XCTAssertEqual(intCol!.type, PropertyType.int) XCTAssertFalse(intCol!.isIndexed) XCTAssertFalse(intCol!.isOptional) XCTAssertNil(intCol!.objectClassName) let floatCol = objectSchema["floatCol"] XCTAssertNotNil(floatCol) XCTAssertEqual(floatCol!.name, "floatCol") XCTAssertEqual(floatCol!.type, PropertyType.float) XCTAssertFalse(floatCol!.isIndexed) XCTAssertFalse(floatCol!.isOptional) XCTAssertNil(floatCol!.objectClassName) let doubleCol = objectSchema["doubleCol"] XCTAssertNotNil(doubleCol) XCTAssertEqual(doubleCol!.name, "doubleCol") XCTAssertEqual(doubleCol!.type, PropertyType.double) XCTAssertFalse(doubleCol!.isIndexed) XCTAssertFalse(doubleCol!.isOptional) XCTAssertNil(doubleCol!.objectClassName) let stringCol = objectSchema["stringCol"] XCTAssertNotNil(stringCol) XCTAssertEqual(stringCol!.name, "stringCol") XCTAssertEqual(stringCol!.type, PropertyType.string) XCTAssertFalse(stringCol!.isIndexed) XCTAssertFalse(stringCol!.isOptional) XCTAssertNil(stringCol!.objectClassName) let binaryCol = objectSchema["binaryCol"] XCTAssertNotNil(binaryCol) XCTAssertEqual(binaryCol!.name, "binaryCol") XCTAssertEqual(binaryCol!.type, PropertyType.data) XCTAssertFalse(binaryCol!.isIndexed) XCTAssertFalse(binaryCol!.isOptional) XCTAssertNil(binaryCol!.objectClassName) let dateCol = objectSchema["dateCol"] XCTAssertNotNil(dateCol) XCTAssertEqual(dateCol!.name, "dateCol") XCTAssertEqual(dateCol!.type, PropertyType.date) XCTAssertFalse(dateCol!.isIndexed) XCTAssertFalse(dateCol!.isOptional) XCTAssertNil(dateCol!.objectClassName) let uuidCol = objectSchema["uuidCol"] XCTAssertNotNil(uuidCol) XCTAssertEqual(uuidCol!.name, "uuidCol") XCTAssertEqual(uuidCol!.type, PropertyType.UUID) XCTAssertFalse(uuidCol!.isIndexed) XCTAssertFalse(uuidCol!.isOptional) XCTAssertNil(uuidCol!.objectClassName) let anyCol = objectSchema["anyCol"] XCTAssertNotNil(anyCol) XCTAssertEqual(anyCol!.name, "anyCol") XCTAssertEqual(anyCol!.type, PropertyType.any) XCTAssertFalse(anyCol!.isIndexed) XCTAssertFalse(anyCol!.isOptional) XCTAssertNil(anyCol!.objectClassName) let objectCol = objectSchema["objectCol"] XCTAssertNotNil(objectCol) XCTAssertEqual(objectCol!.name, "objectCol") XCTAssertEqual(objectCol!.type, PropertyType.object) XCTAssertFalse(objectCol!.isIndexed) XCTAssertTrue(objectCol!.isOptional) XCTAssertEqual(objectCol!.objectClassName!, "SwiftBoolObject") let arrayCol = objectSchema["arrayCol"] XCTAssertNotNil(arrayCol) XCTAssertEqual(arrayCol!.name, "arrayCol") XCTAssertEqual(arrayCol!.type, PropertyType.object) XCTAssertTrue(arrayCol!.isArray) XCTAssertFalse(arrayCol!.isIndexed) XCTAssertFalse(arrayCol!.isOptional) XCTAssertEqual(objectCol!.objectClassName!, "SwiftBoolObject") let setCol = objectSchema["setCol"] XCTAssertNotNil(setCol) XCTAssertEqual(setCol!.name, "setCol") XCTAssertEqual(setCol!.type, PropertyType.object) XCTAssertTrue(setCol!.isSet) XCTAssertFalse(setCol!.isIndexed) XCTAssertFalse(setCol!.isOptional) XCTAssertEqual(setCol!.objectClassName!, "SwiftBoolObject") let dynamicArrayCol = SwiftCompanyObject().objectSchema["employees"] XCTAssertNotNil(dynamicArrayCol) XCTAssertEqual(dynamicArrayCol!.name, "employees") XCTAssertEqual(dynamicArrayCol!.type, PropertyType.object) XCTAssertTrue(dynamicArrayCol!.isArray) XCTAssertFalse(dynamicArrayCol!.isIndexed) XCTAssertFalse(dynamicArrayCol!.isOptional) XCTAssertEqual(dynamicArrayCol!.objectClassName!, "SwiftEmployeeObject") let dynamicSetCol = SwiftCompanyObject().objectSchema["employeeSet"] XCTAssertNotNil(dynamicSetCol) XCTAssertEqual(dynamicSetCol!.name, "employeeSet") XCTAssertEqual(dynamicSetCol!.type, PropertyType.object) XCTAssertTrue(dynamicSetCol!.isSet) XCTAssertFalse(dynamicSetCol!.isIndexed) XCTAssertFalse(dynamicSetCol!.isOptional) XCTAssertEqual(dynamicSetCol!.objectClassName!, "SwiftEmployeeObject") } func testInvalidObjects() { let schema = SwiftFakeObjectSubclass.sharedSchema()! XCTAssertEqual(schema.properties.count, 2) assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithAnyObject.self), reason: "Property SwiftObjectWithAnyObject.anyObject is declared as NSObject") assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithStringArray.self), reason: "Property SwiftObjectWithStringArray.stringArray is declared as Array<String>") assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithOptionalStringArray.self), reason: "Property SwiftObjectWithOptionalStringArray.stringArray is declared as Optional<Array<String>>") assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithBadPropertyName.self), reason: "Property names beginning with 'new' are not supported.") assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithManagedLazyProperty.self), reason: "Lazy managed property 'foobar' is not allowed on a Realm Swift object class.") assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithDynamicManagedLazyProperty.self), reason: "Lazy managed property 'foobar' is not allowed on a Realm Swift object class.") // Shouldn't throw when not ignoring a property of a type we can't persist if it's not dynamic _ = RLMObjectSchema(forObjectClass: SwiftObjectWithEnum.self) // Shouldn't throw when not ignoring a property of a type we can't persist if it's not dynamic _ = RLMObjectSchema(forObjectClass: SwiftObjectWithStruct.self) assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithDatePrimaryKey.self), reason: "Property 'date' cannot be made the primary key of 'SwiftObjectWithDatePrimaryKey'") assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithNSURL.self), reason: "Property SwiftObjectWithNSURL.url is declared as NSURL") assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithNonOptionalLinkProperty.self), reason: "Object property 'objectCol' must be marked as optional.") assertThrows(RLMObjectSchema(forObjectClass: OptionalAnyRealmValueList.self), reason: "List<AnyRealmValue> property 'invalid' must not be marked as optional") assertThrows(RLMObjectSchema(forObjectClass: OptionalAnyRealmValueSet.self), reason: "MutableSet<AnyRealmValue> property 'invalid' must not be marked as optional") assertThrows(RLMObjectSchema(forObjectClass: OptionalAnyRealmValueDictionary.self), reason: "Map<String, AnyRealmValue> property 'invalid' must not be marked as optional") } func testPrimaryKey() { XCTAssertNil(SwiftObject().objectSchema.primaryKeyProperty, "Object should default to having no primary key property") XCTAssertEqual(SwiftPrimaryStringObject().objectSchema.primaryKeyProperty!.name, "stringCol") } func testIgnoredProperties() { let schema = SwiftIgnoredPropertiesObject().objectSchema XCTAssertNil(schema["runtimeProperty"], "The object schema shouldn't contain ignored properties") XCTAssertNil(schema["runtimeDefaultProperty"], "The object schema shouldn't contain ignored properties") XCTAssertNil(schema["readOnlyProperty"], "The object schema shouldn't contain read-only properties") } func testIndexedProperties() { XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["stringCol"]!.isIndexed) XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["intCol"]!.isIndexed) XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["int8Col"]!.isIndexed) XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["int16Col"]!.isIndexed) XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["int32Col"]!.isIndexed) XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["int64Col"]!.isIndexed) XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["boolCol"]!.isIndexed) XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["dateCol"]!.isIndexed) XCTAssertFalse(SwiftIndexedPropertiesObject().objectSchema["floatCol"]!.isIndexed) XCTAssertFalse(SwiftIndexedPropertiesObject().objectSchema["doubleCol"]!.isIndexed) XCTAssertFalse(SwiftIndexedPropertiesObject().objectSchema["dataCol"]!.isIndexed) } func testOptionalProperties() { let schema = RLMObjectSchema(forObjectClass: SwiftOptionalObject.self) for prop in schema.properties { XCTAssertTrue(prop.optional) } let types = Set(schema.properties.map { $0.type }) XCTAssertEqual(types, Set([.string, .string, .data, .date, .object, .int, .float, .double, .bool, .decimal128, .objectId, .UUID])) } func testImplicitlyUnwrappedOptionalsAreParsedAsOptionals() { let schema = SwiftImplicitlyUnwrappedOptionalObject().objectSchema XCTAssertTrue(schema["optObjectCol"]!.isOptional) XCTAssertTrue(schema["optNSStringCol"]!.isOptional) XCTAssertTrue(schema["optStringCol"]!.isOptional) XCTAssertTrue(schema["optBinaryCol"]!.isOptional) XCTAssertTrue(schema["optDateCol"]!.isOptional) XCTAssertTrue(schema["optDecimalCol"]!.isOptional) XCTAssertTrue(schema["optObjectIdCol"]!.isOptional) XCTAssertTrue(schema["optUuidCol"]!.isOptional) } func testNonRealmOptionalTypesDeclaredAsRealmOptional() { assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithNonRealmOptionalType.self)) } func testNotExplicitlyIgnoredComputedProperties() { let schema = SwiftComputedPropertyNotIgnoredObject().objectSchema // The two computed properties should not appear on the schema. XCTAssertEqual(schema.properties.count, 1) XCTAssertNotNil(schema["_urlBacking"]) } func testMultiplePrimaryKeys() { assertThrows(RLMObjectSchema(forObjectClass: SwiftObjectWithMultiplePrimaryKeys.self), reason: "Properties 'pk2' and 'pk1' are both marked as the primary key of 'SwiftObjectWithMultiplePrimaryKeys'") } #if DEBUG // this test depends on @testable import func assertType<T: SchemaDiscoverable>(_ value: T, _ propertyType: PropertyType, optional: Bool = false, list: Bool = false, set: Bool = false, objectType: String? = nil, hasSelectors: Bool = true, line: UInt = #line) { let prop = RLMProperty(name: "property", value: value) XCTAssertEqual(prop.type, propertyType, line: line) XCTAssertEqual(prop.optional, optional, line: line) XCTAssertEqual(prop.array, list, line: line) XCTAssertEqual(prop.set, set, line: line) XCTAssertEqual(prop.objectClassName, objectType, line: line) if hasSelectors { XCTAssertNotNil(prop.getterSel, line: line) XCTAssertNotNil(prop.setterSel, line: line) } else { XCTAssertNil(prop.getterSel, line: line) XCTAssertNil(prop.setterSel, line: line) } } func testPropertyPopulation() { assertType(Int(), .int) assertType(Int8(), .int) assertType(Int16(), .int) assertType(Int32(), .int) assertType(Int64(), .int) assertType(Bool(), .bool) assertType(Float(), .float) assertType(Double(), .double) assertType(String(), .string) assertType(Data(), .data) assertType(Date(), .date) assertType(UUID(), .UUID) assertType(Decimal128(), .decimal128) assertType(ObjectId(), .objectId) assertType(Optional<Int>.none, .int, optional: true) assertType(Optional<Int8>.none, .int, optional: true) assertType(Optional<Int16>.none, .int, optional: true) assertType(Optional<Int32>.none, .int, optional: true) assertType(Optional<Int64>.none, .int, optional: true) assertType(Optional<Bool>.none, .bool, optional: true) assertType(Optional<Float>.none, .float, optional: true) assertType(Optional<Double>.none, .double, optional: true) assertType(Optional<String>.none, .string, optional: true) assertType(Optional<Data>.none, .data, optional: true) assertType(Optional<Date>.none, .date, optional: true) assertType(Optional<UUID>.none, .UUID, optional: true) assertType(Optional<Decimal128>.none, .decimal128, optional: true) assertType(Optional<ObjectId>.none, .objectId, optional: true) assertType(RealmProperty<Int?>(), .int, optional: true, hasSelectors: false) assertType(RealmProperty<Int8?>(), .int, optional: true, hasSelectors: false) assertType(RealmProperty<Int16?>(), .int, optional: true, hasSelectors: false) assertType(RealmProperty<Int32?>(), .int, optional: true, hasSelectors: false) assertType(RealmProperty<Int64?>(), .int, optional: true, hasSelectors: false) assertType(RealmProperty<Bool?>(), .bool, optional: true, hasSelectors: false) assertType(RealmProperty<Float?>(), .float, optional: true, hasSelectors: false) assertType(RealmProperty<Double?>(), .double, optional: true, hasSelectors: false) assertType(List<Int>(), .int, list: true, hasSelectors: false) assertType(List<Int8>(), .int, list: true, hasSelectors: false) assertType(List<Int16>(), .int, list: true, hasSelectors: false) assertType(List<Int32>(), .int, list: true, hasSelectors: false) assertType(List<Int64>(), .int, list: true, hasSelectors: false) assertType(List<Bool>(), .bool, list: true, hasSelectors: false) assertType(List<Float>(), .float, list: true, hasSelectors: false) assertType(List<Double>(), .double, list: true, hasSelectors: false) assertType(List<String>(), .string, list: true, hasSelectors: false) assertType(List<Data>(), .data, list: true, hasSelectors: false) assertType(List<Date>(), .date, list: true, hasSelectors: false) assertType(List<UUID>(), .UUID, list: true, hasSelectors: false) assertType(List<Decimal128>(), .decimal128, list: true, hasSelectors: false) assertType(List<ObjectId>(), .objectId, list: true, hasSelectors: false) assertType(List<Int?>(), .int, optional: true, list: true, hasSelectors: false) assertType(List<Int8?>(), .int, optional: true, list: true, hasSelectors: false) assertType(List<Int16?>(), .int, optional: true, list: true, hasSelectors: false) assertType(List<Int32?>(), .int, optional: true, list: true, hasSelectors: false) assertType(List<Int64?>(), .int, optional: true, list: true, hasSelectors: false) assertType(List<Bool?>(), .bool, optional: true, list: true, hasSelectors: false) assertType(List<Float?>(), .float, optional: true, list: true, hasSelectors: false) assertType(List<Double?>(), .double, optional: true, list: true, hasSelectors: false) assertType(List<String?>(), .string, optional: true, list: true, hasSelectors: false) assertType(List<Data?>(), .data, optional: true, list: true, hasSelectors: false) assertType(List<Date?>(), .date, optional: true, list: true, hasSelectors: false) assertType(List<UUID?>(), .UUID, optional: true, list: true, hasSelectors: false) assertType(List<Decimal128?>(), .decimal128, optional: true, list: true, hasSelectors: false) assertType(List<ObjectId?>(), .objectId, optional: true, list: true, hasSelectors: false) assertType(MutableSet<Int>(), .int, set: true, hasSelectors: false) assertType(MutableSet<Int8>(), .int, set: true, hasSelectors: false) assertType(MutableSet<Int16>(), .int, set: true, hasSelectors: false) assertType(MutableSet<Int32>(), .int, set: true, hasSelectors: false) assertType(MutableSet<Int64>(), .int, set: true, hasSelectors: false) assertType(MutableSet<Bool>(), .bool, set: true, hasSelectors: false) assertType(MutableSet<Float>(), .float, set: true, hasSelectors: false) assertType(MutableSet<Double>(), .double, set: true, hasSelectors: false) assertType(MutableSet<String>(), .string, set: true, hasSelectors: false) assertType(MutableSet<Data>(), .data, set: true, hasSelectors: false) assertType(MutableSet<Date>(), .date, set: true, hasSelectors: false) assertType(MutableSet<UUID>(), .UUID, set: true, hasSelectors: false) assertType(MutableSet<Decimal128>(), .decimal128, set: true, hasSelectors: false) assertType(MutableSet<ObjectId>(), .objectId, set: true, hasSelectors: false) assertType(MutableSet<Int?>(), .int, optional: true, set: true, hasSelectors: false) assertType(MutableSet<Int8?>(), .int, optional: true, set: true, hasSelectors: false) assertType(MutableSet<Int16?>(), .int, optional: true, set: true, hasSelectors: false) assertType(MutableSet<Int32?>(), .int, optional: true, set: true, hasSelectors: false) assertType(MutableSet<Int64?>(), .int, optional: true, set: true, hasSelectors: false) assertType(MutableSet<Bool?>(), .bool, optional: true, set: true, hasSelectors: false) assertType(MutableSet<Float?>(), .float, optional: true, set: true, hasSelectors: false) assertType(MutableSet<Double?>(), .double, optional: true, set: true, hasSelectors: false) assertType(MutableSet<String?>(), .string, optional: true, set: true, hasSelectors: false) assertType(MutableSet<Data?>(), .data, optional: true, set: true, hasSelectors: false) assertType(MutableSet<Date?>(), .date, optional: true, set: true, hasSelectors: false) assertType(MutableSet<UUID?>(), .UUID, optional: true, set: true, hasSelectors: false) assertType(MutableSet<Decimal128?>(), .decimal128, optional: true, set: true, hasSelectors: false) assertType(MutableSet<ObjectId?>(), .objectId, optional: true, set: true, hasSelectors: false) assertThrows(RLMProperty(name: "name", value: Object()), reason: "Object property 'name' must be marked as optional.") assertThrows(RLMProperty(name: "name", value: List<Object?>()), reason: "List<RealmSwiftObject> property 'name' must not be marked as optional.") assertThrows(RLMProperty(name: "name", value: MutableSet<Object?>()), reason: "MutableSet<RealmSwiftObject> property 'name' must not be marked as optional.") assertType(Object?.none, .object, optional: true, objectType: "RealmSwiftObject") assertType(List<Object>(), .object, list: true, objectType: "RealmSwiftObject", hasSelectors: false) assertType(MutableSet<Object>(), .object, set: true, objectType: "RealmSwiftObject", hasSelectors: false) } func assertType<T: _Persistable>(_ type: T.Type, _ propertyType: PropertyType, optional: Bool = false, list: Bool = false, set: Bool = false, map: Bool = false, objectType: String? = nil, line: UInt = #line) { let prop = RLMProperty(name: "_property", value: Persisted<T>()) XCTAssertEqual(prop.name, "property", line: line) XCTAssertEqual(prop.type, propertyType, line: line) XCTAssertEqual(prop.optional, optional, line: line) XCTAssertEqual(prop.array, list, line: line) XCTAssertEqual(prop.set, set, line: line) XCTAssertEqual(prop.dictionary, map, line: line) XCTAssertEqual(prop.objectClassName, objectType, line: line) XCTAssertNil(prop.getterSel, line: line) XCTAssertNil(prop.setterSel, line: line) } func testModernPropertyPopulation() { assertType(Int.self, .int) assertType(Int8.self, .int) assertType(Int16.self, .int) assertType(Int32.self, .int) assertType(Int64.self, .int) assertType(Bool.self, .bool) assertType(Float.self, .float) assertType(Double.self, .double) assertType(String.self, .string) assertType(Data.self, .data) assertType(Date.self, .date) assertType(UUID.self, .UUID) assertType(Decimal128.self, .decimal128) assertType(ObjectId.self, .objectId) assertType(AnyRealmValue.self, .any) assertType(ModernIntEnum.self, .int) assertType(ModernStringEnum.self, .string) assertType(Int?.self, .int, optional: true) assertType(Int8?.self, .int, optional: true) assertType(Int16?.self, .int, optional: true) assertType(Int32?.self, .int, optional: true) assertType(Int64?.self, .int, optional: true) assertType(Bool?.self, .bool, optional: true) assertType(Float?.self, .float, optional: true) assertType(Double?.self, .double, optional: true) assertType(String?.self, .string, optional: true) assertType(Data?.self, .data, optional: true) assertType(Date?.self, .date, optional: true) assertType(UUID?.self, .UUID, optional: true) assertType(Decimal128?.self, .decimal128, optional: true) assertType(ObjectId?.self, .objectId, optional: true) assertType(Object?.self, .object, optional: true, objectType: "RealmSwiftObject") assertType(EmbeddedObject?.self, .object, optional: true, objectType: "RealmSwiftEmbeddedObject") assertType(ModernIntEnum?.self, .int, optional: true) assertType(ModernStringEnum?.self, .string, optional: true) assertType(List<Int>.self, .int, list: true) assertType(List<Int8>.self, .int, list: true) assertType(List<Int16>.self, .int, list: true) assertType(List<Int32>.self, .int, list: true) assertType(List<Int64>.self, .int, list: true) assertType(List<Bool>.self, .bool, list: true) assertType(List<Float>.self, .float, list: true) assertType(List<Double>.self, .double, list: true) assertType(List<String>.self, .string, list: true) assertType(List<Data>.self, .data, list: true) assertType(List<Date>.self, .date, list: true) assertType(List<UUID>.self, .UUID, list: true) assertType(List<Decimal128>.self, .decimal128, list: true) assertType(List<ObjectId>.self, .objectId, list: true) assertType(List<AnyRealmValue>.self, .any, list: true) assertType(List<Object>.self, .object, list: true, objectType: "RealmSwiftObject") assertType(List<EmbeddedObject>.self, .object, list: true, objectType: "RealmSwiftEmbeddedObject") assertType(List<Int?>.self, .int, optional: true, list: true) assertType(List<Int8?>.self, .int, optional: true, list: true) assertType(List<Int16?>.self, .int, optional: true, list: true) assertType(List<Int32?>.self, .int, optional: true, list: true) assertType(List<Int64?>.self, .int, optional: true, list: true) assertType(List<Bool?>.self, .bool, optional: true, list: true) assertType(List<Float?>.self, .float, optional: true, list: true) assertType(List<Double?>.self, .double, optional: true, list: true) assertType(List<String?>.self, .string, optional: true, list: true) assertType(List<Data?>.self, .data, optional: true, list: true) assertType(List<Date?>.self, .date, optional: true, list: true) assertType(List<UUID?>.self, .UUID, optional: true, list: true) assertType(List<Decimal128?>.self, .decimal128, optional: true, list: true) assertType(List<ObjectId?>.self, .objectId, optional: true, list: true) assertType(MutableSet<Int>.self, .int, set: true) assertType(MutableSet<Int8>.self, .int, set: true) assertType(MutableSet<Int16>.self, .int, set: true) assertType(MutableSet<Int32>.self, .int, set: true) assertType(MutableSet<Int64>.self, .int, set: true) assertType(MutableSet<Bool>.self, .bool, set: true) assertType(MutableSet<Float>.self, .float, set: true) assertType(MutableSet<Double>.self, .double, set: true) assertType(MutableSet<String>.self, .string, set: true) assertType(MutableSet<Data>.self, .data, set: true) assertType(MutableSet<Date>.self, .date, set: true) assertType(MutableSet<UUID>.self, .UUID, set: true) assertType(MutableSet<Decimal128>.self, .decimal128, set: true) assertType(MutableSet<ObjectId>.self, .objectId, set: true) assertType(MutableSet<AnyRealmValue>.self, .any, set: true) assertType(MutableSet<Object>.self, .object, set: true, objectType: "RealmSwiftObject") assertType(MutableSet<EmbeddedObject>.self, .object, set: true, objectType: "RealmSwiftEmbeddedObject") assertType(MutableSet<Int?>.self, .int, optional: true, set: true) assertType(MutableSet<Int8?>.self, .int, optional: true, set: true) assertType(MutableSet<Int16?>.self, .int, optional: true, set: true) assertType(MutableSet<Int32?>.self, .int, optional: true, set: true) assertType(MutableSet<Int64?>.self, .int, optional: true, set: true) assertType(MutableSet<Bool?>.self, .bool, optional: true, set: true) assertType(MutableSet<Float?>.self, .float, optional: true, set: true) assertType(MutableSet<Double?>.self, .double, optional: true, set: true) assertType(MutableSet<String?>.self, .string, optional: true, set: true) assertType(MutableSet<Data?>.self, .data, optional: true, set: true) assertType(MutableSet<Date?>.self, .date, optional: true, set: true) assertType(MutableSet<UUID?>.self, .UUID, optional: true, set: true) assertType(MutableSet<Decimal128?>.self, .decimal128, optional: true, set: true) assertType(MutableSet<ObjectId?>.self, .objectId, optional: true, set: true) assertType(Map<String, Int>.self, .int, map: true) assertType(Map<String, Int8>.self, .int, map: true) assertType(Map<String, Int16>.self, .int, map: true) assertType(Map<String, Int32>.self, .int, map: true) assertType(Map<String, Int64>.self, .int, map: true) assertType(Map<String, Bool>.self, .bool, map: true) assertType(Map<String, Float>.self, .float, map: true) assertType(Map<String, Double>.self, .double, map: true) assertType(Map<String, String>.self, .string, map: true) assertType(Map<String, Data>.self, .data, map: true) assertType(Map<String, Date>.self, .date, map: true) assertType(Map<String, UUID>.self, .UUID, map: true) assertType(Map<String, Decimal128>.self, .decimal128, map: true) assertType(Map<String, ObjectId>.self, .objectId, map: true) assertType(Map<String, AnyRealmValue>.self, .any, map: true) assertType(Map<String, Int?>.self, .int, optional: true, map: true) assertType(Map<String, Int8?>.self, .int, optional: true, map: true) assertType(Map<String, Int16?>.self, .int, optional: true, map: true) assertType(Map<String, Int32?>.self, .int, optional: true, map: true) assertType(Map<String, Int64?>.self, .int, optional: true, map: true) assertType(Map<String, Bool?>.self, .bool, optional: true, map: true) assertType(Map<String, Float?>.self, .float, optional: true, map: true) assertType(Map<String, Double?>.self, .double, optional: true, map: true) assertType(Map<String, String?>.self, .string, optional: true, map: true) assertType(Map<String, Data?>.self, .data, optional: true, map: true) assertType(Map<String, Date?>.self, .date, optional: true, map: true) assertType(Map<String, UUID?>.self, .UUID, optional: true, map: true) assertType(Map<String, Decimal128?>.self, .decimal128, optional: true, map: true) assertType(Map<String, ObjectId?>.self, .objectId, optional: true, map: true) assertType(Map<String, Object?>.self, .object, optional: true, map: true, objectType: "RealmSwiftObject") assertType(Map<String, EmbeddedObject?>.self, .object, optional: true, map: true, objectType: "RealmSwiftEmbeddedObject") assertThrows(RLMProperty(name: "_name", value: Persisted<Object>()), reason: "Object property 'name' must be marked as optional.") assertThrows(RLMProperty(name: "_name", value: Persisted<List<Object?>>()), reason: "List<RealmSwiftObject> property 'name' must not be marked as optional.") assertThrows(RLMProperty(name: "_name", value: Persisted<MutableSet<Object?>>()), reason: "MutableSet<RealmSwiftObject> property 'name' must not be marked as optional.") assertThrows(RLMProperty(name: "_name", value: Persisted<LinkingObjects<Object>>()), reason: "LinkingObjects<RealmSwiftObject> property 'name' must set the origin property name with @Persisted(originProperty: \"name\").") assertThrows(RLMProperty(name: "_name", value: Persisted<EmbeddedObject>()), reason: "Object property 'name' must be marked as optional.") assertThrows(RLMProperty(name: "_name", value: Persisted<List<EmbeddedObject?>>()), reason: "List<RealmSwiftObject> property 'name' must not be marked as optional.") assertThrows(RLMProperty(name: "_name", value: Persisted<MutableSet<EmbeddedObject?>>()), reason: "MutableSet<RealmSwiftObject> property 'name' must not be marked as optional.") assertThrows(RLMProperty(name: "_name", value: Persisted<LinkingObjects<EmbeddedObject>>()), reason: "LinkingObjects<RealmSwiftEmbeddedObject> property 'name' must set the origin property name with @Persisted(originProperty: \"name\").") assertThrows(RLMProperty(name: "_name", value: Persisted<Map<String, Object>>()), reason: "Map<String, RealmSwiftObject> property 'name' must be marked as optional.") assertThrows(RLMProperty(name: "_name", value: Persisted<Map<String, EmbeddedObject>>()), reason: "Map<String, RealmSwiftObject> property 'name' must be marked as optional.") } func testModernIndexed() { XCTAssertFalse(RLMProperty(name: "_property", value: Persisted<Int>()).indexed) XCTAssertFalse(RLMProperty(name: "_property", value: Persisted<Int>(wrappedValue: 1)).indexed) XCTAssertFalse(RLMProperty(name: "_property", value: Persisted<Int>(indexed: false)).indexed) XCTAssertFalse(RLMProperty(name: "_property", value: Persisted<Int>(wrappedValue: 1, indexed: false)).indexed) XCTAssertTrue(RLMProperty(name: "_property", value: Persisted<Int>(indexed: true)).indexed) XCTAssertTrue(RLMProperty(name: "_property", value: Persisted<Int>(wrappedValue: 1, indexed: true)).indexed) } func testModernPrimary() { XCTAssertFalse(RLMProperty(name: "_property", value: Persisted<Int>()).isPrimary) XCTAssertFalse(RLMProperty(name: "_property", value: Persisted<Int>(wrappedValue: 1)).isPrimary) XCTAssertFalse(RLMProperty(name: "_property", value: Persisted<Int>(primaryKey: false)).isPrimary) XCTAssertFalse(RLMProperty(name: "_property", value: Persisted<Int>(wrappedValue: 1, primaryKey: false)).isPrimary) XCTAssertTrue(RLMProperty(name: "_property", value: Persisted<Int>(primaryKey: true)).isPrimary) XCTAssertTrue(RLMProperty(name: "_property", value: Persisted<Int>(wrappedValue: 1, primaryKey: true)).isPrimary) } #endif // DEBUG } class SwiftFakeObject: Object { override class func _realmIgnoreClass() -> Bool { return true } @objc dynamic var requiredProp: String? } class SwiftObjectWithNSURL: SwiftFakeObject { @objc dynamic var url = NSURL(string: "http://realm.io")! } class SwiftObjectWithAnyObject: SwiftFakeObject { @objc dynamic var anyObject: AnyObject = NSObject() } class SwiftObjectWithStringArray: SwiftFakeObject { @objc dynamic var stringArray = [String]() } class SwiftObjectWithOptionalStringArray: SwiftFakeObject { @objc dynamic var stringArray: [String]? } enum SwiftEnum { case case1 case case2 } class SwiftObjectWithEnum: SwiftFakeObject { var swiftEnum = SwiftEnum.case1 } class SwiftObjectWithStruct: SwiftFakeObject { var swiftStruct = SortDescriptor(keyPath: "prop") } class SwiftObjectWithDatePrimaryKey: SwiftFakeObject { @objc dynamic var date = Date() override class func primaryKey() -> String? { return "date" } } class SwiftFakeObjectSubclass: SwiftFakeObject { @objc dynamic var dateCol = Date() } // swiftlint:disable:next type_name class SwiftObjectWithNonNullableOptionalProperties: SwiftFakeObject { @objc dynamic var optDateCol: Date? } class SwiftObjectWithNonOptionalLinkProperty: SwiftFakeObject { @objc dynamic var objectCol = SwiftBoolObject() } extension Set: RealmOptionalType { } @available(*, deprecated) // Silence deprecation warnings for RealmOptional class SwiftObjectWithNonRealmOptionalType: SwiftFakeObject { let set = RealmOptional<Set<Int>>() } class SwiftObjectWithBadPropertyName: SwiftFakeObject { @objc dynamic var newValue = false } class SwiftObjectWithManagedLazyProperty: SwiftFakeObject { lazy var foobar: String = "foo" } // swiftlint:disable:next type_name class SwiftObjectWithDynamicManagedLazyProperty: SwiftFakeObject { @objc dynamic lazy var foobar: String = "foo" } class SwiftObjectWithMultiplePrimaryKeys: SwiftFakeObject { @Persisted(primaryKey: true) var pk1: Int @Persisted(primaryKey: true) var pk2: Int } class OptionalAnyRealmValueList: SwiftFakeObject { let invalid = List<AnyRealmValue?>() } class OptionalAnyRealmValueSet: SwiftFakeObject { let invalid = MutableSet<AnyRealmValue?>() } class OptionalAnyRealmValueDictionary: SwiftFakeObject { let invalid = Map<String, AnyRealmValue?>() }
apache-2.0
a6089937096023aaaa06665c3fe3bce4
53.140325
165
0.678607
4.356192
false
false
false
false
Loveswift/TabbarTest
TabbarViewTest/TabbarViewTest/ForthViewController.swift
1
2835
// // ForthViewController.swift // TabbarViewTest // // Created by xjc on 16/5/1. // Copyright © 2016年 xjc. All rights reserved. // import UIKit class ForthViewController: UIViewController { var swipeLeft:UISwipeGestureRecognizer! var swipeRight:UISwipeGestureRecognizer! override func viewDidLoad() { super.viewDidLoad() swipeLeft = UISwipeGestureRecognizer(target: self, action: Selector("tappedRightButton")) swipeLeft.direction = UISwipeGestureRecognizerDirection.Left self.view.addGestureRecognizer(swipeLeft) swipeRight = UISwipeGestureRecognizer(target: self, action: Selector("tappedLeftButton")) swipeRight.direction = UISwipeGestureRecognizerDirection.Right self.view.addGestureRecognizer(swipeRight) } func tappedRightButton() { let selectedIndex = self.tabBarController?.selectedIndex let arrayViewController = self.tabBarController?.viewControllers if selectedIndex! < (arrayViewController?.count)!-1 { let fromView = self.tabBarController?.selectedViewController?.view let toView = self.tabBarController?.storyboard?.instantiateViewControllerWithIdentifier("Forth").view UIView.transitionFromView(fromView!, toView: toView!, duration: 0.5, options: UIViewAnimationOptions.TransitionFlipFromRight, completion: { (finished) -> Void in if(finished) { self.tabBarController?.selectedIndex = 3 } }) } } func tappedLeftButton() { let selectedIndex = self.tabBarController?.selectedIndex if(selectedIndex>0) { let fromView = self.tabBarController?.selectedViewController?.view let toView = self.tabBarController?.storyboard?.instantiateViewControllerWithIdentifier("Third").view UIView.transitionFromView(fromView!, toView: toView!, duration: 0.5, options: UIViewAnimationOptions.TransitionFlipFromLeft, completion: { (finished) -> Void in if(finished) { self.tabBarController?.selectedIndex = 2 } }) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
04dc0b1febf74e43cb1bfe58a07eb28a
34.4
173
0.649364
5.987315
false
false
false
false
devpunk/cartesian
cartesian/Model/DrawProject/Color/MDrawProjectColor.swift
1
2444
import UIKit class MDrawProjectColor { private(set) var items:[MDrawProjectColorItem] var selectedItem:Int init() { let systemCartesianBlue:MDrawProjectColorItemSystem = MDrawProjectColorItemSystem( color:UIColor.cartesianBlue) let systemCartesianGreen:MDrawProjectColorItemSystem = MDrawProjectColorItemSystem( color:UIColor.cartesianGreen) let systemBlack:MDrawProjectColorItemSystem = MDrawProjectColorItemSystem( color:UIColor.black) let systemWhite:MDrawProjectColorItemSystem = MDrawProjectColorItemSystem( color:UIColor.white) let systemRed:MDrawProjectColorItemSystem = MDrawProjectColorItemSystem( color:UIColor.red) let systemGreen:MDrawProjectColorItemSystem = MDrawProjectColorItemSystem( color:UIColor.green) let systemBlue:MDrawProjectColorItemSystem = MDrawProjectColorItemSystem( color:UIColor.blue) items = [ systemCartesianBlue, systemCartesianGreen, systemBlack, systemWhite, systemRed, systemGreen, systemBlue] selectedItem = 0 DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in self?.loadUserColors() } } //MARK: private private func loadUserColors() { DManager.sharedInstance?.fetchData( entityName:DColor.entityName) { [weak self] (data) in guard var colors:[DColor] = data as? [DColor] else { return } colors.sort { (colorA, colorB) -> Bool in return colorA.created < colorB.created } self?.insertUserColors(colors:colors) } } private func insertUserColors(colors:[DColor]) { for color:DColor in colors { let itemUser:MDrawProjectColorItemUser = MDrawProjectColorItemUser( model:color) items.append(itemUser) } } //MARK: public func selectedColor() -> UIColor { let item:MDrawProjectColorItem = items[selectedItem] return item.color } }
mit
f03e03fb47cf3750d3eea2a0af061191
27.091954
91
0.571195
5.278618
false
false
false
false
jonnguy/HSTracker
HSTracker/Importers/FileImporter.swift
1
2455
// // FileImporter.swift // HSTracker // // Created by Benjamin Michotte on 3/04/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation import RegexUtil struct FileImporter { func fileImport(url: URL) -> (Deck, [Card])? { let deckName = url.lastPathComponent.replace("\\.txt$", with: "") logger.verbose("Got deck name \(deckName)") var isArena = false let fileContent: [String]? do { let content = try NSString(contentsOf: url, encoding: String.Encoding.utf8.rawValue) fileContent = content.components(separatedBy: CharacterSet.newlines) } catch let error { logger.error("\(error)") return nil } guard let lines = fileContent else { logger.error("Card list not found") } let deck = Deck() deck.name = deckName var cards: [Card] = [] let regex: RegexPattern = "(\\d)(\\s|x)?([\\w\\s'\\.:!-]+)" for line in lines { guard !line.isBlank else { continue } // match "2xMirror Image" as well as "2 Mirror Image" or "2 GVG_002" if line.match(regex) { let matches = line.matches(regex) let cardName = matches[2].value.trim() if let count = Int(matches[0].value) { if count > 2 { isArena = true } var card = Cards.by(cardId: cardName) if card == nil { card = Cards.by(englishName: cardName) } if card == nil { card = Cards.by(name: cardName) } if let card = card { if card.playerClass != .neutral && deck.playerClass == .neutral { deck.playerClass = card.playerClass logger.verbose("Got class \(deck.playerClass)") } card.count = count logger.verbose("Got card \(card)") cards.append(card) } } } } deck.isArena = isArena guard deck.playerClass != .neutral else { logger.error("Class not found") return nil } return (deck, cards) } }
mit
19eff1a43cc992d190c67eaebf3b0581
30.063291
96
0.471475
4.859406
false
false
false
false
schultka/deploy-manager
src/Pods/Async/Async.swift
4
10880
// // Async.swift // // Created by Tobias DM on 15/07/14. // // OS X 10.10+ and iOS 8.0+ // Only use with ARC // // The MIT License (MIT) // Copyright (c) 2014 Tobias Due Munk // // 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 // MARK: - DSL for GCD queues private class GCD { /* dispatch_get_queue() */ class func mainQueue() -> dispatch_queue_t { return dispatch_get_main_queue() // Don't ever use dispatch_get_global_queue(qos_class_main(), 0) re https://gist.github.com/duemunk/34babc7ca8150ff81844 } class func userInteractiveQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0) } class func userInitiatedQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0) } class func utilityQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_UTILITY, 0) } class func backgroundQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0) } } // MARK: - Async – Struct public struct Async { private let block: dispatch_block_t private init(_ block: dispatch_block_t) { self.block = block } } // MARK: - Async – Static methods public extension Async { // Static methods /* dispatch_async() */ private static func async(block: dispatch_block_t, inQueue queue: dispatch_queue_t) -> Async { // Create a new block (Qos Class) from block to allow adding a notification to it later (see matching regular Async methods) // Create block with the "inherit" type let _block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, block) // Add block to queue dispatch_async(queue, _block) // Wrap block in a struct since dispatch_block_t can't be extended return Async(_block) } static func main(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.mainQueue()) } static func userInteractive(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.userInteractiveQueue()) } static func userInitiated(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.userInitiatedQueue()) } static func utility(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.utilityQueue()) } static func background(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.backgroundQueue()) } static func customQueue(queue: dispatch_queue_t, block: dispatch_block_t) -> Async { return Async.async(block, inQueue: queue) } /* dispatch_after() */ private static func after(seconds: Double, block: dispatch_block_t, inQueue queue: dispatch_queue_t) -> Async { let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC)) let time = dispatch_time(DISPATCH_TIME_NOW, nanoSeconds) return at(time, block: block, inQueue: queue) } private static func at(time: dispatch_time_t, block: dispatch_block_t, inQueue queue: dispatch_queue_t) -> Async { // See Async.async() for comments let _block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, block) dispatch_after(time, queue, _block) return Async(_block) } static func main(#after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.mainQueue()) } static func userInteractive(#after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.userInteractiveQueue()) } static func userInitiated(#after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.userInitiatedQueue()) } static func utility(#after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.utilityQueue()) } static func background(#after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.backgroundQueue()) } static func customQueue(#after: Double, queue: dispatch_queue_t, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: queue) } } // MARK: - Async – Regualar methods matching static ones public extension Async { /* dispatch_async() */ private func chain(block chainingBlock: dispatch_block_t, runInQueue queue: dispatch_queue_t) -> Async { // See Async.async() for comments let _chainingBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, chainingBlock) dispatch_block_notify(self.block, queue, _chainingBlock) return Async(_chainingBlock) } func main(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.mainQueue()) } func userInteractive(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.userInteractiveQueue()) } func userInitiated(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.userInitiatedQueue()) } func utility(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.utilityQueue()) } func background(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.backgroundQueue()) } func customQueue(queue: dispatch_queue_t, chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: queue) } /* dispatch_after() */ private func after(seconds: Double, block chainingBlock: dispatch_block_t, runInQueue queue: dispatch_queue_t) -> Async { // Create a new block (Qos Class) from block to allow adding a notification to it later (see Async) // Create block with the "inherit" type let _chainingBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, chainingBlock) // Wrap block to be called when previous block is finished let chainingWrapperBlock: dispatch_block_t = { // Calculate time from now let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC)) let time = dispatch_time(DISPATCH_TIME_NOW, nanoSeconds) dispatch_after(time, queue, _chainingBlock) } // Create a new block (Qos Class) from block to allow adding a notification to it later (see Async) // Create block with the "inherit" type let _chainingWrapperBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, chainingWrapperBlock) // Add block to queue *after* previous block is finished dispatch_block_notify(self.block, queue, _chainingWrapperBlock) // Wrap block in a struct since dispatch_block_t can't be extended return Async(_chainingBlock) } func main(#after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.mainQueue()) } func userInteractive(#after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.userInteractiveQueue()) } func userInitiated(#after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.userInitiatedQueue()) } func utility(#after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.utilityQueue()) } func background(#after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.backgroundQueue()) } func customQueue(#after: Double, queue: dispatch_queue_t, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: queue) } /* cancel */ public func cancel() { dispatch_block_cancel(block) } /* wait */ /// If optional parameter forSeconds is not provided, use DISPATCH_TIME_FOREVER public func wait(seconds: Double = 0.0) { if seconds != 0.0 { let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC)) let time = dispatch_time(DISPATCH_TIME_NOW, nanoSeconds) dispatch_block_wait(block, time) } else { dispatch_block_wait(block, DISPATCH_TIME_FOREVER) } } } // MARK: - Apply public struct Apply { // DSL for GCD dispatch_apply() // // Apply runs a block multiple times, before returning. // If you want run the block asynchronously from the current thread, // wrap it in an Async block, // e.g. Async.main { Apply.background(3) { ... } } public static func userInteractive(iterations: Int, block: Int -> ()) { dispatch_apply(iterations, GCD.userInteractiveQueue(), block) } public static func userInitiated(iterations: Int, block: Int -> ()) { dispatch_apply(iterations, GCD.userInitiatedQueue(), block) } public static func utility(iterations: Int, block: Int -> ()) { dispatch_apply(iterations, GCD.utilityQueue(), block) } public static func background(iterations: Int, block: Int -> ()) { dispatch_apply(iterations, GCD.backgroundQueue(), block) } public static func customQueue(iterations: Int, queue: dispatch_queue_t, block: Int -> ()) { dispatch_apply(iterations, queue, block) } } // MARK: - qos_class_t public extension qos_class_t { // Convenience description of qos_class_t // Calculated property var description: String { get { switch self { case qos_class_main(): return "Main" case QOS_CLASS_USER_INTERACTIVE: return "User Interactive" case QOS_CLASS_USER_INITIATED: return "User Initiated" case QOS_CLASS_DEFAULT: return "Default" case QOS_CLASS_UTILITY: return "Utility" case QOS_CLASS_BACKGROUND: return "Background" case QOS_CLASS_UNSPECIFIED: return "Unspecified" default: return "Unknown" } } } } // Binary operator for qos_class_t allows for comparison in switch-statements func ~=(lhs: qos_class_t, rhs: qos_class_t) -> Bool { return lhs.value ~= rhs.value } // Make qos_class_t equatable extension qos_class_t: Equatable {} public func ==(lhs: qos_class_t, rhs: qos_class_t) -> Bool { return lhs.value == rhs.value }
mit
8233ce7aff90529d71b9a58a8a491423
35.489933
126
0.714732
3.612625
false
false
false
false
bzatrok/tvOS-VideoCatalog
StockWise/AppDelegate.swift
1
6829
// // AppDelegate.swift // StockWise // // Created by Bence Zátrok on 13/12/15. // Copyright © 2015 Root. All rights reserved. // import UIKit import CoreData import TVMLKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, TVApplicationControllerDelegate { var window: UIWindow? var appController: TVApplicationController? static let TVBaseURL = "http://localhost:9001/" static let TVBootURL = "\(AppDelegate.TVBaseURL)js/application.js" func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { window = UIWindow(frame: UIScreen.mainScreen().bounds) let appControllerContext = TVApplicationControllerContext() guard let javaScriptURL = NSURL(string: AppDelegate.TVBootURL) else { fatalError("unable to create NSURL") } appControllerContext.javaScriptApplicationURL = javaScriptURL appControllerContext.launchOptions["BASEURL"] = AppDelegate.TVBaseURL appController = TVApplicationController(context: appControllerContext, window: window, delegate: self) return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationCachesDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.root.StockWise" in the application's caches Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("StockWise", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationCachesDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
4e3c851c1a2715c139056576b614eeae
52.335938
291
0.713491
5.905709
false
false
false
false
Fenrikur/ef-app_ios
Domain Model/EurofurenceModel/Private/Objects/Entities/KnowledgeGroupImpl.swift
1
1834
import Foundation struct KnowledgeGroupImpl: KnowledgeGroup { var identifier: KnowledgeGroupIdentifier var title: String var groupDescription: String var fontAwesomeCharacterAddress: Character var order: Int var entries: [KnowledgeEntry] } extension KnowledgeGroupImpl { static func fromServerModels(groups: [KnowledgeGroupCharacteristics], entries: [KnowledgeEntryCharacteristics], shareableURLFactory: ShareableURLFactory) -> [KnowledgeGroup] { return groups.map({ (group) -> KnowledgeGroup in let entries = entries .filter({ $0.groupIdentifier == group.identifier }) .map({ KnowledgeEntryImpl.fromServerModel($0, shareableURLFactory: shareableURLFactory) }) .sorted(by: { (first, second) in return first.order < second.order }) let defaultFontAwesomeBackupCharacter: Character = " " let fontAwesomeCharacter: Character = Int(group.fontAwesomeCharacterAddress, radix: 16) .let(UnicodeScalar.init) .let(Character.init) .defaultingTo(defaultFontAwesomeBackupCharacter) return KnowledgeGroupImpl(identifier: KnowledgeGroupIdentifier(group.identifier), title: group.groupName, groupDescription: group.groupDescription, fontAwesomeCharacterAddress: fontAwesomeCharacter, order: group.order, entries: entries) }).sorted(by: { (first, second) in return first.order < second.order }) } }
mit
0d24528df5163b2ddd0fefab7265e27f
40.681818
106
0.570338
6.093023
false
false
false
false
wilzh40/SoundSieve
SwiftSkeleton/PulsingLayer.swift
1
4648
// // PulsingLayer .swift // SoundSieve // // Created by Wilson Zhao on 4/25/15. // Copyright (c) 2015 Innogen. All rights reserved. // import Foundation import UIKit import QuartzCore class PulsingLayer: CALayer { var radius: CGFloat var fromValueForRadius: CGFloat var fromValueForAlpha: CGFloat var keyTimeForHalfOpacity: CGFloat var animationDuration: NSTimeInterval var pulseInterval: NSTimeInterval var animationGroup: CAAnimationGroup let singleton = Singleton.sharedInstance var meterInterval: Float var threshold: Float var intervalThreshold: Float var intervalsSinceLastBeat: Float override init() { // before super.init() self.radius = 100 self.fromValueForRadius = 2 self.fromValueForAlpha = 0.45 self.keyTimeForHalfOpacity = 0.45 self.animationDuration = 1 self.pulseInterval = 0 self.animationGroup = CAAnimationGroup(); // metering vars self.threshold = 0.94 self.meterInterval = 0.01 self.intervalThreshold = 5 self.intervalsSinceLastBeat = 0 super.init() // after super.init() self.repeatCount = 0; self.backgroundColor = UIColor(red: 0.0, green: 0.478, blue: 1.0, alpha: 1).CGColor; var tempPos = self.position; var diameter = self.radius * 2; self.bounds = CGRectMake(0, 0, diameter, diameter); self.cornerRadius = self.radius; self.position = tempPos; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { self.setupAnimationGroup() dispatch_async(dispatch_get_main_queue(), { // Play the animation once self.addAnimation(self.animationGroup, forKey: "pulse") // Then add a timer that meters the audio var timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "meterAudio", userInfo: nil, repeats: true) }) }) } @objc func meterAudio() { // Everytime the amplitude of the first channel exceeds a threshold // it will play the pulse animation again /*println(singleton.audioPlayer.peakPowerInDecibelsForChannel(1)) let lowAmplitude = singleton.audioPlayer.peakPowerInDecibelsForChannel(1) if lowAmplitude > -5 { self.addAnimation(self.animationGroup, forKey:nil) }*/ var normalizedValue = pow(10, singleton.audioPlayer.averagePowerInDecibelsForChannel(0) / 20) + pow(10, singleton.audioPlayer.averagePowerInDecibelsForChannel(1) / 20) //println(normalizedValue) if normalizedValue > self.threshold*2{ intervalsSinceLastBeat++ if intervalsSinceLastBeat > intervalThreshold { self.setupAnimationGroup() self.addAnimation(self.animationGroup, forKey:nil) intervalsSinceLastBeat = 0 } } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupAnimationGroup() { self.animationGroup = CAAnimationGroup() self.animationGroup.duration = self.animationDuration + self.pulseInterval self.animationGroup.repeatCount = self.repeatCount self.animationGroup.removedOnCompletion = false self.animationGroup.fillMode = kCAFillModeForwards; self.animationGroup.delegate = self var defaultCurve = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) self.animationGroup.timingFunction = defaultCurve var scaleAnimation = CABasicAnimation(keyPath: "transform.scale.xy") scaleAnimation.fromValue = self.fromValueForRadius scaleAnimation.toValue = 1.0; scaleAnimation.duration = self.animationDuration; var opacityAnimation = CAKeyframeAnimation(keyPath: "opacity") opacityAnimation.values = [self.fromValueForAlpha, 0.45, 0] opacityAnimation.keyTimes = [0, self.keyTimeForHalfOpacity, 1] opacityAnimation.duration = self.animationDuration opacityAnimation.removedOnCompletion = false var animations = [scaleAnimation, opacityAnimation] self.animationGroup.animations = animations } override func animationDidStop(anim: CAAnimation!, finished flag: Bool) { //self.removeFromSuperlayer() } }
mit
5f886337e5c3b7584d3fef108ddc40ec
33.686567
175
0.6392
5.079781
false
false
false
false
danielbreves/MusicTheory
Sources/Key.swift
1
2926
// // Key.swift // MusicTheory // // Created by Daniel Breves Ribeiro on 26/04/2015. // Copyright (c) 2015 Daniel Breves. All rights reserved. // import Foundation /** Represents a musical key with a note, a quality (e.g. major or minor) and a name (e.g. C minor). */ open class Key: Comparable { /** The key note. */ open let note: Note /** The quality of the key (e.g. minor). */ open let quality: String /** The name of the key (e.g. C minor). */ open let name: String fileprivate var chordCache = [String: Chord]() fileprivate(set) open lazy var scale: RootWithIntervals = { return self.note.scale(self.quality) }() /** Initializes the key with a note and a quality. - parameter note:The key note. - parameter note:The quality of the key (e.g. major or minor). - returns: The new Key instance. */ public init(note: Note, quality: String) { note.octave = 4 self.note = note self.quality = quality self.name = "\(note.name) \(quality)" } /** Initializes the key with a name and a quality. - parameter name:The name of the key. - parameter quality:The quality of the key (e.g. major or minor). - returns: The new Key instance. */ public convenience init(name: String, quality: String = "major") { let note = Note(name: name) self.init(note: note, quality: quality) } /** Generates a chord from a key degree and a type. - parameter degree:The degree of the chord to generate. - parameter degree:The type of chord to generate (e.g. maj). - returns: a new chord. */ open func chord(_ degree: String, type: String = "maj") -> Chord? { let chordName = "\(degree)\(type)" var chord = chordCache[chordName] if (chord != nil) { return chord } var degreeSymbol = degree let flatOrSharp = degree[degree.startIndex] if (flatOrSharp == Music.FLAT || flatOrSharp == Music.SHARP) { degreeSymbol.remove(at: degreeSymbol.startIndex) } let scaleIndex = Music.Degrees.index(of: degreeSymbol) var root = self.scale.notes[scaleIndex!].copy() if (flatOrSharp == Music.FLAT) { --root } else if (flatOrSharp == Music.SHARP) { ++root } chord = root.chord(type) chordCache[chordName] = chord return chord } } /** Checks if the first key note's value is less than the second. - parameter lhs:The first key to compare. - parameter rhs:The second key to compare. - returns: a bool. */ public func <(lhs: Key, rhs: Key) -> Bool { let lhsNote = lhs.note let rhsNote = rhs.note rhsNote.octave = lhsNote.octave return rhsNote.value < lhsNote.value } /** Checks if two keys have the same name. - parameter lhs:The first key to compare. - parameter rhs:The second key to compare. - returns: a bool. */ public func ==(lhs: Key, rhs: Key) -> Bool { return lhs.name == rhs.name }
mit
725decb707319787150e5704e69959e9
22.222222
98
0.637731
3.563946
false
false
false
false
renzifeng/ZFZhiHuDaily
ZFZhiHuDaily/NewsComments/Model/ZFComments.swift
1
2518
// // ZFComments.swift // // Created by 任子丰 on 16/1/30 // Copyright (c) 任子丰. All rights reserved. // import Foundation import SwiftyJSON public class ZFComments: NSObject { // MARK: Declaration for string constants to be used to decode and also serialize. internal let kZFCommentsAuthorKey: String = "author" internal let kZFCommentsContentKey: String = "content" internal let kZFCommentsInternalIdentifierKey: String = "id" internal let kZFCommentsAvatarKey: String = "avatar" internal let kZFCommentsLikesKey: String = "likes" internal let kZFCommentsTimeKey: String = "time" // MARK: Properties public var author: String? public var content: String? public var internalIdentifier: Int? public var avatar: String? public var likes: Int? public var time: Int? // MARK: SwiftyJSON Initalizers /** Initates the class based on the object - parameter object: The object of either Dictionary or Array kind that was passed. - returns: An initalized instance of the class. */ convenience public init(object: AnyObject) { self.init(json: JSON(object)) } /** Initates the class based on the JSON that was passed. - parameter json: JSON object from SwiftyJSON. - returns: An initalized instance of the class. */ public init(json: JSON) { author = json[kZFCommentsAuthorKey].string content = json[kZFCommentsContentKey].string internalIdentifier = json[kZFCommentsInternalIdentifierKey].int avatar = json[kZFCommentsAvatarKey].string likes = json[kZFCommentsLikesKey].int time = json[kZFCommentsTimeKey].int } /** Generates description of the object in the form of a NSDictionary. - returns: A Key value pair containing all valid values in the object. */ public func dictionaryRepresentation() -> [String : AnyObject ] { var dictionary: [String : AnyObject ] = [ : ] if author != nil { dictionary.updateValue(author!, forKey: kZFCommentsAuthorKey) } if content != nil { dictionary.updateValue(content!, forKey: kZFCommentsContentKey) } if internalIdentifier != nil { dictionary.updateValue(internalIdentifier!, forKey: kZFCommentsInternalIdentifierKey) } if avatar != nil { dictionary.updateValue(avatar!, forKey: kZFCommentsAvatarKey) } if likes != nil { dictionary.updateValue(likes!, forKey: kZFCommentsLikesKey) } if time != nil { dictionary.updateValue(time!, forKey: kZFCommentsTimeKey) } return dictionary } }
apache-2.0
7135497116a160925ca7c1d19e815fee
28.139535
88
0.714286
3.940252
false
false
false
false
typelift/swiftz
Tests/SwiftzTests/ArrayExtSpec.swift
2
5691
// // ArrayExtSpec.swift // Swiftz // // Created by Robert Widmann on 1/19/15. // Copyright (c) 2015-2016 TypeLift. All rights reserved. // import XCTest import Swiftz import SwiftCheck #if SWIFT_PACKAGE import Operadics import Swiftx #endif class ArrayExtSpec : XCTestCase { func testProperties() { property("mapFlatten is the same as removing the optionals from an array and forcing") <- forAll { (xs0 : Array<Int?>) in return mapFlatten(xs0) == xs0.filter({ $0 != nil }).map({ $0! }) } property("indexArray is safe") <- forAll { (l : [Int]) in if l.isEmpty { return l.safeIndex(0) == nil } return l.safeIndex(0) != nil } property("Array fmap is the same as map") <- forAll { (xs : [Int]) in return ({ $0 + 1 } <^> xs) == xs.map({ $0 + 1 }) } property("Array pure give a singleton array") <- forAll { (x : Int) in return Array.pure(x) == [x] } property("Array bind works like a map then a concat") <- forAll { (xs : [Int]) in func fs(_ x : Int) -> [Int] { return [x, x+1, x+2] } return (xs >>- fs) == xs.map(fs).reduce([], +) } property("Array obeys the Functor identity law") <- forAll { (x : [Int]) in return (x.map(identity)) == identity(x) } property("Array obeys the Functor composition law") <- forAll { (_ f : ArrowOf<Int, Int>, g : ArrowOf<Int, Int>) in return forAll { (x : [Int]) in return ((f.getArrow • g.getArrow) <^> x) == (x.map(g.getArrow).map(f.getArrow)) } } property("Array obeys the Applicative identity law") <- forAll { (x : [Int]) in return (Array.pure(identity) <*> x) == x } property("Array obeys the Applicative homomorphism law") <- forAll { (_ f : ArrowOf<Int, Int>, x : Int) in return (Array.pure(f.getArrow) <*> Array.pure(x)) == Array.pure(f.getArrow(x)) } property("Array obeys the Applicative interchange law") <- forAll { (fu : Array<ArrowOf<Int, Int>>) in return forAll { (y : Int) in let u = fu.fmap { $0.getArrow } return (u <*> Array.pure(y)) == (Array.pure({ f in f(y) }) <*> u) } } property("Array obeys the first Applicative composition law") <- forAll { (fl : Array<ArrowOf<Int8, Int8>>, gl : Array<ArrowOf<Int8, Int8>>, x : Array<Int8>) in let f = fl.map({ $0.getArrow }) let g = gl.map({ $0.getArrow }) return (curry(•) <^> f <*> g <*> x) == (f <*> (g <*> x)) } property("Array obeys the second Applicative composition law") <- forAll { (fl : Array<ArrowOf<Int8, Int8>>, gl : Array<ArrowOf<Int8, Int8>>, x : Array<Int8>) in let f = fl.map({ $0.getArrow }) let g = gl.map({ $0.getArrow }) let lhs = Array.pure(curry(•)) <*> f <*> g <*> x let rhs = f <*> (g <*> x) return (lhs == rhs) // broken up as 'too complex' for compiler } property("Array obeys the Monad left identity law") <- forAll { (a : Int, fa : ArrowOf<Int, [Int]>) in let f = fa.getArrow return (Array.pure(a) >>- f) == f(a) } property("Array obeys the Monad right identity law") <- forAll { (m : [Int]) in return (m >>- Array.pure) == m } property("Array obeys the Monad associativity law") <- forAll { (fa : ArrowOf<Int, [Int]>, ga : ArrowOf<Int, [Int]>) in let f = fa.getArrow let g = ga.getArrow return forAll { (m : [Int]) in return ((m >>- f) >>- g) == (m >>- { x in f(x) >>- g }) } } property("Array obeys the Monoidal left identity law") <- forAll { (x : Array<Int8>) in return (x <> []) == x } property("Array obeys the Monoidal right identity law") <- forAll { (x : Array<Int8>) in return ([] <> x) == x } property("scanl behaves") <- forAll { (withArray : [Int]) in let scanned = withArray.scanl(0, +) if withArray.isEmpty { return scanned == [0] } return scanned == [0] + [Int](withArray[1..<withArray.count]).scanl(0 + withArray.first!, +) } property("intersperse behaves") <- forAll { (withArray : [Int]) in let inter = withArray.intersperse(1) if withArray.isEmpty { return inter.isEmpty } return TestResult.succeeded // TODO: Test non-empty case } property("span behaves") <- forAll { (xs : [Int]) in return forAll { (pred : ArrowOf<Int, Bool>) in let p = xs.span(pred.getArrow) let t = (xs.takeWhile(pred.getArrow), xs.dropWhile(pred.getArrow)) return p.0 == t.0 && p.1 == t.1 } } property("extreme behaves") <- forAll { (xs : [Int]) in return forAll { (pred : ArrowOf<Int, Bool>) in let p = xs.extreme(pred.getArrow) let t = xs.span((!) • pred.getArrow) return p.0 == t.0 && p.1 == t.1 } } property("intercalate behaves") <- forAll { (xs : [Int], xxs : Array<[Int]>) in return intercalate(xs, nested: xxs) == concat(xxs.intersperse(xs)) } /* property("group for Equatable things is the same as groupBy(==)") <- forAll { (xs : [Int]) in return xs.group == xs.groupBy { $0 == $1 } } */ property("isPrefixOf behaves") <- forAll { (s1 : [Int], s2 : [Int]) in if s1.isPrefixOf(s2) { return s1.stripPrefix(s2) != nil } if s2.isPrefixOf(s1) { return s2.stripPrefix(s1) != nil } return Discard() } property("isSuffixOf behaves") <- forAll { (s1 : [Int], s2 : [Int]) in if s1.isSuffixOf(s2) { return s1.stripSuffix(s2) != nil } if s2.isSuffixOf(s1) { return s2.stripSuffix(s1) != nil } return Discard() } property("sequence occurs in order") <- forAll { (xs : [Int]) in let seq = sequence(xs.map(Array.pure)) return forAllNoShrink(Gen.pure(seq)) { ss in return (ss.first ?? []) == xs } } } #if !(os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) static var allTests = testCase([ ("testProperties", testProperties) ]) #endif }
bsd-3-clause
f202c756b706b8aa4c0181bc4a58e875
28.910526
163
0.587542
2.997363
false
false
false
false