repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
fluidpixel/SquashTracker
SquashTracker/SwiftCharts/Layers/ChartPointsBubbleLayer.swift
1
1817
// // ChartPointsBubbleLayer.swift // Examples // // Created by ischuetz on 16/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public class ChartPointsBubbleLayer<T: ChartPointBubble>: ChartPointsLayer<T> { private let diameterFactor: CGFloat public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], displayDelay: Float = 0, maxBubbleDiameter: CGFloat = 30, minBubbleDiameter: CGFloat = 2) { let (minDiameterScalar, maxDiameterScalar): (CGFloat, CGFloat) = chartPoints.reduce((min: CGFloat(0), max: CGFloat(0))) {tuple, chartPoint in (min: min(tuple.min, chartPoint.diameterScalar), max: max(tuple.max, chartPoint.diameterScalar)) } self.diameterFactor = (maxBubbleDiameter - minBubbleDiameter) / (maxDiameterScalar - minDiameterScalar) super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, displayDelay: displayDelay) } override public func chartViewDrawing(context context: CGContextRef, chart: Chart) { for chartPointModel in self.chartPointsModels { CGContextSetLineWidth(context, 1.0) CGContextSetStrokeColorWithColor(context, chartPointModel.chartPoint.borderColor.CGColor) CGContextSetFillColorWithColor(context, chartPointModel.chartPoint.bgColor.CGColor) let diameter = chartPointModel.chartPoint.diameterScalar * diameterFactor let circleRect = (CGRectMake(chartPointModel.screenLoc.x - diameter / 2, chartPointModel.screenLoc.y - diameter / 2, diameter, diameter)) CGContextFillEllipseInRect(context, circleRect) CGContextStrokeEllipseInRect(context, circleRect) } } }
gpl-2.0
915ef9fbe4b64ef68fcd4a29957461b6
43.317073
191
0.703357
4.910811
false
false
false
false
victors1681/CustomAlertView
CustomAlertView/CustomAlertView.swift
1
4070
// // CustomAlertView.swift // JustOrders // // Created by Victor Santos on 4/4/16. // Copyright © 2016 Victor Santos. All rights reserved. // // import UIKit //AlertView Options public enum AlertViewType { case information case error case caution case question } public protocol CustomAlertViewDelegate: class { func alertBack(controller:CustomAlertView, acction:Bool, tag:Int) } public class CustomAlertView: UIView { var alertViewType:AlertViewType = AlertViewType.information var alertTitle:String = "" var alertMesage:String = "" weak var delegate:CustomAlertViewDelegate? internal var innerTag: Int = 0 @IBOutlet weak var titleLabel: UITextField! @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var cancelButton: UIButton! @IBOutlet weak var aceptarButtonRight: UIButton! @IBOutlet weak var aceptarButtonCenter: UIButton! @IBOutlet weak var topAlertTitle: UIView! @IBAction func closeView(sender: AnyObject) { hideCustomeAlert() } @IBAction func doneButton(sender: AnyObject) { delegate?.alertBack(self, acction: true, tag:innerTag ) //Whether information / error / caution just show OK button hideCustomeAlert() } override public func awakeFromNib() { } class func designCodeAlertView()-> CustomAlertView { return NSBundle(forClass: self).loadNibNamed("CustomAlertView", owner: self, options: nil)[0] as! CustomAlertView } } public extension UIView { struct CustomAlertViewConstants { static let Tag = 1000 } public func showCustomeAlert(alertViewType:AlertViewType? = .information, delegate:CustomAlertViewDelegate? = nil, title:String, message:String, tag:Int? = 0) { let customAlertXibView = CustomAlertView.designCodeAlertView() customAlertXibView.frame = self.bounds customAlertXibView.tag = CustomAlertViewConstants.Tag customAlertXibView.titleLabel.text = title customAlertXibView.messageLabel.text = message customAlertXibView.alertViewType = alertViewType! customAlertXibView.delegate = delegate customAlertXibView.innerTag = tag! selectTop(alertViewType!, customAlertXibView: customAlertXibView) self.addSubview(customAlertXibView) customAlertXibView.alpha = 0 //Show Custom Alert View Animate customAlertXibView.fadeIn(duration: 0.5) } internal func selectTop(alertViewType:AlertViewType,customAlertXibView:CustomAlertView) { switch alertViewType { case AlertViewType.question : customAlertXibView.aceptarButtonCenter.hidden = true break case AlertViewType.caution: customAlertXibView.topAlertTitle.backgroundColor = UIColor(red:0.941, green:0.889, blue:0.3, alpha:1) customAlertXibView.cancelButton.hidden = true customAlertXibView.aceptarButtonRight.hidden = true break case AlertViewType.error: customAlertXibView.topAlertTitle.backgroundColor = UIColor(red:0.948, green:0.439, blue:0.439, alpha:1) customAlertXibView.cancelButton.hidden = true customAlertXibView.aceptarButtonRight.hidden = true break default: customAlertXibView.cancelButton.hidden = true customAlertXibView.aceptarButtonRight.hidden = true } } public func hideCustomeAlert() { if let customAlertXibView = self.viewWithTag(CustomAlertViewConstants.Tag) { customAlertXibView.alpha = 1 customAlertXibView.fadeOutCompletion(duration: 0.5, completion: { (finished) in customAlertXibView.removeFromSuperview() }) } } }
gpl-3.0
7d9b86fc973a4172bc9f9c05f58f4f53
27.454545
164
0.645122
4.89651
false
false
false
false
yeziahehe/Gank
Pods/SKPhotoBrowser/SKPhotoBrowser/SKButtons.swift
2
4137
// // SKButtons.swift // SKPhotoBrowser // // Created by 鈴木 啓司 on 2016/08/09. // Copyright © 2016年 suzuki_keishi. All rights reserved. // import Foundation // helpers which often used private let bundle = Bundle(for: SKPhotoBrowser.self) class SKButton: UIButton { internal var showFrame: CGRect! internal var hideFrame: CGRect! fileprivate var insets: UIEdgeInsets { if UI_USER_INTERFACE_IDIOM() == .phone { return UIEdgeInsets(top: 15.25, left: 15.25, bottom: 15.25, right: 15.25) } else { return UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12) } } fileprivate let size: CGSize = CGSize(width: 44, height: 44) fileprivate var marginX: CGFloat = 0 fileprivate var marginY: CGFloat = 0 fileprivate var extraMarginY: CGFloat = SKMesurement.isPhoneX ? 10 : 0 func setup(_ imageName: String) { backgroundColor = .clear imageEdgeInsets = insets translatesAutoresizingMaskIntoConstraints = true autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin] let image = UIImage(named: "SKPhotoBrowser.bundle/images/\(imageName)", in: bundle, compatibleWith: nil) ?? UIImage() setImage(image, for: .normal) } func setFrameSize(_ size: CGSize? = nil) { guard let size = size else { return } let newRect = CGRect(x: marginX, y: marginY, width: size.width, height: size.height) frame = newRect showFrame = newRect hideFrame = CGRect(x: marginX, y: -marginY, width: size.width, height: size.height) } func updateFrame(_ frameSize: CGSize) { } } class SKImageButton: SKButton { fileprivate var imageName: String { return "" } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) setup(imageName) showFrame = CGRect(x: marginX, y: marginY, width: size.width, height: size.height) hideFrame = CGRect(x: marginX, y: -marginY, width: size.width, height: size.height) } } class SKCloseButton: SKImageButton { override var imageName: String { return "btn_common_close_wh" } override var marginX: CGFloat { get { return SKPhotoBrowserOptions.swapCloseAndDeleteButtons ? SKMesurement.screenWidth - SKButtonOptions.closeButtonPadding.x - self.size.width : SKButtonOptions.closeButtonPadding.x } set { super.marginX = newValue } } override var marginY: CGFloat { get { return SKButtonOptions.closeButtonPadding.y + extraMarginY } set { super.marginY = newValue } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) setup(imageName) showFrame = CGRect(x: marginX, y: marginY, width: size.width, height: size.height) hideFrame = CGRect(x: marginX, y: -marginY, width: size.width, height: size.height) } } class SKDeleteButton: SKImageButton { override var imageName: String { return "btn_common_delete_wh" } override var marginX: CGFloat { get { return SKPhotoBrowserOptions.swapCloseAndDeleteButtons ? SKButtonOptions.deleteButtonPadding.x : SKMesurement.screenWidth - SKButtonOptions.deleteButtonPadding.x - self.size.width } set { super.marginX = newValue } } override var marginY: CGFloat { get { return SKButtonOptions.deleteButtonPadding.y + extraMarginY } set { super.marginY = newValue } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) setup(imageName) showFrame = CGRect(x: marginX, y: marginY, width: size.width, height: size.height) hideFrame = CGRect(x: marginX, y: -marginY, width: size.width, height: size.height) } }
gpl-3.0
bd42435fe551c6121e21e14aa886d9f8
33.672269
125
0.642269
4.244856
false
false
false
false
ethanneff/organize
Organize/Reminder.swift
1
5353
import UIKit class Reminder: NSObject, NSCoding { // MARK: - PROPERTIES var id: String var uid: String var type: ReminderType var date: NSDate var created: NSDate var updated: NSDate override var description: String { return "\(uid) \(type) \(date)" } // MARK: - INIT init(uid: String, type: ReminderType, date: NSDate) { self.id = NSUUID().UUIDString self.uid = uid self.type = type self.date = date self.created = NSDate() self.updated = NSDate() } convenience init(id: String, uid: String, type: ReminderType, date: NSDate, created: NSDate, updated: NSDate) { self.init(uid: uid, type: type, date: date) self.id = id self.created = created self.updated = updated } convenience init(type: ReminderType, date: NSDate?) { let uid = NSUUID().UUIDString let date = type.date(date: date) self.init(uid: uid, type: type, date: date) } // MARK: - DEINIT deinit { LocalNotification.sharedInstance.delete(uid: uid) } // MARK: - SAVE struct PropertyKey { static let id: String = "id" static let uid: String = "uid" static let type: String = "type" static let date: String = "date" static let created: String = "created" static let updated: String = "updated" } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(id, forKey: PropertyKey.id) aCoder.encodeObject(uid, forKey: PropertyKey.uid) aCoder.encodeObject(type.rawValue, forKey: PropertyKey.type) aCoder.encodeObject(date, forKey: PropertyKey.date) aCoder.encodeObject(created, forKey: PropertyKey.created) aCoder.encodeObject(updated, forKey: PropertyKey.updated) } required convenience init?(coder aDecoder: NSCoder) { let id = aDecoder.decodeObjectForKey(PropertyKey.id) as! String let uid = aDecoder.decodeObjectForKey(PropertyKey.uid) as! String let type = ReminderType(rawValue: aDecoder.decodeObjectForKey(PropertyKey.type) as! Int)! let date = aDecoder.decodeObjectForKey(PropertyKey.date) as! NSDate let created = aDecoder.decodeObjectForKey(PropertyKey.created) as! NSDate let updated = aDecoder.decodeObjectForKey(PropertyKey.updated) as! NSDate self.init(id: id, uid: uid, type: type, date: date, created: created, updated: updated) } } enum ReminderType: Int { case None case Later case Evening case Tomorrow case Weekend case Week case Month case Someday case Date var title: String { switch self { case .Later: return "Later Today" case .Evening: return "This Evening" case .Tomorrow: return "Tomorrow" case .Weekend: return "This Weekend" case .Week: return "Next Week" case .Month: return "In a Month" case .Someday: return "Someday" case .None: return "Cancel" case .Date: return "Pick Date" } } var image: UIImage { switch self { case .Later: return UIImage(named: "icon-clock")! case .Evening: return UIImage(named: "icon-moon")! case .Tomorrow: return UIImage(named: "icon-cup")! case .Weekend: return UIImage(named: "icon-weather-sun")! case .Week: return UIImage(named: "icon-cabinet-files")! case .Month: return UIImage(named: "icon-calendar")! case .Someday: return UIImage(named: "icon-weather-rain")! case .None: return UIImage(named: "icon-close-small")! case .Date: return UIImage(named: "icon-list")! } } func imageView(color color: UIColor) -> UIImageView { return Util.imageViewWithColor(image: self.image, color: color) } func date(date date: NSDate?) -> NSDate { // configurable hours let paramLater: Double = 2 let paramMorning: Double = 24 + 8 let paramEvening: Double = 12 + 6 // -1 day because working off tomorrow morning's value let paramWeek: Double = 6 let paramMonth: Double = 29 let paramSomeday: Double = 59 let now: NSDate = NSDate() let today: NSDate = NSCalendar.currentCalendar().startOfDayForDate(NSDate()) let dayOfWeek: Double = Double(NSCalendar.currentCalendar().components(.Weekday, fromDate: today).weekday) // 2 hours let later = now.dateByAddingTimeInterval(60*60*(paramLater)) // at 6pm or 2 hours from now if already after 6pm let evening = now.compare(today.dateByAddingTimeInterval(60*60*(paramEvening))) == .OrderedDescending ? later : today.dateByAddingTimeInterval(60*60*(paramEvening)) // 8am tomorrow let tomorrow = today.dateByAddingTimeInterval(60*60*(paramMorning)) // saturday at 8am or 2hours if already on weekend let weekend = (dayOfWeek == 7 || dayOfWeek == 1) ? later : tomorrow.dateByAddingTimeInterval(60*60*24*(6-dayOfWeek)) // 7 days from now or monday if weekend let week = tomorrow.dateByAddingTimeInterval(60*60*24*(paramWeek)) // 30 days let month = tomorrow.dateByAddingTimeInterval(60*60*24*(paramMonth)) // 60 days let someday = tomorrow.dateByAddingTimeInterval(60*60*24*(paramSomeday)) switch self { case .Later: return later case .Evening: return evening case .Tomorrow: return tomorrow case .Weekend: return weekend case .Week: return week case .Month: return month case .Someday: return someday case .None: return now case .Date: return date ?? now } } }
mit
d6523d8e2f1adf1ff751cc8fb5813190
31.253012
168
0.676817
3.991797
false
false
false
false
tony-dinh/today
today/today WatchKit Extension/EventList.swift
1
1259
// // EventList.swift // day // // Created by Tony Dinh on 2016-11-04. // Copyright © 2016 Tony Dinh. All rights reserved. // import Foundation import EventKit final class EventList { let eventManager = EventManager.sharedInstance var events: [EKEvent]? { return eventManager.events } init() { if eventManager.accessGranted { eventManager.getTodaysEvents() } else { eventManager.requestAccess() { granted, error in if granted { self.eventManager.getTodaysEvents() } } } } func reloadEvents(completion: ((Bool) -> Void)? = nil) { guard eventManager.accessGranted == true else { completion?(false) return } eventManager.getTodaysEvents() completion?(true) } func eventsEndingBefore(date: Date) -> [EKEvent] { guard let events = events else { return [EKEvent]() } return events.filter({$0.endDate <= date}) } func eventsEndingAfter(date: Date) -> [EKEvent] { guard let events = events else { return [EKEvent]() } return events.filter({$0.endDate > date}) } }
mit
19f0e5ca02ea5c2a6d579ec5bc0da41a
23.192308
60
0.554054
4.460993
false
false
false
false
queueit/QueueIT.iOS.Sdk
QueueItSDK/QueueService.swift
1
9885
import Foundation typealias QueueServiceSuccess = (_ data: Data) -> Void typealias QueueServiceFailure = (_ errorMessage: String, _ errorStatusCode: Int) -> Void class QueueService { static let sharedInstance = QueueService() let httpProtocol = "https://" let hostName = "queue-it.net" var customerId = "" func getHostName() -> String { return "\(httpProtocol)\(customerId).\(hostName)" } func enqueue(_ customerId:String, _ eventId:String, _ configId:String, layoutName:String?, language:String?, success:@escaping (_ status: EnqueueDTO) -> Void, failure:@escaping QueueServiceFailure) { self.customerId = customerId let userId = iOSUtils.getUserId() let userAgent = iOSUtils.getSystemInfo() let sdkVersion = iOSUtils.getSDKVersion() var body: [String : String] = ["userId" : userId, "userAgent" : userAgent, "sdkVersion" : sdkVersion, "configurationId" : configId] if layoutName != nil { body["layoutName"] = layoutName } if language != nil { body["language"] = language } let enqueueUrl = "\(getHostName())/api/nativeapp/\(customerId)/\(eventId)/queue/enqueue" self.submitPOSTPath(enqueueUrl, bodyDict: body as NSDictionary, success: { (data) -> Void in let dictData = self.dataToDict(data) let queueIdDto = self.extractQueueIdDetails(dictData!) let eventDetails = self.extractEventDetails(dictData!) let redirectDto = self.extractRedirectDetails(dictData!) success(EnqueueDTO(queueIdDto, eventDetails!, redirectDto)) }) { (errorMessage, errorStatusCode) -> Void in failure(errorMessage, errorStatusCode) } } func getStatus(_ customerId:String, _ eventId:String, _ queueId:String, _ configId:String, _ widgets:[WidgetRequest], onGetStatus:@escaping (_ status: StatusDTO) -> Void, onFailed:@escaping(_ errorMessage: String) -> Void) { self.customerId = customerId var body: [String : Any] = ["configurationId" : configId] var widgetArr = [Any]() var widgetItemDict = [String : Any]() for w in widgets { widgetItemDict["name"] = w.name widgetItemDict["version"] = w.version widgetArr.append(widgetItemDict) } body["widgets"] = widgetArr let statusUrl = "\(self.getHostName())/api/nativeapp/\(customerId)/\(eventId)/queue/\(queueId)/status" self.submitPUTPath(statusUrl, body: body as NSDictionary, success: { (data) -> Void in self.onGetStatusDataSuccess(data, onGetStatus) }) { (message, errorStatusCode) -> Void in onFailed(message) } } func onGetStatusDataSuccess(_ data: Data, _ onGetStatus:@escaping (_ status: StatusDTO) -> Void) { let dictData = self.dataToDict(data) let eventDetails = self.extractEventDetails(dictData!) let redirectDto = self.extractRedirectDetails(dictData!) let widgetsResult = self.extractWidgetDetails(dictData!) let rejectDto = self.extractRejectDetails(dictData!) let nextCallMSec = dictData!.value(forKey: "ttl") as? Int let statusDto = StatusDTO(eventDetails, redirectDto, widgetsResult, nextCallMSec!, rejectDto) onGetStatus(statusDto) } func submitPOSTPath(_ path: String, bodyDict: NSDictionary, success: @escaping QueueServiceSuccess, failure: @escaping QueueServiceFailure) { submitRequestWithURL(path, httpMethod: "POST", bodyDict: bodyDict, expectedStatus: 200, success: success, failure: failure) } func submitPUTPath(_ path: String, body: NSDictionary, success: @escaping QueueServiceSuccess, failure: @escaping QueueServiceFailure) { submitRequestWithURL(path, httpMethod: "PUT", bodyDict: body, expectedStatus: 200, success: success, failure: failure) } func submitRequestWithURL(_ path: String, httpMethod: String, bodyDict: NSDictionary, expectedStatus: Int, success: @escaping QueueServiceSuccess, failure: @escaping QueueServiceFailure) { let url = URL(string: path)! let request = NSMutableURLRequest(url: url) request.httpMethod = httpMethod request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("application/json", forHTTPHeaderField: "Content-Type") do { request.httpBody = try JSONSerialization.data(withJSONObject: bodyDict, options: .prettyPrinted) _ = QueueService_NSURLConnectionRequest(request: request as URLRequest, expectedStatusCode: expectedStatus, successCallback: success, failureCallback: failure) } catch { failure("Could not unwrap body for the request", -1) } } func parseRedirectType(_ redirectType: String) throws -> PassedType { var passedType: PassedType if redirectType == "Safetynet" { passedType = .safetyNet } else if redirectType == "Disabled" { passedType = .disabled } else if redirectType == "DirectLink" { passedType = .directLink } else if redirectType == "AfterEvent" { passedType = .afterEvent } else if redirectType == "Queue" { passedType = .queue } else { throw PassedTypeError.invalidPassedType } return passedType } func parseEventState(_ state: String) throws -> EventState { var eventState: EventState if state == "PreQueue" { eventState = .prequeue } else if state == "Queue" { eventState = .queue } else if state == "Idle" { eventState = .idle } else if state == "PostQueue" { eventState = .postqueue } else { throw EventStateError.invalidEventState } return eventState } func dataToDict(_ data: Data) -> NSDictionary? { return try! JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary } func extractQueueIdDetails(_ dataDict: NSDictionary) -> QueueIdDTO? { var queueIdDto: QueueIdDTO? = nil let qIdDict = dataDict.value(forKey: "queueIdDetails") as? NSDictionary if qIdDict != nil { let qId = qIdDict?["queueId"] as! String let ttl = Int(qIdDict?["ttl"] as! CLongLong) queueIdDto = QueueIdDTO(qId, ttl) } return queueIdDto } func extractEventDetails(_ dataDict: NSDictionary) -> EventDTO? { var eventDetails: EventDTO? = nil let eventDetailsDict = dataDict.value(forKey: "eventDetails") as? NSDictionary if eventDetailsDict != nil { let stateString = eventDetailsDict?["state"] as! String let state: EventState = try! self.parseEventState(stateString) eventDetails = EventDTO(state) } return eventDetails } func extractRejectDetails(_ dataDict: NSDictionary) -> RejectDTO? { var rejectDetails: RejectDTO? = nil let rejectDetailsDict = dataDict.value(forKey: "rejectDetails") as? NSDictionary if rejectDetailsDict != nil { let reason = rejectDetailsDict?["reason"] as! String rejectDetails = RejectDTO(reason) } return rejectDetails } func extractRedirectDetails(_ dataDict: NSDictionary) -> RedirectDTO? { var redirectDto: RedirectDTO? = nil let redirectDetailsDict = dataDict.value(forKey: "redirectDetails") as? NSDictionary if redirectDetailsDict != nil { let redirectType = redirectDetailsDict?["redirectType"] as! String let ttl = Int(redirectDetailsDict?["ttl"] as! CLongLong) let extendTtl = redirectDetailsDict?["extendTtl"] as! Bool let redirectId = redirectDetailsDict?["redirectId"] as! String let passedType = try! self.parseRedirectType(redirectType) redirectDto = RedirectDTO(passedType, ttl, extendTtl, redirectId) } return redirectDto } func extractWidgetDetails(_ dataDict: NSDictionary) -> [WidgetDTO]? { var widgetsResult = [WidgetDTO]() let widgetArr = dataDict.value(forKey: "widgets") as? NSArray for w in widgetArr! { var widgetText = String(describing: w) widgetText = widgetText.replacingOccurrences(of: "\n", with: "") widgetText = widgetText.replacingOccurrences(of: " ", with: "") widgetText = widgetText.replacingOccurrences(of: "{", with: "") widgetText = widgetText.replacingOccurrences(of: "}", with: "") var kvPairs = getAllKeyValues(widgetText) let name = kvPairs["type"] let checksum = kvPairs["checksum"] kvPairs.removeValue(forKey: "type") kvPairs.removeValue(forKey: "version") kvPairs.removeValue(forKey: "checksum") let widgetDto = WidgetDTO(name!, checksum!, kvPairs) widgetsResult.append(widgetDto) } return widgetsResult } func getAllKeyValues(_ text: String) -> [String:String] { var kvPairs = [String:String]() var key = ""; var cand = "" for c in text.characters { if c == "=" { key = cand cand = "" } else if c == ";" { kvPairs[key] = cand cand = "" } else { cand = cand + String(c) } } return kvPairs } }
lgpl-3.0
e8a9470b1de171a76433174061145a00
42.933333
228
0.606474
4.640845
false
false
false
false
Zewo/TodoBackend
Sources/TodoBackend/main.swift
1
887
import HTTPServer import POSIX // Configuration let apiRoot = environment["API_ROOT"] ?? "http://localhost:8080/" let usePq = environment["USE_POSTGRES"] == "true" let pqHost = environment["POSTGRES_HOST"] ?? "localhost" let pqPort = Int(environment["POSTGRES_PORT"] ?? "5432")! let pqUser = environment["POSTGRES_USER"] let pqPass = environment["POSTGRES_PASS"] // Middleware let cors = CORSMiddleware() let log = LogMiddleware() // Storage let store: TodoStore = usePq ? try PostgreSQLTodoStore(info: .init(host: pqHost, port: pqPort, databaseName: "todo-backend", username: pqUser, password: pqPass)) : InMemoryTodoStore() // Resources let todoResource = TodoResource(store: store, root: apiRoot) // Main router let router = BasicRouter(middleware: [log, cors]) { route in route.compose("/", resource: todoResource) } // Server try Server(responder: router).start()
mit
789bc64d3bf8503e64b6e57bbf6e6941
28.566667
136
0.719278
3.451362
false
false
false
false
Shashi717/ImmiGuide
ImmiGuide/ImmiGuide/ProgramsViewController.swift
1
14028
// // ProgramsViewController.swift // ImmiGuide // // Created by Cris on 2/18/17. // Copyright © 2017 Madushani Lekam Wasam Liyanage. All rights reserved. // import UIKit import SnapKit import Lottie private let cellID = "cellID" private let gedCellID = "GEDCell" private let segueID = "SegueToProgramDetails" class ProgramsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITabBarControllerDelegate { var language: String! var gedLocations = [GED]() var rwLocations = [ReadingWritingLiteracyPrograms]() var dict = [String : String]() var filteredAgeDict = [String : [ReadingWritingLiteracyPrograms]]() @IBOutlet weak var programsTableView: UITableView! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let userDefaults = UserDefaults.standard let appLanguage = userDefaults.object(forKey: TranslationLanguage.appLanguage.rawValue) if let language = appLanguage as? String, let languageDict = Translation.tabBarTranslation[language], let firstTab = languageDict["Education"] { self.navigationController?.tabBarItem.title = firstTab } } override func viewDidLoad() { super.viewDidLoad() programsTableView.delegate = self programsTableView.dataSource = self self.tabBarController?.delegate = self self.getGEDData() self.getReadingData() programsTableView.estimatedRowHeight = 125 programsTableView.rowHeight = UITableViewAutomaticDimension self.navigationController?.navigationBar.titleTextAttributes = ([NSForegroundColorAttributeName: UIColor.white]) self.navigationItem.titleView = UIImageView(image: UIImage(named: "School-52")) self.navigationController?.navigationBar.barTintColor = UIColor(red:1.00, green:0.36, blue:0.36, alpha:1.0) programsTableView.preservesSuperviewLayoutMargins = false programsTableView.separatorInset = UIEdgeInsets.init(top: 0, left: 15, bottom: 0, right: 15) programsTableView.layoutMargins = UIEdgeInsets.zero programsTableView.separatorColor = UIColor.darkGray setupViewHierarchy() configureConstraints() animateBookAndCircle() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) language = Translation.getLanguageFromDefauls() programsTableView.reloadData() animateCells() } func getGEDData() { let endpoint = APIRequestManager.gedAPIEndPoint APIRequestManager.manager.getData(endPoint: endpoint) { (data) in guard let validData = data else { return } do { let json = try JSONSerialization.jsonObject(with: validData, options: []) guard let jsonDict = json as? [[String : Any]] else { return } for object in jsonDict { guard let gedObject = GED(fromDict: object) else { return } self.gedLocations.append(gedObject) } DispatchQueue.main.async { self.programsTableView.reloadData() self.animateCells() } } catch { print(error) } } } func getReadingData() { let endpoint = APIRequestManager.literacyProgramsAPIEndPoint APIRequestManager.manager.getData(endPoint: endpoint) { (data) in guard let validData = data else { return } do { let json = try JSONSerialization.jsonObject(with: validData, options: []) guard let jsonDict = json as? [[String : Any]] else { return } for object in jsonDict { guard let rwObject = ReadingWritingLiteracyPrograms(fromDict: object) else { return } self.rwLocations.append(rwObject) } DispatchQueue.main.async { self.getCategoriesAndRefresh() self.sortRWBy() self.animateCells() } } catch { print(error) } } } func getCategoriesAndRefresh() { for loc in rwLocations { let program = loc.program let age = loc.ageGroup dict[program] = age } } func sortRWBy() { let categories = dict.keys.sorted() for cat in categories { let filteredByAgeArr = rwLocations.filter{$0.program == cat} filteredAgeDict[cat] = filteredByAgeArr } self.programsTableView.reloadData() } func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 1 case 1: return dict.keys.count default: break } return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = UITableViewCell() switch indexPath.section { case 0: cell = programsTableView.dequeueReusableCell(withIdentifier: gedCellID, for: indexPath) if let cell = cell as? GEDTableViewCell { guard let languageDict = Translation.programVC[language] as? [String : String], let labelText = languageDict["GED"] else { return cell } cell.gedLabel.text = ("\(labelText)/ College Prep") cell.gedLabel.font = UIFont(name: "Montserrat-Light", size: 25) cell.gedLabel?.textColor = UIColor.darkGray } case 1: let cat = dict.keys.sorted() let category = cat[indexPath.row] cell = programsTableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) if let cell = cell as? ProgramTableViewCell { if let languageDict = Translation.programVC[language] as? [String : String], let labelTextName = languageDict[category] { cell.nameOfProgram.text = labelTextName cell.nameOfProgram.font = UIFont(name: "Montserrat-Light", size: 25) cell.nameOfProgram?.textColor = UIColor.darkGray DispatchQueue.main.async { if let age = self.dict[category] { if let ageText = languageDict[age] { cell.subtitleProgram.text = ageText cell.subtitleProgram.textColor = UIColor.darkGray cell.subtitleProgram.font = UIFont(name: "Montserrat-Light", size: 20) } } } } } default: break } return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let selected = sender as? ProgramTableViewCell, let indexPath = programsTableView.indexPath(for: selected), let dest = segue.destination as? SupportProgramListViewController { let cat = dict.keys.sorted() let category = cat[indexPath.row] guard let chosen = filteredAgeDict[category] else { return } dest.categoryChosen = chosen } else if let _ = sender as? GEDTableViewCell, let dest = segue.destination as? SupportProgramListViewController { dest.gedLocation = self.gedLocations } } // MARK: UITabBarController Delegate func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) { let tabBarIndex = tabBarController.selectedIndex switch tabBarIndex { case 0: language = Translation.getLanguageFromDefauls() if let tabBars = tabBarController.customizableViewControllers { for (index,item) in tabBars.enumerated() { if let languageDict = Translation.tabBarTranslation[language], let communityTabName = languageDict["Community"], let educationTabName = languageDict["Education"], let settingsTabName = languageDict["Settings"] { if index == 0 { item.tabBarItem.title = communityTabName } else if index == 1 { item.tabBarItem.title = educationTabName } else if index == 2 { item.tabBarItem.title = settingsTabName } } } } case 1: language = Translation.getLanguageFromDefauls() if let tabBars = tabBarController.customizableViewControllers { for (index,item) in tabBars.enumerated() { if let languageDict = Translation.tabBarTranslation[language], let communityTabName = languageDict["Community"], let educationTabName = languageDict["Education"], let settingsTabName = languageDict["Settings"] { if index == 0 { item.tabBarItem.title = communityTabName } else if index == 1 { item.tabBarItem.title = educationTabName } else if index == 2 { item.tabBarItem.title = settingsTabName } } } } case 2: language = Translation.getLanguageFromDefauls() if let tabBars = tabBarController.customizableViewControllers { for (index,item) in tabBars.enumerated() { if let languageDict = Translation.tabBarTranslation[language], let communityTabName = languageDict["Community"], let educationTabName = languageDict["Education"], let settingsTabName = languageDict["Settings"] { if index == 0 { item.tabBarItem.title = communityTabName } else if index == 1 { item.tabBarItem.title = educationTabName } else if index == 2 { item.tabBarItem.title = settingsTabName } } } } default: break } } // MARK: Animation func animateCells() { let allVisibleCells = self.programsTableView.visibleCells for (index, cell) in allVisibleCells.enumerated() { cell.transform = CGAffineTransform(translationX: 100.0, y: 0) cell.alpha = 0 UIView.animate(withDuration: 1.5, delay: 0.2 * Double(index), options: .curveEaseInOut, animations: { cell.alpha = 1.0 cell.transform = .identity }, completion: nil) } } func animateBookAndCircle() { circleAnimationView.play() bookAnimationView.play() } // MARK: Setup func setupViewHierarchy() { view.addSubview(circleAndBookView) view.addSubview(circleAnimationView) view.addSubview(bookAnimationView) } func configureConstraints() { self.edgesForExtendedLayout = [] circleAndBookView.snp.makeConstraints { (view) in view.top.leading.trailing.equalToSuperview() view.bottom.equalTo(programsTableView.snp.top) } circleAnimationView.snp.makeConstraints { (view) in view.centerX.equalTo(circleAndBookView.snp.centerX) view.centerY.equalTo(circleAndBookView.snp.centerY) view.height.width.equalTo(self.view.snp.height).multipliedBy(0.47) } bookAnimationView.snp.makeConstraints { (view) in view.height.equalTo(circleAnimationView.snp.height) view.width.equalTo(circleAnimationView.snp.width) view.centerX.equalTo(circleAnimationView.snp.centerX) view.centerY.equalTo(circleAnimationView.snp.centerY).multipliedBy(1.2) } } // MARK: Lazy Vars //Views internal lazy var circleAndBookView: UIView = { let view: UIView = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = .white return view }() //Animation views internal lazy var bookAnimationView: LAAnimationView = { var view: LAAnimationView = LAAnimationView() view = LAAnimationView.animationNamed("BluePenGrayBook") view.contentMode = .scaleAspectFill return view }() internal lazy var circleAnimationView: LAAnimationView = { var view: LAAnimationView = LAAnimationView() view = LAAnimationView.animationNamed("GrayCircle") view.contentMode = .scaleAspectFill return view }() }
mit
b1a8dfa1d166b1300a76847f9c9af892
40.255882
120
0.551009
5.606315
false
false
false
false
yoman07/SwiftBackgroundLocation
Example/SwiftBackgroundLocation/Extensions/MKMapView+Center.swift
1
463
import MapKit extension MKMapView { public func centerCamera(to location: CLLocation? = nil, distance: Double = 500, pitch: CGFloat = 0, heading: Double? = 0, animated: Bool = false) { let coordinate: CLLocationCoordinate2D = location?.coordinate ?? camera.centerCoordinate let c = MKMapCamera(lookingAtCenter: coordinate, fromDistance: distance, pitch: pitch, heading: heading ?? 0) setCamera(c, animated: animated) } }
mit
6ff638040f964d8551209835bc8adc3a
45.3
152
0.695464
4.539216
false
false
false
false
montionugera/yellow
yellow-ios/yellow/Model/FeedContent.swift
1
2590
// // PostContent.swift // yellow // // Created by montionugera on 8/23/17. // Copyright © 2017 23. All rights reserved. // import Foundation import FirebaseDatabase struct FeedContent { let key: String let postDesc: String let addedByUser: String let addedByUserName: String let addedByUserURL: String let emo: String let place: String let love: Int let ref: DatabaseReference? var mediaURL: String var mediaType: String var lochash: String var postDttmInt: Double var postDttmStr: String init(postDesc: String, addedByUser: String , addedByUserName: String , addedByUserURL: String, mediaURL: String, emo: String, love: Int, place: String, mediaType: String , lochash: String, postDttmInt: Double , postDttmStr: String, key: String = "") { self.key = key self.postDesc = postDesc self.addedByUser = addedByUser self.addedByUserName = addedByUserName self.addedByUserURL = addedByUserURL self.emo = emo self.love = love self.place = place self.mediaURL = mediaURL self.mediaType = mediaType self.lochash = lochash self.postDttmInt = postDttmInt self.postDttmStr = postDttmStr self.ref = nil } init(snapshot: DataSnapshot) { key = snapshot.key let snapshotValue = snapshot.value as! [String: AnyObject] postDesc = snapshotValue["postDesc"] as! String addedByUser = snapshotValue["addedByUser"] as! String if let addedByUserName_ = snapshotValue["addedByUserName"] { addedByUserName = addedByUserName_ as! String }else{ addedByUserName = "" } if let addedByUserURL_ = snapshotValue["addedByUserURL"] { addedByUserURL = addedByUserURL_ as! String }else{ addedByUserURL = "" } emo = snapshotValue["emo"] as! String love = snapshotValue["love"] as! Int place = snapshotValue["place"] as! String mediaURL = snapshotValue["mediaURL"] as! String mediaType = snapshotValue["mediaType"] as! String lochash = snapshotValue["lochash"] as! String postDttmInt = snapshotValue["postDttmInt"] as! Double postDttmStr = snapshotValue["postDttmStr"] as! String ref = snapshot.ref } func toAnyObject() -> Any { return [ "postDesc": postDesc, "addedByUser": addedByUser, "mediaType": mediaType, "mediaURL": mediaURL ] } }
mit
265552ab44424ec3a2567c20879f14d7
30.962963
255
0.622248
4.30782
false
false
false
false
jmgc/swift
test/Concurrency/Runtime/async_taskgroup_next_on_completed.swift
1
2221
// RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-concurrency) | %FileCheck %s --dump-input=always // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: OS=macosx // REQUIRES: CPU=x86_64 import Dispatch #if canImport(Darwin) import Darwin #elseif canImport(Glibc) import Glibc #endif func test_sum_nextOnCompleted() async { let numbers = [1, 2, 3, 4, 5] let expected = numbers.reduce(0, +) let sum = await try! Task.withGroup(resultType: Int.self) { (group) async -> Int in for n in numbers { await group.add { () async -> Int in print(" complete group.add { \(n) }") return n } } // We specifically want to await on completed child tasks in this test, // so give them some time to complete before we hit group.next() sleep(2) var sum = 0 do { while let r = await try group.next() { fputs("error: \(#function)[\(#file):\(#line)]: next: \(r)\n", stderr) print("next: \(r)") // DispatchQueue.main.sync { // TODO: remove once executors/actors are a thing sum += r // } print("sum: \(sum)") } } catch { print("ERROR: \(error)") } // assert(group.isEmpty, "Group must be empty after we consumed all tasks") fputs("error: \(#function)[\(#file):\(#line)]: group returning: \(sum)", stderr) print("task group returning: \(sum)") return sum } // The completions may arrive in any order, we make no strong guarantees about it: // CON: CHECK-DAG: complete group.add { [[N1:[0-9]+]] } // CON: CHECK-DAG: complete group.add { [[N2:[0-9]+]] } // CON: CHECK-DAG: complete group.add { [[N3:[0-9]+]] } // CON: CHECK-DAG: complete group.add { [[N4:[0-9]+]] } // CON: CHECK-DAG: complete group.add { [[N5:[0-9]+]] } // CON: CHECK-DAG: next: [[N1]] // CON: CHECK-DAG: next: [[N2]] // CON: CHECK-DAG: next: [[N3]] // CON: CHECK-DAG: next: [[N4]] // CON: CHECK-DAG: next: [[N5]] // CHECK: sum: 15 // // CHECK: task group returning: 15 // CHECK: result: 15 print("result: \(sum)") } runAsyncAndBlock(test_sum_nextOnCompleted)
apache-2.0
af66271011ad41ac6a4b6f19042d6b5d
29.847222
113
0.569563
3.497638
false
true
false
false
roecrew/AudioKit
Examples/iOS/MicrophoneAnalysis/MicrophoneAnalysis/ViewController.swift
2
2878
// // ViewController.swift // MicrophoneAnalysis // // Created by Kanstantsin Linou on 6/9/16. // Copyright © 2016 AudioKit. All rights reserved. // import UIKit import AudioKit class ViewController: UIViewController { @IBOutlet var frequencyLabel: UILabel! @IBOutlet var amplitudeLabel: UILabel! @IBOutlet var noteNameWithSharpsLabel: UILabel! @IBOutlet var noteNameWithFlatsLabel: UILabel! @IBOutlet var audioInputPlot: EZAudioPlot! var mic: AKMicrophone! var tracker: AKFrequencyTracker! var silence: AKBooster! let noteFrequencies = [16.35,17.32,18.35,19.45,20.6,21.83,23.12,24.5,25.96,27.5,29.14,30.87] let noteNamesWithSharps = ["C", "C♯","D","D♯","E","F","F♯","G","G♯","A","A♯","B"] let noteNamesWithFlats = ["C", "D♭","D","E♭","E","F","G♭","G","A♭","A","B♭","B"] func setupPlot() { let plot = AKNodeOutputPlot(mic, frame: audioInputPlot.bounds) plot.plotType = .Rolling plot.shouldFill = true plot.shouldMirror = true plot.color = UIColor.blueColor() audioInputPlot.addSubview(plot) } override func viewDidLoad() { super.viewDidLoad() AKSettings.audioInputEnabled = true mic = AKMicrophone() tracker = AKFrequencyTracker.init(mic) silence = AKBooster(tracker, gain: 0) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) AudioKit.output = silence AudioKit.start() setupPlot() NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(ViewController.updateUI), userInfo: nil, repeats: true) } func updateUI() { if tracker.amplitude > 0.1 { frequencyLabel.text = String(format: "%0.1f", tracker.frequency) var frequency = Float(tracker.frequency) while (frequency > Float(noteFrequencies[noteFrequencies.count-1])) { frequency = frequency / 2.0 } while (frequency < Float(noteFrequencies[0])) { frequency = frequency * 2.0 } var minDistance: Float = 10000.0 var index = 0 for i in 0..<noteFrequencies.count { let distance = fabsf(Float(noteFrequencies[i]) - frequency) if (distance < minDistance){ index = i minDistance = distance } } let octave = Int(log2f(Float(tracker.frequency) / frequency)) noteNameWithSharpsLabel.text = "\(noteNamesWithSharps[index])\(octave)" noteNameWithFlatsLabel.text = "\(noteNamesWithFlats[index])\(octave)" } amplitudeLabel.text = String(format: "%0.2f", tracker.amplitude) } }
mit
2bd667a3e8d867d9574cdce990a93f5e
33.011905
141
0.588379
4.232593
false
false
false
false
SparrowTek/LittleManComputer
LittleManComputer/Modules/AssemblyCode/AssemblyCodeEditor.swift
1
3633
// // AssemblyCodeEditor.swift // LittleManComputer // // Created by Thomas J. Rademaker on 3/29/20. // Copyright © 2020 SparrowTek LLC. All rights reserved. // import SwiftUI struct AssemblyCodeEditor: View { @Environment(\.horizontalSizeClass) var horizontalSizeClass @EnvironmentObject var appState: AppState let viewModel: AssemblyCodeEditorViewModel private var isIpadAndRegularWidth: Bool { appState.isIpad && horizontalSizeClass == .regular } var body: some View { VStack { if isIpadAndRegularWidth { Text("assemblyCodeEditorTitle") .padding(.top, 1) .font(.system(size: 20, weight: .bold)) } else { SheetTopBar() Spacer() HStack { Text("assemblyCodeEditorTitle") .padding([.leading], 32) .padding(.top, 16) .font(.system(size: 20, weight: .bold)) Spacer() } } // TextEditor(text: $appState.sourceCode) // .frame(maxWidth: .infinity, maxHeight: .infinity) // .padding([.leading, .trailing], 20) // .background(Color(Colors.textEditorBackground)) // .opacity(0.5) // .font(.system(size: 18)) // .foregroundColor(Color.green) // .keyboardType(.numberPad) // .autocapitalization(.allCharacters) // .disableAutocorrection(true) TextView(sourceCode: $appState.sourceCode) .frame(maxWidth: .infinity, maxHeight: .infinity) .background(Color(Colors.textEditorBackground)) .padding([.leading, .trailing], 20) LMCButton(title: "compileCodeButton", maxHeight: 50, maxWidth: .infinity, action: compile) .padding([.leading, .trailing]) } .alert(isPresented: $appState.showCompileError) { Alert(title: Text(appState.alertMessage)) } } private func compile() { viewModel.compileCode(appState.sourceCode) } } struct TextView: UIViewRepresentable { @Binding var sourceCode: String func makeUIView(context: Context) -> UITextView { let textView = UITextView() textView.isScrollEnabled = true textView.isEditable = true textView.isUserInteractionEnabled = true textView.textColor = UIColor(named: Colors.textEditorText) textView.backgroundColor = UIColor(named: Colors.textEditorBackground) textView.font = .systemFont(ofSize: 18) textView.autocorrectionType = .no textView.autocapitalizationType = .allCharacters textView.delegate = context.coordinator return textView } func updateUIView(_ uiView: UITextView, context: Context) { uiView.text = sourceCode } func makeCoordinator() -> TextView.Coordinator { Coordinator(self) } class Coordinator: NSObject, UITextViewDelegate { var control: TextView init(_ control: TextView) { self.control = control } func textViewDidChange(_ textView: UITextView) { control.sourceCode = textView.text } } } struct AssemblyCodeEditor_Previews: PreviewProvider { static var previews: some View { AssemblyCodeEditor(viewModel: AssemblyCodeEditorViewModel(appState: AppState())).environmentObject(AppState()) } }
mit
c4952ac0b2b0b8a27f470e5d94b16122
33.264151
118
0.582874
5.065551
false
false
false
false
fangandyuan/FYPlayer
Tools/FYConst.swift
1
825
// // PConst.swift // Play // // Created by 方圆 on 2017/3/8. // Copyright © 2017年 letus. All rights reserved. // import UIKit import RxSwift enum MovieDefinition { case height case general case low } public typealias Parameters = [String: Any] let FYRadius : CGFloat = 5; let FYSmallMarge : CGFloat = 10; let FYGeneralMarge : CGFloat = 15; let FYLargeMarge : CGFloat = 20; let FYNavHeight : CGFloat = 64; let FYTabBarHeight : CGFloat = 49; let FYScreenWidth: CGFloat = UIScreen.main.bounds.width let FYScreenHeight: CGFloat = UIScreen.main.bounds.height let FYScreenScale = UIScreen.main.scale let FYScreenWidthScale = UIScreen.main.bounds.width / 375.0 var disposeBag = DisposeBag() extension Disposable { public func disposed(by bag: DisposeBag) { bag.insert(self) } }
mit
5b5f012061b427b66c96ddd3b2972d78
18.95122
59
0.709046
3.541126
false
false
false
false
ingresse/ios-sdk
IngresseSDK/Model/DeclinedReason.swift
1
1103
// // Copyright © 2019 Ingresse. All rights reserved. // public class DeclinedReason: NSObject, Codable { @objc public var message: String? @objc public var declinedBy: String? @objc public var code: String? @objc public var createdAt: String? @objc public var checkDeclinedBy: String { switch declinedBy! { case "acquirer": return "Adquirente" case "antifraud": return "Antifraude" default: return declinedBy ?? "" } } enum CodingKeys: String, CodingKey { case message case declinedBy case createdAt case code } public required init(from decoder: Decoder) throws { guard let container = try? decoder.container(keyedBy: CodingKeys.self) else { return } message = container.decodeKey(.message, ofType: String.self) declinedBy = container.decodeKey(.declinedBy, ofType: String.self) createdAt = container.decodeKey(.createdAt, ofType: String.self) code = container.decodeKey(.code, ofType: String.self) } }
mit
6a3b2cd2c0873e669d51bd4e25fd28d7
29.611111
94
0.629764
4.461538
false
false
false
false
phimage/Phiole
Phiole.swift
1
7563
// // Phiole.swift // 2015 Eric Marchand (phimage) // /* The MIT License (MIT) Copyright (c) 2015 Eric Marchand (phimage) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation public class Phiole: NSObject { public static let LINE_DELIMITER = "\n" // MARK: singleton public class var std : Phiole { struct Static { static var onceToken : dispatch_once_t = 0 static var instance : Phiole? = nil } dispatch_once(&Static.onceToken) { let stdin = NSFileHandle.fileHandleWithStandardInput() let stdout = NSFileHandle.fileHandleWithStandardOutput() let stderr = NSFileHandle.fileHandleWithStandardError() Static.instance = Phiole(input:stdin, output: stdout, error: stderr) } return Static.instance! } // MARK: vars public var input: NSFileHandle public var output: NSFileHandle public var error: NSFileHandle // reader for input file handle private var reader: FileHandleReader? = nil // MARK: init public init(input: NSFileHandle, output: NSFileHandle, error: NSFileHandle) { self.input = input self.output = output self.error = error if input != NSFileHandle.fileHandleWithStandardInput() { self.reader = FileHandleReader(fileHandle: input, delimiter: Phiole.LINE_DELIMITER) } } // MARK: clone altered public func withOutput(output: NSFileHandle) -> Phiole { return Phiole(input: self.input, output: output, error: self.error) } public func withError(error: NSFileHandle) -> Phiole { return Phiole(input: self.input, output: self.output, error: error) } public func withInput(input: NSFileHandle) -> Phiole { return Phiole(input: input, output: self.output, error: self.error) } // MARK: functions public func newln() { Phiole.writeTo(output, Phiole.LINE_DELIMITER) } public func println() { newln() } public func println(object: AnyObject) { Phiole.writeTo(output, decorateOutput(object) + Phiole.LINE_DELIMITER) } public func print(object: AnyObject) { Phiole.writeTo(output, decorateOutput(object)) } public func readline() -> String? { if let r = reader { return r.readLine() } return Phiole.readFrom(self.input) } public func readlines(stopClosure: (String) -> Bool) { var line = readline() while line != nil { if stopClosure(line!) { return } line = readline() } } public func error(object: AnyObject) { Phiole.writeTo(error, decorateError(object)) } public func errorln(object: AnyObject) { Phiole.writeTo(error, decorateError(object) + Phiole.LINE_DELIMITER) } // MARK: class func public class func writeTo(handle: NSFileHandle, _ string: String) { if let data = string.dataUsingEncoding(NSUTF8StringEncoding) { handle.writeData(data) } } public class func readFrom(handle: NSFileHandle) -> String? { if let str = NSString(data: handle.availableData, encoding:NSUTF8StringEncoding) { return str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) as String } return nil } // MARK: optional decoration method, could be removed when copying to speed up code private func decorateOutput(object: AnyObject) -> String { return decorate("\(object)", withColor: self.valueForKey("outputColor")) } private func decorateError(object: AnyObject) -> String { return decorate("\(object)", withColor: self.valueForKey("errorColor")) } private func decorate(string: String, withColor color: AnyObject?) -> String { if let decorator = color as? StringDecorator, colorize = self.valueForKey("colorize") as? Bool where colorize { return decorator.decorate(string) } return string } public override func valueForUndefinedKey(key: String) -> AnyObject? { if key == "errorColor" || key == "outputColor" || key == "colorize" { return nil } return super.valueForUndefinedKey(key) } } protocol StringDecorator { func decorate(string: String) -> String } private class FileHandleReader { var fileHandle : NSFileHandle let encoding : UInt let chunkSize : Int let delimData : NSData! let buffer : NSMutableData! var atEof : Bool = false init?(fileHandle: NSFileHandle, delimiter: String, encoding : UInt = NSUTF8StringEncoding, chunkSize : Int = 4096) { self.fileHandle = fileHandle self.encoding = encoding self.chunkSize = chunkSize if let delimData = delimiter.dataUsingEncoding(encoding), buffer = NSMutableData(capacity: chunkSize) { self.delimData = delimData self.buffer = buffer } else { self.delimData = nil self.buffer = nil return nil } } // Return next line, or nil on EOF. func readLine() -> String? { if atEof { return nil } // Read data chunks from file until a line delimiter is found var range = buffer.rangeOfData(delimData, options: [], range: NSMakeRange(0, buffer.length)) while range.location == NSNotFound { let tmpData = fileHandle.readDataOfLength(chunkSize) if tmpData.length == 0 { // EOF or read error. atEof = true if buffer.length > 0 { // last line let line = NSString(data: buffer, encoding: encoding) buffer.length = 0 return line as String? } // No more lines return nil } buffer.appendData(tmpData) range = buffer.rangeOfData(delimData, options: [], range: NSMakeRange(0, buffer.length)) } let line = NSString(data: buffer.subdataWithRange(NSMakeRange(0, range.location)), encoding: encoding) buffer.replaceBytesInRange(NSMakeRange(0, range.location + range.length), withBytes: nil, length: 0) return line as String? } } typealias Φole = Phiole //typealias Console = Phiole
mit
5a9b53ec94a3a3967d61b0ea82571fcc
32.608889
120
0.629331
4.665022
false
false
false
false
Automattic/Automattic-Tracks-iOS
Sources/Encrypted Logs/EventLoggingUploadManager.swift
1
2563
import Foundation import Sodium class EventLoggingUploadManager { private let dataSource: EventLoggingDataSource private let delegate: EventLoggingDelegate private let networkService: EventLoggingNetworkService private let fileManager: FileManager typealias LogUploadCallback = (Result<Void, Error>) -> Void init(dataSource: EventLoggingDataSource, delegate: EventLoggingDelegate, networkService: EventLoggingNetworkService = EventLoggingNetworkService(), fileManager: FileManager = FileManager.default ) { self.dataSource = dataSource self.delegate = delegate self.networkService = networkService self.fileManager = fileManager } func upload(_ log: LogFile, then callback: @escaping LogUploadCallback) { guard delegate.shouldUploadLogFiles else { delegate.uploadCancelledByDelegate(log) callback(.failure(EventLoggingFileUploadError.cancelledByDelegate)) return } guard fileManager.fileExistsAtURL(log.url) else { let error = EventLoggingFileUploadError.fileMissing delegate.uploadFailed(withError: error, forLog: log) callback(.failure(error)) return } let request = createRequest( url: dataSource.logUploadURL, uuid: log.uuid, authenticationToken: dataSource.loggingAuthenticationToken ) delegate.didStartUploadingLog(log) networkService.uploadFile(request: request, fileURL: log.url) { result in switch result { case .success: callback(.success(())) /// fire after the callback so the hosting app can act on the result of the callback (such as removing the log from the queue) self.delegate.didFinishUploadingLog(log) case .failure(let error): callback(.failure(error)) /// fire after the callback so the hosting app can act on any state changes caused by the callback self.delegate.uploadFailed(withError: error, forLog: log) } } } func createRequest(url: URL, uuid: String, authenticationToken: String) -> URLRequest { var request = URLRequest(url: url) request.addValue(uuid, forHTTPHeaderField: "log-uuid") request.addValue(authenticationToken, forHTTPHeaderField: "Authorization") request.httpMethod = "POST" return request } }
gpl-2.0
9f7f51ace99bc2f5b74d68e22b5a27c7
36.691176
146
0.649629
5.523707
false
false
false
false
devxoul/Drrrible
Drrrible/Sources/Views/ShotViewReactionButtonView.swift
1
2578
// // ShotViewReactionButtonView.swift // Drrrible // // Created by Suyeol Jeon on 12/03/2017. // Copyright © 2017 Suyeol Jeon. All rights reserved. // import UIKit import ReactorKit import RxSwift final class ShotViewReactionButtonView: UIView, View { // MARK: Constants fileprivate struct Metric { static let buttonSize = 20.f static let labelLeft = 6.f } fileprivate struct Font { static let label = UIFont.systemFont(ofSize: 12) } // MARK: UI fileprivate let button = UIButton().then { $0.touchAreaInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20) } fileprivate let label = UILabel().then { $0.font = Font.label } // MARK: Properties var disposeBag = DisposeBag() // MARK: Initializing init(image: UIImage?, selectedImage: UIImage? = nil) { super.init(frame: .zero) self.button.setBackgroundImage(image, for: .normal) self.button.setBackgroundImage(selectedImage, for: .selected) self.addSubview(self.button) self.addSubview(self.label) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Configure func bind(reactor: ShotViewReactionButtonViewReactor) { // Action self.button.rx.tap .map { Reactor.Action.toggleReaction } .bind(to: reactor.action) .disposed(by: self.disposeBag) // State reactor.state.map { $0.isReacted } .filterNil() .distinctUntilChanged() .bind(to: self.button.rx.isSelected) .disposed(by: self.disposeBag) reactor.state.map { $0.canToggleReaction } .distinctUntilChanged() .bind(to: self.button.rx.isUserInteractionEnabled) .disposed(by: self.disposeBag) reactor.state.map { "\($0.count)" } .distinctUntilChanged() .bind(to: self.label.rx.text) .disposed(by: self.disposeBag) reactor.state.map { _ in } .bind(to: self.rx.setNeedsLayout) .disposed(by: self.disposeBag) } // MARK: Size override func sizeThatFits(_ size: CGSize) -> CGSize { self.setNeedsLayout() self.layoutIfNeeded() return CGSize(width: self.label.right, height: self.button.height) } class func height() -> CGFloat { return Metric.buttonSize } // MARK: Layout override func layoutSubviews() { super.layoutSubviews() self.button.width = Metric.buttonSize self.button.height = Metric.buttonSize self.label.sizeToFit() self.label.left = self.button.right + Metric.labelLeft self.label.centerY = self.button.centerY } }
mit
fe084b3eea0d56f344da0ecfc9aae9b6
21.215517
79
0.667831
3.886878
false
false
false
false
sora0077/QiitaKit
QiitaKit/src/Endpoint/ExpandedTemplate/CreateExpandedTemplate.swift
1
1716
// // CreateExpandedTemplate.swift // QiitaKit // // Created on 2015/06/08. // Copyright (c) 2015年 林達也. All rights reserved. // import Foundation import APIKit /** * 受け取ったテンプレート用文字列の変数を展開して返します。 */ public struct CreateExpandedTemplate { /// テンプレートの本文 /// example: Weekly MTG on %{Year}/%{month}/%{day} /// public let body: String /// タグ一覧 /// example: [{"name"=>"MTG/%{Year}/%{month}/%{day}", "versions"=>["0.0.1"]}] /// public let tags: Array<Tagging> /// 生成される投稿のタイトルの雛形 /// example: Weekly MTG on %{Year}/%{month}/%{day} /// public let title: String public init(body: String, tags: Array<Tagging>, title: String) { self.body = body self.tags = tags self.title = title } } extension CreateExpandedTemplate: QiitaRequestToken { public typealias Response = ExpandedTemplate public typealias SerializedObject = [String: AnyObject] public var method: HTTPMethod { return .POST } public var path: String { return "/api/v2/expanded_templates" } public var parameters: [String: AnyObject]? { return [ "body": body, "tags": tags.map({ ["name": $0.name, "versions": $0.versions] }), "title": title ] } public var encoding: RequestEncoding { return .JSON } } public extension CreateExpandedTemplate { func transform(request: NSURLRequest?, response: NSHTTPURLResponse?, object: SerializedObject) throws -> Response { return _ExpandedTemplate(object) } }
mit
5768751a422b8439840742dcd06587d3
21.8
119
0.601504
3.728972
false
false
false
false
ZNosX/SwiftHN
SwiftHN/ViewControllers/NewsViewController.swift
4
11395
// // NewsViewController.swift // SwiftHN // // Created by Thomas Ricouard on 05/06/14. // Copyright (c) 2014 Thomas Ricouard. All rights reserved. // import UIKit import SwiftHNShared import HackerSwifter class NewsViewController: HNTableViewController, NewsCellDelegate, CategoriesViewControllerDelegate { var filter: Post.PostFilter = .Top var loadMoreEnabled = false var infiniteScrollingView:UIView? override func viewDidLoad() { super.viewDidLoad() self.title = "HN:News" self.setupInfiniteScrollingView() self.setupNavigationItems() } private func setupInfiniteScrollingView() { self.infiniteScrollingView = UIView(frame: CGRectMake(0, self.tableView.contentSize.height, self.tableView.bounds.size.width, 60)) self.infiniteScrollingView!.autoresizingMask = UIViewAutoresizing.FlexibleWidth self.infiniteScrollingView!.backgroundColor = UIColor.LoadMoreLightGrayColor() var activityViewIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge) activityViewIndicator.color = UIColor.darkGrayColor() activityViewIndicator.frame = CGRectMake(self.infiniteScrollingView!.frame.size.width/2-activityViewIndicator.frame.width/2, self.infiniteScrollingView!.frame.size.height/2-activityViewIndicator.frame.height/2, activityViewIndicator.frame.width, activityViewIndicator.frame.height) activityViewIndicator.startAnimating() self.infiniteScrollingView!.addSubview(activityViewIndicator) } func onPullToFresh() { self.refreshing = true Post.fetch(self.filter, completion: {(posts: [Post]!, error: Fetcher.ResponseError!, local: Bool) in if let realDatasource = posts { self.datasource = realDatasource if (self.datasource.count % 30 == 0) { self.loadMoreEnabled = true } else { self.loadMoreEnabled = false } } if (!local) { self.refreshing = false } }) } func loadMore() { let fetchPage = Int(ceil(Double(self.datasource.count)/30))+1 Post.fetch(self.filter, page:fetchPage, completion: {(posts: [Post]!, error: Fetcher.ResponseError!, local: Bool) in if let realDatasource = posts { var tempDatasource:NSMutableArray = NSMutableArray(array: self.datasource) let postsNotFromNewPageCount = ((fetchPage-1)*30) if (tempDatasource.count - postsNotFromNewPageCount > 0) { tempDatasource.removeObjectsInRange(NSMakeRange(postsNotFromNewPageCount, tempDatasource.count-postsNotFromNewPageCount)) } tempDatasource.addObjectsFromArray(realDatasource) self.datasource = tempDatasource if (self.datasource.count % 30 == 0) { self.loadMoreEnabled = true } else { self.loadMoreEnabled = false } } if (!local) { self.refreshing = false self.tableView.tableFooterView = nil } }) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.onPullToFresh() self.showFirstTimeEditingCellAlert() } func setupNavigationItems() { var rightButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Organize, target: self, action: "onRightButton") self.navigationItem.rightBarButtonItem = rightButton } func onRightButton() { var navCategories = self.storyboard?.instantiateViewControllerWithIdentifier("categoriesNavigationController") as! UINavigationController var categoriesVC = navCategories.visibleViewController as! CategoriesViewController categoriesVC.delegate = self navCategories.modalPresentationStyle = UIModalPresentationStyle.Popover if (navCategories.popoverPresentationController != nil) { navCategories.popoverPresentationController?.sourceView = self.view navCategories.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem } self.presentViewController(navCategories, animated: true, completion: nil) } //MARK: Alert management func showFirstTimeEditingCellAlert() { if (!Preferences.sharedInstance.firstTimeLaunch) { var alert = UIAlertController(title: "Quick actions", message: "By swiping a cell you can quickly send post to the Safari Reading list, or use the more button to share it and access other functionalities", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Cancel, handler: {(action: UIAlertAction?) in Preferences.sharedInstance.firstTimeLaunch = true })) self.presentViewController(alert, animated: true, completion: nil) } } func showActionSheetForPost(post: Post) { var titles = ["Share", "Open", "Open in Safari", "Cancel"] var sheet = UIAlertController(title: post.title, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) var handler = {(action: UIAlertAction?) -> () in self.tableView.setEditing(false, animated: true) if let realAction = action { if (action!.title == titles[0]) { Helper.showShareSheet(post, controller: self, barbutton: nil) } else if (action!.title == titles[1]) { var webview = self.storyboard?.instantiateViewControllerWithIdentifier("WebviewController") as! WebviewController webview.post = post self.showDetailViewController(webview, sender: nil) } else if (action!.title == titles[2]) { UIApplication.sharedApplication().openURL(post.url!) } } } for title in titles { var type = UIAlertActionStyle.Default if (title == "Cancel") { type = UIAlertActionStyle.Cancel } sheet.addAction(UIAlertAction(title: title, style: type, handler: handler)) } self.presentViewController(sheet, animated: true, completion: nil) } //MARK: TableView Management override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView,numberOfRowsInSection section: Int) -> Int { if (self.datasource != nil) { return self.datasource.count } return 0 } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var title: NSString = (self.datasource[indexPath.row] as! Post).title! return NewsCell.heightForText(title, bounds: self.tableView.bounds) } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier(NewsCellsId) as? NewsCell cell!.post = self.datasource[indexPath.row] as! Post cell!.cellDelegate = self if (loadMoreEnabled && indexPath.row == self.datasource.count-3) { self.tableView.tableFooterView = self.infiniteScrollingView loadMore() } return cell! } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if (segue.identifier == "toWebview") { var destination = segue.destinationViewController as! WebviewController if let selectedRows = self.tableView.indexPathsForSelectedRows() { destination.post = self.datasource[selectedRows[0].row] as? Post } } } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { } override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject] { var readingList = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "Read\nLater", handler: {(action: UITableViewRowAction!, indexpath: NSIndexPath!) -> Void in if (Helper.addPostToReadingList(self.datasource[indexPath.row] as! Post)) { } var post = self.datasource Preferences.sharedInstance.addToReadLater(self.datasource[indexPath.row] as! Post) var cell = self.tableView.cellForRowAtIndexPath(indexPath) as! NewsCell cell.readLaterIndicator.hidden = false self.tableView.setEditing(false, animated: true) }) readingList.backgroundColor = UIColor.ReadingListColor() var more = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "More", handler: {(action: UITableViewRowAction!, indexpath: NSIndexPath!) -> Void in self.showActionSheetForPost(self.datasource[indexPath.row] as! Post) }) return [readingList, more] } //MARK: NewsCellDelegate func newsCellDidSelectButton(cell: NewsCell, actionType: Int, post: Post) { var indexPath = self.tableView.indexPathForCell(cell) if let realIndexPath = indexPath { let delay = 0.2 * Double(NSEC_PER_SEC) let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(time, dispatch_get_main_queue()) { () -> Void in self.tableView.selectRowAtIndexPath(realIndexPath, animated: false, scrollPosition: .None) } } if (actionType == NewsCellActionType.Comment.rawValue) { var detailVC = self.storyboard?.instantiateViewControllerWithIdentifier("DetailViewController") as! DetailViewController detailVC.post = post self.showDetailViewController(detailVC, sender: self) } else if (actionType == NewsCellActionType.Username.rawValue) { if let realUsername = post.username { var detailVC = self.storyboard?.instantiateViewControllerWithIdentifier("UserViewController") as! UserViewController detailVC.user = realUsername self.showDetailViewController(detailVC, sender: self) } } } //MARK: CategoriesDelegate func categoriesViewControllerDidSelecteFilter(controller: CategoriesViewController, filer: Post.PostFilter, title: String) { self.filter = filer self.datasource = nil self.onPullToFresh() self.title = title } func delayedSelection(indexpath: NSIndexPath) { } }
gpl-2.0
d7285bfb00780c6d0e37fb12b96e56fc
42.659004
289
0.64186
5.457375
false
false
false
false
chrisjmendez/swift-exercises
Menus/DualPanel/DualPanel/AppDelegate.swift
1
4738
// // AppDelegate.swift // DualPanel // // Created by Tommy Trojan on 12/19/15. // Copyright © 2015 Chris Mendez. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var drawerContainer:MMDrawerController? var userDefaults:NSUserDefaults? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. //If User is signed in, create a Main Navigation if(isSignedIn()){ initNavigationDrawer() } else { //Set the User ID to something userDefaults?.setValue("USER ID ADDED", forKey: "userID") //Kick off the process all over again initNavigationDrawer() } 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:. } } extension AppDelegate{ func isSignedIn() -> Bool{ userDefaults = NSUserDefaults() let userID = userDefaults!.stringForKey("userID") if(userID != nil){ print("User Signed In") return true } print("User Not Signed In") return false } func initProtectedPage(){ let mainStoryboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let mainPage = mainStoryboard.instantiateViewControllerWithIdentifier("mainViewController") as! MainPageViewController let mainPageNav = UINavigationController(rootViewController: mainPage) self.window?.rootViewController = mainPageNav } func initNavigationDrawer(){ //Instantiate 3 navigation View Controllers let mainStoryboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let mainPage = mainStoryboard.instantiateViewControllerWithIdentifier("mainViewController") as! MainPageViewController let leftSideMenu = mainStoryboard.instantiateViewControllerWithIdentifier("leftSideViewController") as! LeftSideViewController let rightSideMenu = mainStoryboard.instantiateViewControllerWithIdentifier("rightSideViewController") as! RightSideViewController //Wrap each View Controller into a Navigation Controller let mainPageNav = UINavigationController(rootViewController: mainPage) let leftSideMenuNav = UINavigationController(rootViewController: leftSideMenu) let rightSideMenuNav = UINavigationController(rootViewController: rightSideMenu) //Create the Navigation Drawer itself drawerContainer = MMDrawerController(centerViewController: mainPageNav, leftDrawerViewController: leftSideMenuNav, rightDrawerViewController: rightSideMenuNav) drawerContainer!.openDrawerGestureModeMask = MMOpenDrawerGestureMode.PanningCenterView drawerContainer!.closeDrawerGestureModeMask = MMCloseDrawerGestureMode.PanningCenterView //Set the Navigation Controller to the window Root Controller window?.rootViewController = drawerContainer } }
mit
9cbed7c6ca21776ad5ee65fcb5077881
47.346939
285
0.731053
6.01906
false
false
false
false
cathandnya/CHWebPreview
CHWebPreview/Classes/WebPreviewParser.swift
1
7576
// // WebPreviewParser.swift // ORE2 // // Created by nya on 2/27/16. // Copyright © 2016 cathand.org. All rights reserved. // import Foundation class WebPreviewParser: CHHtmlParser, NSURLSessionDataDelegate { var baseUrl: NSURL! var finishedHandler: ((WebpageInfo, NSError?) -> Void)? private var webInfo = WebpageInfo() private var finished = false private var inHead = false private var characterBuffer: NSMutableData? private var dataBuffer = NSMutableData() private var charset: NSStringEncoding override init() { charset = NSUTF8StringEncoding super.init(encoding: charset) } override func startElementName(name: String!, attributes: [NSObject : AnyObject]!) { let name = name.lowercaseString func getValue(key: String) -> String? { return (attributes[key] as? String) } if name == "meta" { if getValue("http-equiv")?.lowercaseString == "content-type" { if let content = getValue("content")?.lowercaseString, start = content.rangeOfString("charset=")?.endIndex { let set = content.substringFromIndex(start) var enc = encoding() if set == "shift_jis" { enc = NSShiftJISStringEncoding } else if set == "euc-jp" { enc = NSJapaneseEUCStringEncoding } else if set == "iso-2022-jp" { enc = NSISO2022JPStringEncoding } else if set == "utf-8" { enc = NSUTF8StringEncoding } charset = enc } } } if name == "head" { inHead = true } if inHead { if name == "meta" { if let property = getValue("property")?.lowercaseString, content = getValue("content") { if property == "og:title" { webInfo.title = content.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) } else if property == "og:description" { webInfo.desc = content.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) } else if webInfo.desc == nil && property == "description" { webInfo.desc = content.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) } else if property.hasPrefix("og:image") { if property == "og:image" || property == "og:image:url" { var url = content while url.rangeOfString("/../") != nil { url = url.stringByReplacingOccurrencesOfString("/../", withString: "/") } if !url.hasPrefix("https://") && !url.hasPrefix("http://") { url = baseUrl.URLByAppendingPathComponent(url).absoluteString } webInfo.images.append(WebpageImage(url: url)) } else if property == "og:image:width" { if let val = Int(content) { webInfo.images.last?.width = val } } else if property == "og:image:height" { if let val = Int(content) { webInfo.images.last?.height = val } } } else if property == "og:type" && content == "metadata" { } } else if let name = getValue("name")?.lowercaseString, content = getValue("content") { if webInfo.desc == nil && name == "description" { webInfo.desc = content.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) } } } else if name == "title" { if webInfo.title == nil { characterBuffer = NSMutableData() } } else if name == "link" && getValue("rel")?.lowercaseString == "origin" { if let href = getValue("href") { webInfo.origin = NSURL(string: href) } } } } override func endElementName(name: String!) { if name == "head" { inHead = false finished = true } if inHead { if name == "title" { /* if webInfo.title == nil { if let data = characterBuffer, str = String(data: data, encoding: encoding()) { //webInfo.title = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) } } */ characterBuffer = nil } } } override func characters(ch: UnsafePointer<UInt8>, length len: Int32) { /* for i in 0 ..< Int(len) { print(String(format: "%%%02X", Int(ch[i])), terminator: "") } print("\ncharacters: \(String(data: NSData(bytes: ch, length: Int(len)), encoding: encoding()))") */ characterBuffer?.appendData(NSData(bytes: ch, length: Int(len))) } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) { webInfo.url = response.URL?.absoluteString completionHandler(.Allow) } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { dataBuffer.appendData(data) addData(data) if encoding() != charset { addDataEnd() webInfo = WebpageInfo() finished = false inHead = false characterBuffer = nil setup(charset) addData(dataBuffer) } if finished { addDataEnd() finish(nil) } } func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { addDataEnd() finish(error) } private func finish(err: NSError?) { finishedHandler?(webInfo, err) finishedHandler = nil } class func load(url: NSURL, handler: (WebpageInfo, NSError?) -> Void) { let parser = WebPreviewParser() parser.baseUrl = url.URLByDeletingLastPathComponent let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: parser, delegateQueue: NSOperationQueue()) let task = session.dataTaskWithRequest(NSURLRequest(URL: url)) task.resume() parser.finishedHandler = { info, err in dispatch_async(dispatch_get_main_queue()) { task.cancel() parser if let url = info.origin { WebPreviewParser.load(url) { i, e -> Void in handler(i, e) } } else { handler(info, err) } } } } }
mit
af8c85e5edf529e4888b03ce0d17c965
39.079365
182
0.507063
5.485156
false
false
false
false
yl-github/YLDYZB
YLDouYuZB/YLDouYuZB/Classes/Main/Controller/YLBaseViewController.swift
1
1444
// // YLBaseViewController.swift // YLDouYuZB // // Created by yl on 2016/10/19. // Copyright © 2016年 yl. All rights reserved. // import UIKit class YLBaseViewController: UIViewController { // 用来接收collectionview var contentView : UIView? fileprivate lazy var imageView : UIImageView = {[unowned self] in let imageView = UIImageView(image: UIImage(named:"img_loading_1")); imageView.center = self.view.center; imageView.animationImages = [UIImage(named:"img_loading_1")!,UIImage(named:"img_loading_2")!]; imageView.animationDuration = 0.5; imageView.animationRepeatCount = LONG_MAX; imageView.autoresizingMask = [.flexibleTopMargin,.flexibleBottomMargin]; return imageView; }() override func viewDidLoad() { super.viewDidLoad() setupUI(); } } extension YLBaseViewController { func setupUI(){ // 1.隐藏contentview contentView?.isHidden = true; // 2.添加imageView view.addSubview(imageView); // 3.设置背景颜色 view.backgroundColor = UIColor(r: 250, g: 250, b: 250); // 4.开始动画 imageView.startAnimating(); } func loadDataFinished(){ // 1.停止动画 imageView.stopAnimating(); // 2.隐藏imageView imageView.isHidden = true; // 3.显示contentView contentView?.isHidden = false; } }
mit
febbca98115d4b58fd83b8c06af144d6
27.346939
102
0.62563
4.495146
false
false
false
false
esttorhe/RxSwift
RxSwift/RxSwift/Error.swift
1
1009
// // Error.swift // Rx // // Created by Krunoslav Zaher on 3/28/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation let RxErrorDomain = "RxErrorDomain" let RxCompositeFailures = "RxCompositeFailures" public enum RxErrorCode : Int { case Unknown = 0 case Cast = 2 case Disposed = 3 } // just temporary public func errorEquals(lhs: ErrorType, _ rhs: ErrorType) -> Bool { if let error1 = lhs as? NSError { if let error2 = rhs as? NSError { return error1 === error2 } } return false } public let UnknownError = NSError(domain: RxErrorDomain, code: RxErrorCode.Unknown.rawValue, userInfo: nil) public let CastError = NSError(domain: RxErrorDomain, code: RxErrorCode.Cast.rawValue, userInfo: nil) public let DisposedError = NSError(domain: RxErrorDomain, code: RxErrorCode.Disposed.rawValue, userInfo: nil) func removingObserverFailed() { rxFatalError("Removing observer for key failed") }
mit
53ec3bfd3a3d744385981341d86854a1
25.552632
109
0.68781
3.836502
false
false
false
false
oAugus/SlideMenu-Swift
SlideMenu/ContainerViewController.swift
2
9308
// // ContainerViewController.swift // SlideMenu // // Created by Augus on 4/27/15. // Copyright (c) 2015 Augus. All rights reserved. // import UIKit enum SlideOutState { case collapsed case LeftPanelExpanded } let kExpandedOffSet: CGFloat = 130.0 class ContainerViewController: UIViewController, UIGestureRecognizerDelegate { let kScreenWidth = UIScreen.mainScreen().bounds.width let kScreenHeight = UIScreen.mainScreen().bounds.height var centerVCFrontBlurView: UIVisualEffectView! var centerNavigationController: UINavigationController! var mainViewController: MainTabBarController! var leftViewController: SlidePanelViewController? var currentState: SlideOutState = .collapsed { didSet { let shouldShowShadow = currentState != .collapsed showShadowForCenterViewController(shouldShowShadow) } } override func viewDidLoad() { super.viewDidLoad() configureBlurView() mainViewController = UIStoryboard.mainViewController() centerNavigationController = UINavigationController(rootViewController: mainViewController) centerNavigationController.setNavigationBarHidden(true , animated: false) view.addSubview(centerNavigationController.view) addChildViewController(centerNavigationController) centerNavigationController.didMoveToParentViewController(self) configureGestureRecognizer() } func configureBlurView(){ // centerVCFrontBlurView = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton let viewEffect = UIBlurEffect(style: .Light) centerVCFrontBlurView = UIVisualEffectView(effect: viewEffect) centerVCFrontBlurView.alpha = 0.9 } func configureGestureRecognizer() { let panGestureRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:))) panGestureRecognizer.edges = UIRectEdge.Left centerNavigationController.view.addGestureRecognizer(panGestureRecognizer) // panGestureRecognizer.delegate = self let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_:))) centerVCFrontBlurView.addGestureRecognizer(tapGestureRecognizer) } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } // func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailByGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { // // if gestureRecognizer.isKindOfClass(UIScreenEdgePanGestureRecognizer.classForCoder()) { // if (otherGestureRecognizer.view?.isKindOfClass(UIScrollView.classForCoder()) != nil){ // return true // } // } // if (otherGestureRecognizer.view?.isKindOfClass(UITableView.classForCoder()) != nil){ // return true // } // return false // } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func toggleLeftPanel() { let notAlreadyExpanded = (currentState != .LeftPanelExpanded) if notAlreadyExpanded { addLeftPanelViewController() } animateLeftPanel(notAlreadyExpanded) } func addLeftPanelViewController() { if leftViewController == nil { leftViewController = UIStoryboard.leftViewController() addChildSidePanelController(leftViewController!) } } func addChildSidePanelController(sidePanelController: SlidePanelViewController) { view.insertSubview(sidePanelController.view, atIndex: 0) addChildViewController(sidePanelController) sidePanelController.didMoveToParentViewController(self) } func animateLeftPanel(shouldExpand: Bool) { if shouldExpand { currentState = .LeftPanelExpanded animateCenterPanelXPosition(kExpandedOffSet) } else { animateCenterPanelXPosition(0) { finished in self.currentState = .collapsed self.leftViewController?.view.removeFromSuperview() self.leftViewController = nil; } } } func animateCenterPanelXPosition(targetPosition: CGFloat, completion: ((Bool) -> Void)! = nil) { UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: .CurveEaseInOut, animations: { self.centerNavigationController?.view.frame.origin.x = targetPosition }, completion: completion) } func showShadowForCenterViewController(shouldShowShadow: Bool) { if (shouldShowShadow) { centerNavigationController?.view.layer.shadowOpacity = 0.8 } else { centerNavigationController?.view.layer.shadowOpacity = 0 } } func menuSelected(index: Int) { if index == 0 { centerNavigationController.viewControllers[0] = mainViewController } view.addSubview(centerNavigationController.view) addChildViewController(centerNavigationController) centerNavigationController.didMoveToParentViewController(self) collapseSidePanels() } func collapseSidePanels() { switch (currentState) { case .LeftPanelExpanded: toggleLeftPanel() default: break } } func handlePanGesture(recognizer: UIPanGestureRecognizer) { let gestureIsDraggingFromLeftToRight = (recognizer.velocityInView(view).x > 0) switch(recognizer.state) { case .Began: mainViewController.view.addSubview(centerVCFrontBlurView) centerVCFrontBlurView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activateConstraints([ NSLayoutConstraint(item: centerVCFrontBlurView, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: 0), NSLayoutConstraint(item: centerVCFrontBlurView, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: 0), NSLayoutConstraint(item: centerVCFrontBlurView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0), NSLayoutConstraint(item: centerVCFrontBlurView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0) ]) mainViewController.navigationController?.setNavigationBarHidden(true , animated: false) if (currentState == .collapsed) { if (gestureIsDraggingFromLeftToRight) { addLeftPanelViewController() showShadowForCenterViewController(true) } } case .Changed: let pointX = centerNavigationController.view.frame.origin.x if (gestureIsDraggingFromLeftToRight || pointX > 0){ recognizer.view!.center.x = recognizer.view!.center.x + recognizer.translationInView(view).x recognizer.setTranslation(CGPointZero, inView: view) } case .Ended: if leftViewController != nil{ // animate the side panel open or closed based on whether the view has moved more or less than halfway let hasMovedGreaterThanHalfway = recognizer.view!.center.x > view.bounds.size.width / 1.5 animateLeftPanel(hasMovedGreaterThanHalfway) if !hasMovedGreaterThanHalfway { centerVCFrontBlurView.removeFromSuperview() } } default: break } } func handleTapGesture(recognizer: UITapGestureRecognizer) { if leftViewController != nil { animateLeftPanel(false) centerVCFrontBlurView?.removeFromSuperview() } } // close left panel override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { if leftViewController != nil { animateLeftPanel(false) centerVCFrontBlurView?.removeFromSuperview() } } } private extension UIStoryboard { class func mainStoryboard() -> UIStoryboard { return UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) } class func leftViewController() -> SlidePanelViewController? { return mainStoryboard().instantiateViewControllerWithIdentifier("LeftViewController") as? SlidePanelViewController } class func mainViewController() -> MainTabBarController? { return mainStoryboard().instantiateViewControllerWithIdentifier("TabBarController") as? MainTabBarController } }
mit
aff46faa0af8e489b1a3ab265ea1d533
37.7875
172
0.657714
6.075718
false
false
false
false
BelledonneCommunications/linphone-iphone
Classes/Swift/Voip/Widgets/UICallTimer.swift
1
1953
/* * Copyright (c) 2010-2020 Belledonne Communications SARL. * * This file is part of linphone-iphone * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Foundation import linphonesw class CallTimer : StyledLabel { let min_width = 50.0 let formatter = DateComponentsFormatter() var startDate = Date() var call:Call? = nil { didSet { self.format() } } var conference:Conference? = nil { didSet { self.format() } } required init?(coder: NSCoder) { super.init(coder: coder) } init (_ text:String?, _ style:TextStyle, _ call:Call? = nil) { super.init(style,text) self.call = call formatter.unitsStyle = .positional formatter.allowedUnits = [.minute, .second ] formatter.zeroFormattingBehavior = [ .pad ] Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in var elapsedTime: TimeInterval = 0 if (self.call != nil || self.conference != nil) { elapsedTime = Date().timeIntervalSince(self.startDate) } self.formatter.string(from: elapsedTime).map { self.text = $0.hasPrefix("0:") ? "0" + $0 : $0 } } minWidth(min_width).done() } func format() { guard let duration = self.call != nil ? self.call!.duration : self.conference != nil ? self.conference!.duration: nil else { return } startDate = Date().advanced(by: -TimeInterval(duration)) } }
gpl-3.0
9b0c72d1e4c3f916e311bbfba6cc61a4
26.507042
126
0.69022
3.544465
false
false
false
false
mcomella/prox
Prox/Prox/Widgets/ReviewScoreView.swift
1
4487
/* 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 private let ItemSeparation: CGFloat = 2 class ReviewScoreView: UIStackView { var color: UIColor { didSet { if color != oldValue { updateReviewScore(score: self.score) } } } var score: Float = 0.0 { didSet { updateReviewScore(score: score) } } convenience init(color: UIColor) { self.init(score: 0, color: color) } init(score: Float, color: UIColor) { self.score = score self.color = color super.init(frame: .zero) distribution = .equalSpacing axis = .horizontal alignment = .center spacing = 0 for index in 0..<5 { let scoreItem = ReviewScoreItemView(filledColor: self.color, unfilledColor: Colors.reviewScoreDefault) scoreItem.backgroundColor = .clear let scoreRemaining = self.score - Float(index) setFillScore(score: scoreRemaining, forView: scoreItem) addArrangedSubview(scoreItem) } } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate var reviewScoreWidth: CGFloat? fileprivate var reviewScoreHeight: CGFloat? override func layoutSubviews() { super.layoutSubviews() if reviewScoreWidth == nil || reviewScoreHeight == nil { let width: CGFloat = (frame.width - ItemSeparation * 4) / 5 let height: CGFloat = frame.height for subview in arrangedSubviews { subview.widthAnchor.constraint(equalToConstant: width).isActive = true subview.heightAnchor.constraint(equalToConstant: height).isActive = true } reviewScoreHeight = height reviewScoreWidth = width } } private func updateReviewScore(score: Float) { for (index, subview) in arrangedSubviews.enumerated() { if let scoreItem = subview as? ReviewScoreItemView { let scoreRemaining = self.score - Float(index) setFillScore(score: scoreRemaining, forView: scoreItem) } } } private func setFillScore(score: Float, forView view: ReviewScoreItemView) { if score >= 1 { view.fillType = .full } else if score > 0 { view.fillType = .half } else { view.fillType = .empty } } } private enum FillAmount { case full case half case empty } private class ReviewScoreItemView: UIView { var filledColor: UIColor { didSet { setNeedsDisplay() } } var unfilledColor: UIColor { didSet { setNeedsDisplay() } } var fillType: FillAmount = .empty init(filledColor: UIColor, unfilledColor: UIColor) { self.filledColor = filledColor self.unfilledColor = unfilledColor super.init(frame: .zero) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { super.draw(rect) let width = rect.size.width / 2 let leftColor: UIColor let rightColor: UIColor switch fillType { case .full: leftColor = filledColor rightColor = filledColor case .half: leftColor = filledColor rightColor = unfilledColor case .empty: leftColor = unfilledColor rightColor = unfilledColor } let leftHalf = UIBezierPath(roundedRect: CGRect(x: rect.origin.x, y: rect.origin.x, width: width, height: rect.size.height), byRoundingCorners: [UIRectCorner.topLeft, UIRectCorner.bottomLeft], cornerRadii: CGSize(width: 10, height: 10)) leftHalf.close() leftColor.setFill() leftHalf.fill() let rightHalf = UIBezierPath(roundedRect: CGRect(x: rect.origin.x + width, y: rect.origin.x, width: width, height: rect.size.height), byRoundingCorners: [UIRectCorner.topRight, UIRectCorner.bottomRight], cornerRadii: CGSize(width: 10, height: 10)) rightHalf.close() rightColor.setFill() rightHalf.fill() } }
mpl-2.0
b6665cca1fc790a4be37a2de42a7067e
27.948387
255
0.601293
4.602051
false
false
false
false
Ray0218/SevenSwitch
SevenSwitch.swift
1
18978
// // SevenSwitch.swift // // Created by Benjamin Vogelzang on 6/20/14. // Copyright (c) 2014 Ben Vogelzang. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import QuartzCore @objc class SevenSwitch: UIControl { // public /* * Set (without animation) whether the switch is on or off */ var on: Bool { get { return switchValue } set { switchValue = newValue self.setOn(newValue, animated: false) } } /* * Sets the background color that shows when the switch off and actively being touched. * Defaults to light gray. */ var activeColor: UIColor = UIColor(red: 0.89, green: 0.89, blue: 0.89, alpha: 1) { willSet { if self.on && !self.tracking { backgroundView.backgroundColor = newValue } } } /* * Sets the background color when the switch is off. * Defaults to clear color. */ var inactiveColor: UIColor = UIColor.clearColor() { willSet { if !self.on && !self.tracking { backgroundView.backgroundColor = newValue } } } /* * Sets the background color that shows when the switch is on. * Defaults to green. */ var onTintColor: UIColor = UIColor(red: 0.3, green: 0.85, blue: 0.39, alpha: 1) { willSet { if self.on && !self.tracking { backgroundView.backgroundColor = newValue backgroundView.layer.borderColor = newValue.CGColor } } } //var offTintColor: UIColor /* * Sets the border color that shows when the switch is off. Defaults to light gray. */ var borderColor: UIColor = UIColor(red: 0.78, green: 0.78, blue: 0.8, alpha: 1) { willSet { if !self.on { backgroundView.layer.borderColor = newValue.CGColor } } } /* * Sets the knob color. Defaults to white. */ var thumbTintColor: UIColor = UIColor.whiteColor() { willSet { if !userDidSpecifyOnThumbTintColor { onThumbTintColor = newValue } if (!userDidSpecifyOnThumbTintColor || !self.on) && !self.tracking { thumbView.backgroundColor = newValue } } } /* * Sets the knob color that shows when the switch is on. Defaults to white. */ var onThumbTintColor: UIColor = UIColor.whiteColor() { willSet { userDidSpecifyOnThumbTintColor = true if self.on && !self.tracking { thumbView.backgroundColor = newValue } } } /* * Sets the shadow color of the knob. Defaults to gray. */ var shadowColor: UIColor = UIColor.grayColor() { willSet { thumbView.layer.shadowColor = newValue.CGColor } } /* * Sets whether or not the switch edges are rounded. * Set to NO to get a stylish square switch. * Defaults to YES. */ var isRounded: Bool = true { willSet { if newValue { backgroundView.layer.cornerRadius = self.frame.size.height * 0.5 thumbView.layer.cornerRadius = (self.frame.size.height * 0.5) - 1 } else { backgroundView.layer.cornerRadius = 2 thumbView.layer.cornerRadius = 2 } thumbView.layer.shadowPath = UIBezierPath(roundedRect: thumbView.bounds, cornerRadius: thumbView.layer.cornerRadius).CGPath } } /* * Sets the image that shows on the switch thumb. */ var thumbImage: UIImage! { willSet { thumbImageView.image = newValue } } /* * Sets the image that shows when the switch is on. * The image is centered in the area not covered by the knob. * Make sure to size your images appropriately. */ var onImage: UIImage! { willSet { onImageView.image = newValue } } /* * Sets the image that shows when the switch is off. * The image is centered in the area not covered by the knob. * Make sure to size your images appropriately. */ var offImage: UIImage! { willSet { offImageView.image = newValue } } /* * Sets the text that shows when the switch is on. * The text is centered in the area not covered by the knob. */ var onLabel: UILabel! /* * Sets the text that shows when the switch is off. * The text is centered in the area not covered by the knob. */ var offLabel: UILabel! // private var backgroundView: UIView! var thumbView: UIView! var onImageView: UIImageView! var offImageView: UIImageView! var thumbImageView: UIImageView! var currentVisualValue: Bool = false var startTrackingValue: Bool = false var didChangeWhileTracking: Bool = false var isAnimating: Bool = false var userDidSpecifyOnThumbTintColor: Bool = false var switchValue: Bool = false /* * Initialization */ override init() { super.init(frame: CGRectMake(0, 0, 50, 30)) self.setup() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } override init(frame: CGRect) { let initialFrame = CGRectIsEmpty(frame) ? CGRectMake(0, 0, 50, 30) : frame super.init(frame: initialFrame) self.setup() } /* * Setup the individual elements of the switch and set default values */ func setup() { // background self.backgroundView = UIView(frame: CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)) backgroundView.backgroundColor = UIColor.clearColor() backgroundView.layer.cornerRadius = self.frame.size.height * 0.5 backgroundView.layer.borderColor = self.borderColor.CGColor backgroundView.layer.borderWidth = 1.0 backgroundView.userInteractionEnabled = false backgroundView.clipsToBounds = true self.addSubview(backgroundView) // on/off images self.onImageView = UIImageView(frame: CGRectMake(0, 0, self.frame.size.width - self.frame.size.height, self.frame.size.height)) onImageView.alpha = 1.0 onImageView.contentMode = UIViewContentMode.Center backgroundView.addSubview(onImageView) self.offImageView = UIImageView(frame: CGRectMake(self.frame.size.height, 0, self.frame.size.width - self.frame.size.height, self.frame.size.height)) offImageView.alpha = 1.0 offImageView.contentMode = UIViewContentMode.Center backgroundView.addSubview(offImageView) // labels self.onLabel = UILabel(frame: CGRectMake(0, 0, self.frame.size.width - self.frame.size.height, self.frame.size.height)) onLabel.textAlignment = NSTextAlignment.Center onLabel.textColor = UIColor.lightGrayColor() onLabel.font = UIFont.systemFontOfSize(12) backgroundView.addSubview(onLabel) self.offLabel = UILabel(frame: CGRectMake(self.frame.size.height, 0, self.frame.size.width - self.frame.size.height, self.frame.size.height)) offLabel.textAlignment = NSTextAlignment.Center offLabel.textColor = UIColor.lightGrayColor() offLabel.font = UIFont.systemFontOfSize(12) backgroundView.addSubview(offLabel) // thumb self.thumbView = UIView(frame: CGRectMake(1, 1, self.frame.size.height - 2, self.frame.size.height - 2)) thumbView.backgroundColor = self.thumbTintColor thumbView.layer.cornerRadius = (self.frame.size.height * 0.5) - 1 thumbView.layer.shadowColor = self.shadowColor.CGColor thumbView.layer.shadowRadius = 2.0 thumbView.layer.shadowOpacity = 0.5 thumbView.layer.shadowOffset = CGSizeMake(0, 3) thumbView.layer.shadowPath = UIBezierPath(roundedRect: thumbView.bounds, cornerRadius: thumbView.layer.cornerRadius).CGPath thumbView.layer.masksToBounds = false thumbView.userInteractionEnabled = false self.addSubview(thumbView) // thumb image self.thumbImageView = UIImageView(frame: CGRectMake(0, 0, thumbView.frame.size.width, thumbView.frame.size.height)) thumbImageView.contentMode = UIViewContentMode.Center thumbImageView.autoresizingMask = UIViewAutoresizing.FlexibleWidth thumbView.addSubview(thumbImageView) self.on = false } override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) -> Bool { super.beginTrackingWithTouch(touch, withEvent: event) startTrackingValue = self.on didChangeWhileTracking = false let activeKnobWidth = self.bounds.size.height - 2 + 5 isAnimating = true UIView.animateWithDuration(0.3, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut | UIViewAnimationOptions.BeginFromCurrentState, animations: { if self.on { self.thumbView.frame = CGRectMake(self.bounds.size.width - (activeKnobWidth + 1), self.thumbView.frame.origin.y, activeKnobWidth, self.thumbView.frame.size.height) self.backgroundView.backgroundColor = self.onTintColor self.thumbView.backgroundColor = self.onThumbTintColor } else { self.thumbView.frame = CGRectMake(self.thumbView.frame.origin.x, self.thumbView.frame.origin.y, activeKnobWidth, self.thumbView.frame.size.height) self.backgroundView.backgroundColor = self.activeColor self.thumbView.backgroundColor = self.thumbTintColor } }, completion: { finished in self.isAnimating = false }) return true } override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) -> Bool { super.continueTrackingWithTouch(touch, withEvent: event) // Get touch location let lastPoint = touch.locationInView(self) // update the switch to the correct visuals depending on if // they moved their touch to the right or left side of the switch if lastPoint.x > self.bounds.size.width * 0.5 { self.showOn(true) if !startTrackingValue { didChangeWhileTracking = true } } else { self.showOff(true) if startTrackingValue { didChangeWhileTracking = true } } return true } override func endTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) { super.endTrackingWithTouch(touch, withEvent: event) let previousValue = self.on if didChangeWhileTracking { self.setOn(currentVisualValue, animated: true) } else { self.setOn(!self.on, animated: true) } if previousValue != self.on { self.sendActionsForControlEvents(UIControlEvents.ValueChanged) } } override func cancelTrackingWithEvent(event: UIEvent?) { super.cancelTrackingWithEvent(event) // just animate back to the original value if self.on { self.showOn(true) } else { self.showOff(true) } } override func layoutSubviews() { super.layoutSubviews() if !isAnimating { let frame = self.frame // background backgroundView.frame = CGRectMake(0, 0, frame.size.width, frame.size.height) backgroundView.layer.cornerRadius = self.isRounded ? frame.size.height * 0.5 : 2 // images onImageView.frame = CGRectMake(0, 0, frame.size.width - frame.size.height, frame.size.height) offImageView.frame = CGRectMake(frame.size.height, 0, frame.size.width - frame.size.height, frame.size.height) self.onLabel.frame = CGRectMake(0, 0, frame.size.width - frame.size.height, frame.size.height) self.offLabel.frame = CGRectMake(frame.size.height, 0, frame.size.width - frame.size.height, frame.size.height) // thumb let normalKnobWidth = frame.size.height - 2 if self.on { thumbView.frame = CGRectMake(frame.size.width - (normalKnobWidth + 1), 1, frame.size.height - 2, normalKnobWidth) } else { thumbView.frame = CGRectMake(1, 1, normalKnobWidth, normalKnobWidth) } thumbView.layer.cornerRadius = self.isRounded ? (frame.size.height * 0.5) - 1 : 2 } } /* * Set the state of the switch to on or off, optionally animating the transition. */ func setOn(isOn: Bool, animated: Bool) { switchValue = isOn if on { self.showOn(animated) } else { self.showOff(animated) } } /* * Detects whether the switch is on or off * * @return BOOL YES if switch is on. NO if switch is off */ func isOn() -> Bool { return self.on } /* * update the looks of the switch to be in the on position * optionally make it animated */ func showOn(animated: Bool) { let normalKnobWidth = self.bounds.size.height - 2 let activeKnobWidth = normalKnobWidth + 5 if animated { isAnimating = true UIView.animateWithDuration(0.3, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut | UIViewAnimationOptions.BeginFromCurrentState, animations: { if self.tracking { self.thumbView.frame = CGRectMake(self.bounds.size.width - (activeKnobWidth + 1), self.thumbView.frame.origin.y, activeKnobWidth, self.thumbView.frame.size.height) } else { self.thumbView.frame = CGRectMake(self.bounds.size.width - (normalKnobWidth + 1), self.thumbView.frame.origin.y, normalKnobWidth, self.thumbView.frame.size.height) } self.backgroundView.backgroundColor = self.onTintColor self.backgroundView.layer.borderColor = self.onTintColor.CGColor self.thumbView.backgroundColor = self.onThumbTintColor self.onImageView.alpha = 1.0 self.offImageView.alpha = 0 self.onLabel.alpha = 1.0 self.offLabel.alpha = 0 }, completion: { finished in self.isAnimating = false }) } else { if self.tracking { thumbView.frame = CGRectMake(self.bounds.size.width - (activeKnobWidth + 1), thumbView.frame.origin.y, activeKnobWidth, thumbView.frame.size.height) } else { thumbView.frame = CGRectMake(self.bounds.size.width - (normalKnobWidth + 1), thumbView.frame.origin.y, normalKnobWidth, thumbView.frame.size.height) } backgroundView.backgroundColor = self.onTintColor backgroundView.layer.borderColor = self.onTintColor.CGColor thumbView.backgroundColor = self.onThumbTintColor onImageView.alpha = 1.0 offImageView.alpha = 0 onLabel.alpha = 1.0 offLabel.alpha = 0 } currentVisualValue = true } /* * update the looks of the switch to be in the off position * optionally make it animated */ func showOff(animated: Bool) { let normalKnobWidth = self.bounds.size.height - 2 let activeKnobWidth = normalKnobWidth + 5 if animated { isAnimating = true UIView.animateWithDuration(0.3, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut | UIViewAnimationOptions.BeginFromCurrentState, animations: { if self.tracking { self.thumbView.frame = CGRectMake(1, self.thumbView.frame.origin.y, activeKnobWidth, self.thumbView.frame.size.height); self.backgroundView.backgroundColor = self.activeColor } else { self.thumbView.frame = CGRectMake(1, self.thumbView.frame.origin.y, normalKnobWidth, self.thumbView.frame.size.height); self.backgroundView.backgroundColor = self.inactiveColor } self.backgroundView.layer.borderColor = self.borderColor.CGColor self.thumbView.backgroundColor = self.thumbTintColor self.onImageView.alpha = 0 self.offImageView.alpha = 1.0 self.onLabel.alpha = 0 self.offLabel.alpha = 1.0 }, completion: { finished in self.isAnimating = false }) } else { if (self.tracking) { thumbView.frame = CGRectMake(1, thumbView.frame.origin.y, activeKnobWidth, thumbView.frame.size.height) backgroundView.backgroundColor = self.activeColor } else { thumbView.frame = CGRectMake(1, thumbView.frame.origin.y, normalKnobWidth, thumbView.frame.size.height) backgroundView.backgroundColor = self.inactiveColor } backgroundView.layer.borderColor = self.borderColor.CGColor thumbView.backgroundColor = self.thumbTintColor onImageView.alpha = 0 offImageView.alpha = 1.0 onLabel.alpha = 0 offLabel.alpha = 1.0 } currentVisualValue = false } }
mit
fb5545db37e6616582b2eedd761284dc
35.356322
183
0.610496
4.70218
false
false
false
false
Eonil/Promise.Swift
EonilPromise/PromiseExtensions.swift
1
8632
// // PromiseExtensions.swift // Promise // // Created by Hoon H. on 2015/12/05. // Copyright © 2015 Eonil. All rights reserved. // import Foundation public extension Promise { public convenience init(result: PromiseResult<T>) { self.init() self.result = result } public convenience init(error: ErrorType) { self.init() self.result = PromiseResult.Error(error) } public convenience init(value: T) { self.init() self.result = PromiseResult<T>.Ready(value) } public convenience init(unstoppableNonMainThreadExecution: ()->PromiseResult<T>) { self.init() GCDUtility.continueInNonMainThreadAsynchronously { [weak self] in let result = unstoppableNonMainThreadExecution() GCDUtility.continueInMainThreadAynchronously { [weak self] in assertMainThread() precondition(self != nil) self!.result = result } } } } //public extension Promise { // /// Also cancels specified promise when this promise cancels. // public func <U>(promise: Promise<U>) { // // This is an a bit optimized implementation. // // This also can be implemented using `then` chaining. // let oldOnCancel = onCancel // onCancel = { [weak promise] in // oldOnCancel?() // guard let promise = promise else { return } // guard promise.result == nil else { return } // promise.cancel() // } // } //} public extension Promise { public func then(continuation: ()->()) { then { (_: PromiseResult<T>) -> () in continuation() } } /// Terminates promise chain regardless of result state. public func then(continuation: PromiseResult<T> -> ()) { _ = then({ (result: PromiseResult<T>) -> Promise<()> in continuation(result) return Promise<()>(value: ()) }) } /// Terminates promise chain on ready state. public func thenOnReady(continuation: T -> ()) { _ = thenOnReady({ (value: T) -> Promise<()> in continuation(value) return Promise<()>(value: ()) }) } public func thenOnReady<U>(continuation: T -> Promise<U>) -> Promise<U> { return then({ (result: PromiseResult<T>) -> Promise<U> in switch result { case .Ready(let value): return continuation(value) case .Error(let error): return Promise<U>(error: error) case .Cancel: return Promise<U>(result: PromiseResult<U>.Cancel) } }) } // public func then<U>(continuation: (result: PromiseResult<T>, onComplete: (result: PromiseResult<U>) -> ()) -> ()) -> Promise<U> { // return then({ (result: PromiseResult<T>) -> Promise<U> in // let subpromise = Promise<U>() // let onComplete = { subpromise.result = $0 } // continuation(result: result, onComplete: onComplete) // return subpromise // }) // } // public func then<U>(continuation: (value: T, onComplete: (PromiseResult<U>) -> ()) -> ()) -> Promise<U> { // return then({ (value: T) -> Promise<U> in // let subpromise = Promise<U>() // let onComplete = { (result: PromiseResult<U>) -> () in // subpromise.result = result // } // continuation(value: value, onComplete: onComplete) // return subpromise // }) // } } extension Promise { /// Waits unconditionally. This always wait even on error or cancel. func thenWaitAlways(durationInSeconds: NSTimeInterval) -> Promise<T> { return thenWaitConditionally(durationInSeconds, condition: { _ in return true }) } /// Waits only on ready state. Doesn't wait on error or cancel. func thenWaitOnReady(durationInSeconds: NSTimeInterval) -> Promise<T> { return thenWaitConditionally(durationInSeconds, condition: { (result: PromiseResult<T>) -> Bool in switch result { case .Ready: return true default: return false } }) } /// Waits only on ready state. Doesn't wait on error or cancel. func thenWaitOnError(durationInSeconds: NSTimeInterval) -> Promise<T> { return thenWaitConditionally(durationInSeconds, condition: { (result: PromiseResult<T>) -> Bool in switch result { case .Error: return true default: return false } }) } /// Waits only on ready state. Doesn't wait on error or cancel. func thenWaitOnCancel(durationInSeconds: NSTimeInterval) -> Promise<T> { return thenWaitConditionally(durationInSeconds, condition: { (result: PromiseResult<T>) -> Bool in switch result { case .Cancel: return true default: return false } }) } /// Waits conditionally. func thenWaitConditionally(durationInSeconds: NSTimeInterval, condition: PromiseResult<T> -> Bool) -> Promise<T> { return then({ (result: PromiseResult<T>) -> Promise<T> in print(result) guard condition(result) else { return Promise(result: result) } let subpromise = Promise<T>() let time = dispatch_time(DISPATCH_TIME_NOW, Int64(durationInSeconds * NSTimeInterval(NSEC_PER_SEC))) dispatch_after(time, GCDUtility.mainThreadQueue()) { if subpromise.result != nil && subpromise.result!.isCancel { return } subpromise.result = result } return subpromise }) } } extension Promise { public func waitForPromise<U>(otherPromise: Promise<U>) -> Promise<T> { return then({ (result: PromiseResult<T>) -> Promise<T> in let subpromise = Promise<T>() otherPromise.then({ () -> () in subpromise.result = result }) return subpromise }) } } extension Promise { public func thenExecuteUnstoppableOperationInNonMainThread<U>(unstoppableNonMainThreadOperation: PromiseResult<T>->PromiseResult<U>) -> Promise<U> { return then { (result: PromiseResult<T>) -> Promise<U> in let subpromise = Promise<U>() GCDUtility.continueInNonMainThreadAsynchronously { let result = unstoppableNonMainThreadOperation(result) GCDUtility.continueInMainThreadAynchronously { assertMainThread() subpromise.result = result } } return subpromise } } public func thenExecuteUnstoppableOperationInNonMainThreadOnReady<U>(unstoppableNonMainThreadOperation: T->PromiseResult<U>) -> Promise<U> { return thenExecuteUnstoppableOperationInNonMainThread { (result: PromiseResult<T>) -> PromiseResult<U> in switch result { case .Ready(let value): return unstoppableNonMainThreadOperation(value) case .Error(let error): return .Error(error) case .Cancel: return .Cancel } } } public func thenExecuteUnstoppableOperationInNonMainThreadOnReady<U>(unstoppableNonMainThreadOperation: T throws -> U) -> Promise<U> { return thenExecuteUnstoppableOperationInNonMainThread { (result: PromiseResult<T>) -> PromiseResult<U> in switch result { case .Ready(let value): do { return .Ready(try unstoppableNonMainThreadOperation(value)) } catch let error { return .Error(error) } case .Error(let error): return .Error(error) case .Cancel: return .Cancel } } } } public enum PromiseNSURLRequestError: ErrorType { case CompleteWithNoErrorAndNoData(request: NSURLRequest, response: NSURLResponse?) } public extension Promise { public func thenExecuteNSURLSessionDataTask(continuation: T throws -> NSURLRequest) -> Promise<NSData> { return thenOnReady { (value: T) -> Promise<NSData> in let subpromise = Promise<NSData>() do { let request = try continuation(value) let onComplete = { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in GCDUtility.continueInMainThreadAynchronously { if let error = error { if error.code == NSURLErrorCancelled { subpromise.result = .Cancel return } subpromise.result = .Error(error) return } if let data = data { subpromise.result = .Ready(data) return } let error = PromiseNSURLRequestError.CompleteWithNoErrorAndNoData(request: request, response: response) subpromise.result = .Error(error) return } } let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: onComplete) subpromise.onCancel = { [task] in task.cancel() } task.resume() } catch let error { subpromise.result = .Error(error) } return subpromise } } } //public protocol CancellableTaskType { // typealias Value // func run(onSuccess onSuccess: Value->(), onFailure: ErrorType->()) // func cancel() //} //public extension Promise { // public func thenExecuteCancellableTask<U: CancellableTaskType>(task: U) -> Promise<U.Value> { // let subpromise = Promise<U.Value>() // let onSuccess = { (value: U.Value) -> () in // subpromise.result = .Ready(value) // } // let onFailure = { (error: ErrorType) -> () in // subpromise.result = .Error(error) // } // task.run(onSuccess: onSuccess, onFailure: onFailure) // subpromise.onCancel = { task.cancel() } // return subpromise // } //}
mit
bc9027394ac203141e2873eca82e35c2
28.762069
149
0.682424
3.50142
false
false
false
false
mwharrison/openstax-ios
Openstax/BookmarkTableViewController.swift
1
7283
// // BookmarkTableViewController.swift // Openstax // // Created by Michael Harrison on 8/30/16. // Copyright © 2016 Openstax. All rights reserved. // import UIKit class BookmarkTableViewController: UITableViewController { var bookmarks : NSMutableArray = [] //var bookmarksLoaded :NSArray = [] var bookmarkURL : String = "" func loadBookmarks() { bookmarks.removeAllObjects() var bookmarksLoaded = UserDefaults.standard.object(forKey: "bookmarks") // if there are bookmarks, load them into the bookmarks array so we can edit them if(bookmarksLoaded != nil) { for tempBookmark in bookmarksLoaded as! NSArray { bookmarks.add(tempBookmark) } bookmarksLoaded = nil } tableView.reloadData() } 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 viewDidAppear(_ animated: Bool) { loadBookmarks() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return bookmarks.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "BookmarkTableViewCell", for: indexPath) as! BookmarkTableViewCell let bookmark = bookmarks[indexPath.row] as! [String:String] cell.bookTitleLabel.text = bookmark["bookName"] cell.bookSectionLabel.text = bookmark["bookSection"] // Use the outlet in our custom class to get a reference to the UIImage in the cell if(bookmark["bookName"] == "College Algebra") { cell.bookImage.image = UIImage(named: "algebra.png") }else if(bookmark["bookName"] == "Algebra and Trigonometry"){ cell.bookImage.image = UIImage(named: "algebra_trig.png") }else if(bookmark["bookName"] == "Anatomy & Physiology"){ cell.bookImage.image = UIImage(named: "anatomy.png") }else if(bookmark["bookName"] == "Biology"){ cell.bookImage.image = UIImage(named: "biology.png") }else if(bookmark["bookName"] == "Concepts of Biology"){ cell.bookImage.image = UIImage(named: "biology_concepts.png") }else if(bookmark["bookName"] == "Calculus Volume 1"){ cell.bookImage.image = UIImage(named: "calculus_1.jpg") }else if(bookmark["bookName"] == "Calculus Volume 2"){ cell.bookImage.image = UIImage(named: "calculus_2.jpg") }else if(bookmark["bookName"] == "Calculus Volume 3"){ cell.bookImage.image = UIImage(named: "calculus_3.jpg") }else if(bookmark["bookName"] == "Principles of Economics"){ cell.bookImage.image = UIImage(named: "economics.png") }else if(bookmark["bookName"] == "Microeconomics"){ cell.bookImage.image = UIImage(named: "microecon.png") }else if(bookmark["bookName"]!.hasPrefix("Principles of Microeconomics for AP")){ cell.bookImage.image = UIImage(named: "microecon_ap.png") }else if(bookmark["bookName"] == "Macroeconomics"){ cell.bookImage.image = UIImage(named: "macroecon.png") }else if(bookmark["bookName"]!.hasPrefix("Principles of Macroeconomics for AP")){ cell.bookImage.image = UIImage(named: "macroecon_ap.png") }else if(bookmark["bookName"] == "College Physics"){ cell.bookImage.image = UIImage(named: "physics.png") }else if(bookmark["bookName"]!.hasPrefix("College Physics For AP")){ cell.bookImage.image = UIImage(named: "physics_ap.png") }else if(bookmark["bookName"] == "Prealgebra"){ cell.bookImage.image = UIImage(named: "prealgebra.jpeg") }else if(bookmark["bookName"] == "Precalculus"){ cell.bookImage.image = UIImage(named: "precalculus.png") }else if(bookmark["bookName"] == "Introduction to Sociology 2e"){ cell.bookImage.image = UIImage(named: "sociology.png") }else if(bookmark["bookName"] == "Introductory Statistics"){ cell.bookImage.image = UIImage(named: "statistics.png") }else if(bookmark["bookName"] == "U.S. History"){ cell.bookImage.image = UIImage(named: "us_history.png") }else if(bookmark["bookName"] == "Chemistry"){ cell.bookImage.image = UIImage(named: "chemistry.png") }else if(bookmark["bookName"] == "Psychology"){ cell.bookImage.image = UIImage(named: "psychology.png") }else{ print("Textbook not implemented") } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let bookmark = bookmarks[indexPath.row] as! [String:String] bookmarkURL = bookmark["url"] as String! performSegue(withIdentifier: "webView", sender: self) } // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false 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, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source - clear NSUserDefaults and repopulate bookmarks.removeObject(at: indexPath.row) UserDefaults.standard.removeObject(forKey: "bookmarks") UserDefaults.standard.set(bookmarks, forKey: "bookmarks") tableView.deleteRows(at: [indexPath], with: .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, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "webView") { let svc = segue.destination as! WebViewController; svc.bookmarkURL = self.bookmarkURL } } }
agpl-3.0
b62d4e7afe25115b6928ee35243fe893
44.5125
136
0.643917
4.556946
false
false
false
false
kylef/Spectre
Spectre.playground/Sources/Playground.swift
1
1313
class PlaygroundReporter : ContextReporter { var depth = 0 #if swift(>=3.0) func print(_ message: String) { let indentation = String(repeating: " ", count: depth * 2) Swift.print("\(indentation)\(message)") } #else func print(message: String) { let indentation = String(count: depth * 2, repeatedValue: " " as Character) Swift.print("\(indentation)\(message)") } #endif func report(_ name: String, closure: (ContextReporter) -> Void) { print("\(name):") depth += 1 closure(self) depth -= 1 print("") } func addSuccess(_ name: String) { print("✓ \(name)") } func addDisabled(_ name: String) { print("✱ \(name)") } func addFailure(_ name: String, failure: FailureType) { print("✗ \(name)") } } let reporter = PlaygroundReporter() #if swift(>=3.0) public func describe(_ name: String, closure: (ContextType) -> ()) { let context = Context(name: name) closure(context) context.run(reporter: reporter) } #else public func describe(name: String, closure: ContextType -> ()) { let context = Context(name: name) closure(context) context.run(reporter) } #endif public func it(name: String, closure: @escaping () throws -> ()) { let testCase = Case(name: name, closure: closure) testCase.run(reporter: reporter) }
bsd-2-clause
b9ed2472e0889f59e436ef946c6ef1ab
21.152542
79
0.634277
3.620499
false
false
false
false
SteveBarnegren/TweenKit
Example-iOS/Example/ClockView.swift
1
3661
// // ClockView.swift // Example // // Created by Steven Barnegren on 04/04/2017. // Copyright © 2017 Steve Barnegren. All rights reserved. // import UIKit class ClockView: UIView { // MARK: - Internal var hours = 15.0 { didSet{ drawView.redraw() } } var onScreenAmount = 1.0 { didSet{ drawView.redraw() } } var size = 1.0 { didSet{ drawView.redraw() } } var fillOpacity = CGFloat(0) { didSet{ drawView.redraw() } } var clockRect: CGRect { return CGRect(x: clockPosition.x - clockSize.width/2, y: clockPosition.y - clockSize.height/2, width: clockSize.width, height: clockSize.height) } init() { super.init(frame: UIScreen.main.bounds) drawView.drawClosure = { func handEndPoint(hours: Double, length: Double) -> CGPoint { let angle = ((Double.pi * 2) * hours/12.0) - Double.pi/2 let x = cos(angle) * length let y = sin(angle) * length return CGPoint(x: self.clockPosition.x + CGFloat(x), y: self.clockPosition.y + CGFloat(y)) } UIColor.white.set() let clockBounds = CGRect(x: self.clockPosition.x - (self.clockSize.width/2), y: self.clockPosition.y - (self.clockSize.height/2), width: self.clockSize.width, height: self.clockSize.height) let borderPath = UIBezierPath(ovalIn: clockBounds) borderPath.lineWidth = self.lineWidth borderPath.stroke() let hourHandEnd = handEndPoint(hours: self.hours, length: Double(self.clockSize.height/2) * 0.333) let minuteHandEnd = handEndPoint(hours: self.hours * 12, length: Double(self.clockSize.height/2) * 0.666) let handsPath = UIBezierPath() handsPath.move(to: hourHandEnd) handsPath.addLine(to: self.clockPosition) handsPath.addLine(to: minuteHandEnd) handsPath.lineWidth = self.lineWidth handsPath.lineJoinStyle = .round handsPath.lineCapStyle = .round handsPath.stroke() UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: self.fillOpacity).set() borderPath.fill() } addSubview(drawView) } // MARK: - Properties private let lineWidth = CGFloat(3) private var clockPosition: CGPoint { let min = CGPoint(x: UIScreen.main.bounds.size.width/2, y: UIScreen.main.bounds.size.height + (clockSize.height/2) + 10) let max = CGPoint(x: UIScreen.main.bounds.size.width/2, y: UIScreen.main.bounds.size.height/2) return min.lerp(t: onScreenAmount, end: max) } private var clockSize: CGSize { let sideLength = 120.0 * self.size return CGSize(width: sideLength, height: sideLength) } private let drawView: DrawClosureView = { let view = DrawClosureView() return view }() // MARK: - UIView required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() drawView.frame = bounds } }
mit
07657eb53e86cca38699a19a465f9c12
29.756303
117
0.52541
4.436364
false
false
false
false
KanChen2015/DRCRegistrationKit
DRCRegistrationKit/DRCRegistrationKit/DRCLoginPageViewController.swift
1
2969
// // DRCLoginPageViewController.swift // DRCRegistrationKit // // Created by Kan Chen on 6/6/16. // Copyright © 2016 drchrono. All rights reserved. // import UIKit class DRCLoginPageViewController: UIPageViewController, UIPageViewControllerDataSource { weak var loginDelegate: DRCLoginViewControllerDelegate? let imageResources = [ "panel_phone_ipadehr_front", "panel_phone_medicalbilling_front", "panel_phone_onpatient_front" ] private var cachedViewController: [UIViewController] = [] override func viewDidLoad() { super.viewDidLoad() for imageResource in imageResources { if let page = storyboard?.instantiateViewControllerWithIdentifier("welcomePage") as? DRCWelcomePage { page.image = UIImage(named: imageResource, inBundle: NSBundle(forClass: DRCLoginPageViewController.classForCoder()), compatibleWithTraitCollection: nil) cachedViewController.append(page) } } if let loginController = storyboard?.instantiateViewControllerWithIdentifier("login") as? DRCLoginViewController { loginController.delegate = loginDelegate cachedViewController.append(loginController) } let firstViewController = cachedViewController[0] setViewControllers([firstViewController], direction: .Forward, animated: false, completion: nil) dataSource = self } /* // 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. } */ // MARK: - PageViewController DataSource func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { guard let currentIndex = cachedViewController.indexOf(viewController) else { return nil } if currentIndex == 0 { return nil } return cachedViewController[currentIndex - 1] } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { guard let currentIndex = cachedViewController.indexOf(viewController) else { return nil } if currentIndex == cachedViewController.count - 1 { return nil } return cachedViewController[currentIndex + 1] } func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int { return cachedViewController.count } func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int { return 0 } }
mit
30b43d1c95322fbef9f5d63d335651c2
41.4
161
0.704515
5.785575
false
false
false
false
53ningen/todo
TODO/UI/SelectLabels/SelectLabelsViewController.swift
1
3480
import UIKit import RxSwift final class SelectLabelsViewController: BaseViewController { fileprivate lazy var viewModel: SelectLabelsViewModel = SelectLabelsViewModel() func setViewModel(_ viewModel: SelectLabelsViewModel) { self.viewModel = viewModel } @IBOutlet weak var tableView: UITableView! @IBOutlet weak var doneButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self tableView.registerNib(LabelCellView.self) // tableView上下の余計なスペースを除去するために必要 tableView.contentInset = UIEdgeInsets(top: -1, left: 0, bottom: 0, right: 0) tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0.1)) tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0.1)) if tableView.responds(to: #selector(getter: UITableViewCell.separatorInset)) { tableView.separatorInset = UIEdgeInsets.zero } if tableView.responds(to: #selector(getter: UIView.layoutMargins)) { tableView.layoutMargins = UIEdgeInsets.zero } navigationItem.title = "Select labels" } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) bind() subscribeEvents() viewModel.updateLabels() } private func bind() { tableView.rx.itemSelected.map { self.viewModel.labels.value.safeIndex($0.item) }.subscribe(onNext: viewModel.selectLabel).addDisposableTo(disposeBag) viewModel.labels.asObservable().map { _ in () }.subscribe(onNext: tableView.reloadData).addDisposableTo(disposeBag) } private func subscribeEvents() { tableView.rx.itemSelected .subscribe(onNext: { [weak self] indexPath in let accessory = self?.tableView.cellForRow(at: indexPath)?.accessoryType self?.tableView.cellForRow(at: indexPath)?.accessoryType = accessory == UITableViewCellAccessoryType.none ? .checkmark : .none self?.tableView.cellForRow(at: indexPath)?.isSelected = false }) .addDisposableTo(disposeBag) doneButton.rx.tap.single() .subscribe(onNext: { self.dismiss(animated: true, completion: nil) }) .addDisposableTo(disposeBag) } } extension SelectLabelsViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.labels.value.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: LabelCellView.cellReuseIdentifier, for: indexPath) viewModel.labels.value.safeIndex(indexPath.row).forEach { (cell as? LabelCellView)?.bind($0, titleOnly: true) cell.accessoryType = self.viewModel.isSelected($0) ? .checkmark : .none } return cell } } extension SelectLabelsViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 75 } @objc(tableView:commitEditingStyle:forRowAtIndexPath:) func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {} }
mit
14fd8e5ef2085952c424026a75f67d70
41.469136
183
0.682267
4.992743
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/HandyJSON/Source/Metadata.swift
2
11621
/* * Copyright 1999-2101 Alibaba Group. * * 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. */ // // Created by zhouzhuo on 07/01/2017. // struct _class_rw_t { var flags: Int32 var version: Int32 var ro: UInt // other fields we don't care func class_ro_t() -> UnsafePointer<_class_ro_t>? { return UnsafePointer<_class_ro_t>(bitPattern: self.ro) } } struct _class_ro_t { var flags: Int32 var instanceStart: Int32 var instanceSize: Int32 // other fields we don't care } // MARK: MetadataType protocol MetadataType : PointerType { static var kind: Metadata.Kind? { get } } extension MetadataType { var kind: Metadata.Kind { return Metadata.Kind(flag: UnsafePointer<Int>(pointer).pointee) } init?(anyType: Any.Type) { self.init(pointer: unsafeBitCast(anyType, to: UnsafePointer<Int>.self)) if let kind = type(of: self).kind, kind != self.kind { return nil } } } // MARK: Metadata struct Metadata : MetadataType { var pointer: UnsafePointer<Int> init(type: Any.Type) { self.init(pointer: unsafeBitCast(type, to: UnsafePointer<Int>.self)) } } struct _Metadata {} var is64BitPlatform: Bool { return MemoryLayout<Int>.size == MemoryLayout<Int64>.size } // MARK: Metadata + Kind // include/swift/ABI/MetadataKind.def let MetadataKindIsNonHeap = 0x200 let MetadataKindIsRuntimePrivate = 0x100 let MetadataKindIsNonType = 0x400 extension Metadata { static let kind: Kind? = nil enum Kind { case `struct` case `enum` case optional case opaque case foreignClass case tuple case function case existential case metatype case objCClassWrapper case existentialMetatype case heapLocalVariable case heapGenericLocalVariable case errorObject case `class` // The kind only valid for non-class metadata init(flag: Int) { switch flag { case (0 | MetadataKindIsNonHeap): self = .struct case (1 | MetadataKindIsNonHeap): self = .enum case (2 | MetadataKindIsNonHeap): self = .optional case (3 | MetadataKindIsNonHeap): self = .foreignClass case (0 | MetadataKindIsRuntimePrivate | MetadataKindIsNonHeap): self = .opaque case (1 | MetadataKindIsRuntimePrivate | MetadataKindIsNonHeap): self = .tuple case (2 | MetadataKindIsRuntimePrivate | MetadataKindIsNonHeap): self = .function case (3 | MetadataKindIsRuntimePrivate | MetadataKindIsNonHeap): self = .existential case (4 | MetadataKindIsRuntimePrivate | MetadataKindIsNonHeap): self = .metatype case (5 | MetadataKindIsRuntimePrivate | MetadataKindIsNonHeap): self = .objCClassWrapper case (6 | MetadataKindIsRuntimePrivate | MetadataKindIsNonHeap): self = .existentialMetatype case (0 | MetadataKindIsNonType): self = .heapLocalVariable case (0 | MetadataKindIsNonType | MetadataKindIsRuntimePrivate): self = .heapGenericLocalVariable case (1 | MetadataKindIsNonType | MetadataKindIsRuntimePrivate): self = .errorObject default: self = .class } } } } // MARK: Metadata + Class extension Metadata { struct Class : ContextDescriptorType { static let kind: Kind? = .class var pointer: UnsafePointer<_Metadata._Class> var isSwiftClass: Bool { get { // see include/swift/Runtime/Config.h macro SWIFT_CLASS_IS_SWIFT_MASK // it can be 1 or 2 depending on environment let lowbit = self.pointer.pointee.rodataPointer & 3 return lowbit != 0 } } var contextDescriptorOffsetLocation: Int { return is64BitPlatform ? 8 : 11 } var superclass: Class? { guard let superclass = pointer.pointee.superclass else { return nil } // If the superclass doesn't conform to handyjson/handyjsonenum protocol, // we should ignore the properties inside if !(superclass is HandyJSON.Type) && !(superclass is HandyJSONEnum.Type) { return nil } // ignore objc-runtime layer guard let metaclass = Metadata.Class(anyType: superclass) else { return nil } return metaclass } var vTableSize: Int { // memory size after ivar destroyer return Int(pointer.pointee.classObjectSize - pointer.pointee.classObjectAddressPoint) - (contextDescriptorOffsetLocation + 2) * MemoryLayout<Int>.size } // reference: https://github.com/apple/swift/blob/master/docs/ABI/TypeMetadata.rst#generic-argument-vector var genericArgumentVector: UnsafeRawPointer? { let pointer = UnsafePointer<Int>(self.pointer) var superVTableSize = 0 if let _superclass = self.superclass { superVTableSize = _superclass.vTableSize / MemoryLayout<Int>.size } let base = pointer.advanced(by: contextDescriptorOffsetLocation + 2 + superVTableSize) if base.pointee == 0 { return nil } return UnsafeRawPointer(base) } func _propertyDescriptionsAndStartPoint() -> ([Property.Description], Int32?)? { let instanceStart = pointer.pointee.class_rw_t()?.pointee.class_ro_t()?.pointee.instanceStart var result: [Property.Description] = [] if let fieldOffsets = self.fieldOffsets, let fieldRecords = self.reflectionFieldDescriptor?.fieldRecords { class NameAndType { var name: String? var type: Any.Type? } for i in 0..<self.numberOfFields { let name = fieldRecords[i].fieldName if let cMangledTypeName = fieldRecords[i].mangledTypeName, let fieldType = _getTypeByMangledNameInContext(cMangledTypeName, getMangledTypeNameSize(cMangledTypeName), genericContext: self.contextDescriptorPointer, genericArguments: self.genericArgumentVector) { result.append(Property.Description(key: name, type: fieldType, offset: fieldOffsets[i])) } } } if let superclass = superclass, String(describing: unsafeBitCast(superclass.pointer, to: Any.Type.self)) != "SwiftObject", // ignore the root swift object let superclassProperties = superclass._propertyDescriptionsAndStartPoint(), superclassProperties.0.count > 0 { return (superclassProperties.0 + result, superclassProperties.1) } return (result, instanceStart) } func propertyDescriptions() -> [Property.Description]? { let propsAndStp = _propertyDescriptionsAndStartPoint() if let firstInstanceStart = propsAndStp?.1, let firstProperty = propsAndStp?.0.first?.offset { return propsAndStp?.0.map({ (propertyDesc) -> Property.Description in let offset = propertyDesc.offset - firstProperty + Int(firstInstanceStart) return Property.Description(key: propertyDesc.key, type: propertyDesc.type, offset: offset) }) } else { return propsAndStp?.0 } } } } extension _Metadata { struct _Class { var kind: Int var superclass: Any.Type? var reserveword1: Int var reserveword2: Int var rodataPointer: UInt var classFlags: UInt32 var instanceAddressPoint: UInt32 var instanceSize: UInt32 var instanceAlignmentMask: UInt16 var runtimeReservedField: UInt16 var classObjectSize: UInt32 var classObjectAddressPoint: UInt32 var nominalTypeDescriptor: Int var ivarDestroyer: Int // other fields we don't care func class_rw_t() -> UnsafePointer<_class_rw_t>? { if MemoryLayout<Int>.size == MemoryLayout<Int64>.size { let fast_data_mask: UInt64 = 0x00007ffffffffff8 let databits_t: UInt64 = UInt64(self.rodataPointer) return UnsafePointer<_class_rw_t>(bitPattern: UInt(databits_t & fast_data_mask)) } else { return UnsafePointer<_class_rw_t>(bitPattern: self.rodataPointer & 0xfffffffc) } } } } // MARK: Metadata + Struct extension Metadata { struct Struct : ContextDescriptorType { static let kind: Kind? = .struct var pointer: UnsafePointer<_Metadata._Struct> var contextDescriptorOffsetLocation: Int { return 1 } var genericArgumentOffsetLocation: Int { return 2 } var genericArgumentVector: UnsafeRawPointer? { let pointer = UnsafePointer<Int>(self.pointer) let base = pointer.advanced(by: genericArgumentOffsetLocation) if base.pointee == 0 { return nil } return UnsafeRawPointer(base) } func propertyDescriptions() -> [Property.Description]? { guard let fieldOffsets = self.fieldOffsets, let fieldRecords = self.reflectionFieldDescriptor?.fieldRecords else { return [] } var result: [Property.Description] = [] class NameAndType { var name: String? var type: Any.Type? } for i in 0..<self.numberOfFields { let name = fieldRecords[i].fieldName if let cMangledTypeName = fieldRecords[i].mangledTypeName, let fieldType = _getTypeByMangledNameInContext(cMangledTypeName, getMangledTypeNameSize(cMangledTypeName), genericContext: self.contextDescriptorPointer, genericArguments: self.genericArgumentVector) { result.append(Property.Description(key: name, type: fieldType, offset: fieldOffsets[i])) } } return result } } } extension _Metadata { struct _Struct { var kind: Int var contextDescriptorOffset: Int var parent: Metadata? } } // MARK: Metadata + ObjcClassWrapper extension Metadata { struct ObjcClassWrapper: ContextDescriptorType { static let kind: Kind? = .objCClassWrapper var pointer: UnsafePointer<_Metadata._ObjcClassWrapper> var contextDescriptorOffsetLocation: Int { return is64BitPlatform ? 8 : 11 } var targetType: Any.Type? { get { return pointer.pointee.targetType } } } } extension _Metadata { struct _ObjcClassWrapper { var kind: Int var targetType: Any.Type? } }
mit
630fd768438c1d87566b79a599d29486
34.756923
225
0.61234
4.680226
false
false
false
false
stephentyrone/swift
validation-test/Reflection/reflect_UInt32.swift
3
1773
// RUN: %empty-directory(%t) // RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_UInt32 // RUN: %target-codesign %t/reflect_UInt32 // RUN: %target-run %target-swift-reflection-test %t/reflect_UInt32 | %FileCheck %s --check-prefix=CHECK-%target-ptrsize // REQUIRES: objc_interop // REQUIRES: executable_test // UNSUPPORTED: use_os_stdlib import SwiftReflectionTest class TestClass { var t: UInt32 init(t: UInt32) { self.t = t } } var obj = TestClass(t: 123) reflect(object: obj) // CHECK-64: Reflecting an object. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (class reflect_UInt32.TestClass) // CHECK-64: Type info: // CHECK-64: (class_instance size=20 alignment=4 stride=20 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=t offset=16 // CHECK-64: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))) // CHECK-32: Reflecting an object. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (class reflect_UInt32.TestClass) // CHECK-32: Type info: // CHECK-32: (class_instance size=12 alignment=4 stride=12 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=t offset=8 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))) doneReflecting() // CHECK-64: Done. // CHECK-32: Done.
apache-2.0
c5bba2a28edb125da5c998bfcd3da60d
33.096154
120
0.693739
3.105079
false
true
false
false
pkrll/ComicZipper-2
ComicZipper/Support/NotificationHelper.swift
2
1793
// // NotificationHelper.swift // ComicZipper // // Created by Ardalan Samimi on 04/01/16. // Copyright © 2016 Ardalan Samimi. All rights reserved. // import Cocoa class NotificationHelper { private static var notificationSound: String = Constants.General.notificationSoundName private static var userNotification: NSUserNotification { let notification = NSUserNotification() notification.title = Constants.Application.bundleName notification.soundName = self.notificationSound return notification } class func setBadgeLabel(label: String) { NSApplication.sharedApplication().dockTile.badgeLabel = label } class func clearBadgeLabel() { self.setBadgeLabel("") } class func deliverUserNotification(text: String) { let notification = self.userNotification notification.informativeText = text NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notification) } class func makeSound() { NSSound(named: self.notificationSound)?.play() } class func postNotification(notification: NotificationsType, sender: AnyObject?, userInfo: [NSObject: AnyObject]?) { NSNotificationCenter.defaultCenter().postNotificationName(notification.rawValue, object: sender, userInfo: userInfo) } class func registerObserver(observer: AnyObject, forNotification type: NotificationsType?, fromObject: AnyObject?, selector: Selector) { NSNotificationCenter.defaultCenter().addObserver(observer, selector: selector, name: type?.rawValue, object: fromObject) } class func unRegisterObserver(observer: AnyObject, forNotification type: NotificationsType?, object: AnyObject?) { NSNotificationCenter.defaultCenter().removeObserver(observer, name: type?.rawValue, object: object) } }
mit
9cddae616a41ec36ec970d28ef823964
34.156863
138
0.762835
5.090909
false
false
false
false
benlangmuir/swift
test/Distributed/distributed_actor_isolation.swift
4
10571
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/Inputs/FakeDistributedActorSystems.swift // RUN: %target-swift-frontend -typecheck -verify -verify-ignore-unknown -disable-availability-checking -I %t 2>&1 %s // REQUIRES: concurrency // REQUIRES: distributed // TODO(distributed): rdar://82419661 remove -verify-ignore-unknown here, no warnings should be emitted for our // generated code but right now a few are, because of Sendability checks -- need to track it down more. import Distributed import FakeDistributedActorSystems @available(SwiftStdlib 5.5, *) typealias DefaultDistributedActorSystem = FakeActorSystem // ==== ---------------------------------------------------------------------------------------------------------------- actor LocalActor_1 { let name: String = "alice" var mutable: String = "" distributed func nope() { // expected-error@-1{{'distributed' method can only be declared within 'distributed actor'}} } } struct NotCodableValue { } distributed actor DistributedActor_1 { let name: String = "alice" // expected-note{{access to property 'name' is only permitted within distributed actor 'DistributedActor_1'}} var mutable: String = "alice" // expected-note{{access to property 'mutable' is only permitted within distributed actor 'DistributedActor_1'}} var computedMutable: String { get { "hey" } set { _ = newValue } } distributed let letProperty: String = "" // expected-error{{property 'letProperty' cannot be 'distributed', only computed properties can}} distributed var varProperty: String = "" // expected-error{{property 'varProperty' cannot be 'distributed', only computed properties can}} distributed var computed: String { "computed" } distributed var computedNotCodable: NotCodableValue { // expected-error{{result type 'NotCodableValue' of distributed property 'computedNotCodable' does not conform to serialization requirement 'Codable'}} .init() } distributed var getSet: String { // expected-error{{'distributed' computed property 'getSet' cannot have setter}} get { "computed" } set { _ = newValue } } distributed static func distributedStatic() {} // expected-error{{'distributed' method cannot be 'static'}} distributed class func distributedClass() {} // expected-error@-1{{class methods are only allowed within classes; use 'static' to declare a static method}} // expected-error@-2{{'distributed' method cannot be 'static'}} func hello() {} // expected-note{{distributed actor-isolated instance method 'hello()' declared here}} func helloAsync() async {} // expected-note{{distributed actor-isolated instance method 'helloAsync()' declared here}} func helloAsyncThrows() async throws {} // expected-note{{distributed actor-isolated instance method 'helloAsyncThrows()' declared here}} distributed func distHello() { } // ok distributed func distHelloAsync() async { } // ok distributed func distHelloThrows() throws { } // ok distributed func distHelloAsyncThrows() async throws { } // ok distributed func distInt() async throws -> Int { 42 } // ok distributed func distInt(int: Int) async throws -> Int { int } // ok distributed func distIntString(int: Int, two: String) async throws -> (String) { "\(int) + \(two)" } // ok distributed func dist(notCodable: NotCodableValue) async throws { // expected-error@-1 {{parameter 'notCodable' of type 'NotCodableValue' in distributed instance method does not conform to serialization requirement 'Codable'}} } distributed func distBadReturn(int: Int) async throws -> NotCodableValue { // expected-error@-1 {{result type 'NotCodableValue' of distributed instance method 'distBadReturn' does not conform to serialization requirement 'Codable'}} fatalError() } distributed func varargs(int: Int...) { // expected-error@-1{{cannot declare variadic argument 'int' in distributed instance method 'varargs(int:)'}} } distributed func closure(close: () -> String) { // expected-error@-1{{parameter 'close' of type '() -> String' in distributed instance method does not conform to serialization requirement 'Codable'}} } distributed func noInout(inNOut burger: inout String) { // expected-error@-1{{cannot declare 'inout' argument 'burger' in distributed instance method 'noInout(inNOut:)'}}{{43-49=}} } distributed func distReturnGeneric<T: Codable & Sendable>(item: T) async throws -> T { // ok item } distributed func distReturnGenericWhere<T: Sendable>(item: Int) async throws -> T where T: Codable { // ok fatalError() } distributed func distBadReturnGeneric<T: Sendable>(int: Int) async throws -> T { // expected-error@-1 {{result type 'T' of distributed instance method 'distBadReturnGeneric' does not conform to serialization requirement 'Codable'}} fatalError() } distributed func distGenericParam<T: Codable & Sendable>(value: T) async throws { // ok fatalError() } distributed func distGenericParamWhere<T: Sendable>(value: T) async throws -> T where T: Codable { // ok value } distributed func distBadGenericParam<T: Sendable>(int: T) async throws { // expected-error@-1 {{parameter 'int' of type 'T' in distributed instance method does not conform to serialization requirement 'Codable'}} fatalError() } static func staticFunc() -> String { "" } // ok @MainActor static func staticMainActorFunc() -> String { "" } // ok static distributed func staticDistributedFunc() -> String { // expected-error@-1{{'distributed' method cannot be 'static'}}{10-21=} fatalError() } func test_inside() async throws { _ = self.name _ = self.computedMutable _ = try await self.distInt() _ = try await self.distInt(int: 42) self.hello() _ = await self.helloAsync() _ = try await self.helloAsyncThrows() self.distHello() await self.distHelloAsync() try self.distHelloThrows() try await self.distHelloAsyncThrows() // Hops over to the global actor. _ = await DistributedActor_1.staticMainActorFunc() } } func test_outside( local: LocalActor_1, distributed: DistributedActor_1 ) async throws { // ==== properties _ = distributed.id // ok distributed.id = ActorAddress(parse: "mock://1.1.1.1:8080/#123121") // expected-error{{cannot assign to property: 'id' is immutable}} _ = local.name // ok, special case that let constants are okey let _: String = local.mutable // ok, special case that let constants are okey _ = distributed.name // expected-error{{distributed actor-isolated property 'name' can not be accessed from a non-isolated context}} _ = distributed.mutable // expected-error{{distributed actor-isolated property 'mutable' can not be accessed from a non-isolated context}} // ==== special properties (nonisolated, implicitly replicated) // the distributed actor's special fields may always be referred to _ = distributed.id _ = distributed.actorSystem // ==== static functions _ = distributed.staticFunc() // expected-error{{static member 'staticFunc' cannot be used on instance of type 'DistributedActor_1'}} _ = DistributedActor_1.staticFunc() // ==== non-distributed functions distributed.hello() // expected-error{{only 'distributed' instance methods can be called on a potentially remote distributed actor}} _ = await distributed.helloAsync() // expected-error{{only 'distributed' instance methods can be called on a potentially remote distributed actor}} _ = try await distributed.helloAsyncThrows() // expected-error{{only 'distributed' instance methods can be called on a potentially remote distributed actor}} } // ==== Protocols and static (non isolated functions) protocol P { static func hello() -> String } extension P { static func hello() -> String { "" } } distributed actor ALL: P { } // ==== Codable parameters and return types ------------------------------------ func test_params( distributed: DistributedActor_1 ) async throws { _ = try await distributed.distInt() // ok _ = try await distributed.distInt(int: 42) // ok _ = try await distributed.dist(notCodable: .init()) } // Actor initializer isolation (through typechecking only!) distributed actor DijonMustard { nonisolated init(system: FakeActorSystem) {} // expected-warning {{'nonisolated' on an actor's synchronous initializer is invalid; this is an error in Swift 6}} {{3-15=}} convenience init(conv: FakeActorSystem) { // expected-warning {{initializers in actors are not marked with 'convenience'; this is an error in Swift 6}}{{3-15=}} self.init(system: conv) self.f() // expected-error {{actor-isolated instance method 'f()' can not be referenced from a non-isolated context}} } func f() {} // expected-note {{distributed actor-isolated instance method 'f()' declared here}} nonisolated init(conv2: FakeActorSystem) { // expected-warning {{'nonisolated' on an actor's synchronous initializer is invalid; this is an error in Swift 6}} {{3-15=}} self.init(system: conv2) } } // ==== Larger example with protocols and extensions --------------------------- protocol Greeting: DistributedActor { distributed func greeting() -> String distributed func greetingAsyncThrows() async throws -> String } extension Greeting { func greetLocal(name: String) async throws { // expected-note{{distributed actor-isolated instance method 'greetLocal(name:)' declared here}} try await print("\(greetingAsyncThrows()), \(name)!") // requirement is async throws, things work } func greetLocal2(name: String) { print("\(greeting()), \(name)!") } } extension Greeting where SerializationRequirement == Codable { // okay, uses Codable to transfer arguments. distributed func greetDistributed(name: String) async throws { // okay, we're on the actor try await greetLocal(name: name) } distributed func greetDistributed2(name: String) async throws { // okay, we're on the actor greetLocal2(name: name) } func greetDistributedNon(name: String) async throws { // okay, we're on the actor greetLocal2(name: name) } } extension Greeting where SerializationRequirement == Codable { nonisolated func greetAliceALot() async throws { try await greetLocal(name: "Alice") // expected-error{{only 'distributed' instance methods can be called on a potentially remote distributed actor}} } }
apache-2.0
ce1e05eab925389086146563cd005481
39.814672
219
0.702677
4.357378
false
false
false
false
loudnate/Loop
Learn/Models/TimeComponents.swift
1
2081
// // TimeComponents.swift // Learn // // Copyright © 2019 LoopKit Authors. All rights reserved. // import Foundation struct TimeComponents: Equatable, Hashable { let hour: Int let minute: Int init(hour: Int, minute: Int) { if hour >= 24, minute >= 60 { assertionFailure("Invalid time components: \(hour):\(minute)") } self.hour = hour self.minute = minute } init?(dateComponents: DateComponents) { guard let hour = dateComponents.hour, let minute = dateComponents.minute else { return nil } self.init(hour: hour, minute: minute) } init(timeIntervalSinceMidnight timeInterval: TimeInterval) { self.init(hour: Int(timeInterval.hours), minute: Int(timeInterval.minutes) % 60) } var dateComponents: DateComponents { return DateComponents(hour: hour, minute: minute, second: 0) } var timeIntervalSinceMidnight: TimeInterval { return TimeInterval(hours: Double(hour)) + TimeInterval(minutes: Double(minute)) } func floored(to timeInterval: TimeInterval) -> TimeComponents { let floored = floor(timeIntervalSinceMidnight / timeInterval) * timeInterval return TimeComponents(timeIntervalSinceMidnight: floored) } func bucket(withBucketSize bucketSize: TimeInterval) -> Range<TimeComponents> { let lowerBound = floored(to: bucketSize) return lowerBound..<(lowerBound + bucketSize) } private func adding(_ timeInterval: TimeInterval) -> TimeComponents { return TimeComponents(timeIntervalSinceMidnight: timeIntervalSinceMidnight + timeInterval) } } extension TimeComponents: Comparable { static func < (lhs: TimeComponents, rhs: TimeComponents) -> Bool { if lhs.hour == rhs.hour { return lhs.minute < rhs.minute } else { return lhs.hour < rhs.hour } } } extension TimeComponents { static func + (lhs: TimeComponents, rhs: TimeInterval) -> TimeComponents { return lhs.adding(rhs) } }
apache-2.0
0f1e14981cacc4083cf23065aa5d5968
27.493151
98
0.654808
4.632517
false
false
false
false
benlangmuir/swift
test/Sema/enum_conformance_synthesis.swift
9
12423
// RUN: %target-swift-frontend -typecheck -verify -primary-file %s %S/Inputs/enum_conformance_synthesis_other.swift -verify-ignore-unknown -swift-version 4 var hasher = Hasher() enum Foo: CaseIterable { case A, B } func foo() { if Foo.A == .B { } var _: Int = Foo.A.hashValue Foo.A.hash(into: &hasher) _ = Foo.allCases Foo.A == Foo.B // expected-warning {{result of operator '==' is unused}} } enum Generic<T>: CaseIterable { case A, B static func method() -> Int { // Test synthesis of == without any member lookup being done if A == B { } return Generic.A.hashValue } } func generic() { if Generic<Foo>.A == .B { } var _: Int = Generic<Foo>.A.hashValue Generic<Foo>.A.hash(into: &hasher) _ = Generic<Foo>.allCases } func localEnum() -> Bool { enum Local { case A, B } return Local.A == .B } enum CustomHashable { case A, B func hash(into hasher: inout Hasher) {} } func ==(x: CustomHashable, y: CustomHashable) -> Bool { return true } func customHashable() { if CustomHashable.A == .B { } var _: Int = CustomHashable.A.hashValue CustomHashable.A.hash(into: &hasher) } // We still synthesize conforming overloads of '==' and 'hashValue' if // explicit definitions don't satisfy the protocol requirements. Probably // not what we actually want. enum InvalidCustomHashable { case A, B var hashValue: String { return "" } } func ==(x: InvalidCustomHashable, y: InvalidCustomHashable) -> String { return "" } func invalidCustomHashable() { if InvalidCustomHashable.A == .B { } var s: String = InvalidCustomHashable.A == .B s = InvalidCustomHashable.A.hashValue _ = s var _: Int = InvalidCustomHashable.A.hashValue InvalidCustomHashable.A.hash(into: &hasher) } // Check use of an enum's synthesized members before the enum is actually declared. struct UseEnumBeforeDeclaration { let eqValue = EnumToUseBeforeDeclaration.A == .A let hashValue = EnumToUseBeforeDeclaration.A.hashValue } enum EnumToUseBeforeDeclaration { case A } func getFromOtherFile() -> AlsoFromOtherFile { return .A } func overloadFromOtherFile() -> YetAnotherFromOtherFile { return .A } func overloadFromOtherFile() -> Bool { return false } func useEnumBeforeDeclaration() { // Check enums from another file in the same module. if FromOtherFile.A == .A {} let _: Int = FromOtherFile.A.hashValue if .A == getFromOtherFile() {} if .A == overloadFromOtherFile() {} } // Complex enums are not automatically Equatable, Hashable, or CaseIterable. enum Complex { case A(Int) case B } func complex() { if Complex.A(1) == .B { } // expected-error{{cannot convert value of type 'Complex' to expected argument type 'CustomHashable'}} } // Enums with equatable payloads are equatable if they explicitly conform. enum EnumWithEquatablePayload: Equatable { case A(Int) case B(String, Int) case C } func enumWithEquatablePayload() { if EnumWithEquatablePayload.A(1) == .B("x", 1) { } if EnumWithEquatablePayload.A(1) == .C { } if EnumWithEquatablePayload.B("x", 1) == .C { } } // Enums with hashable payloads are hashable if they explicitly conform. enum EnumWithHashablePayload: Hashable { case A(Int) case B(String, Int) case C } func enumWithHashablePayload() { _ = EnumWithHashablePayload.A(1).hashValue _ = EnumWithHashablePayload.B("x", 1).hashValue _ = EnumWithHashablePayload.C.hashValue EnumWithHashablePayload.A(1).hash(into: &hasher) EnumWithHashablePayload.B("x", 1).hash(into: &hasher) EnumWithHashablePayload.C.hash(into: &hasher) // ...and they should also inherit equatability from Hashable. if EnumWithHashablePayload.A(1) == .B("x", 1) { } if EnumWithHashablePayload.A(1) == .C { } if EnumWithHashablePayload.B("x", 1) == .C { } } // Enums with non-hashable payloads don't derive conformance. struct NotHashable {} enum EnumWithNonHashablePayload: Hashable { // expected-error 2 {{does not conform}} case A(NotHashable) //expected-note {{associated value type 'NotHashable' does not conform to protocol 'Hashable', preventing synthesized conformance of 'EnumWithNonHashablePayload' to 'Hashable'}} // expected-note@-1 {{associated value type 'NotHashable' does not conform to protocol 'Equatable', preventing synthesized conformance of 'EnumWithNonHashablePayload' to 'Equatable'}} } // Enums should be able to derive conformances based on the conformances of // their generic arguments. enum GenericHashable<T: Hashable>: Hashable { case A(T) case B } func genericHashable() { if GenericHashable<String>.A("a") == .B { } var _: Int = GenericHashable<String>.A("a").hashValue } // But it should be an error if the generic argument doesn't have the necessary // constraints to satisfy the conditions for derivation. enum GenericNotHashable<T: Equatable>: Hashable { // expected-error 2 {{does not conform to protocol 'Hashable'}} case A(T) //expected-note 2 {{associated value type 'T' does not conform to protocol 'Hashable', preventing synthesized conformance of 'GenericNotHashable<T>' to 'Hashable'}} case B } func genericNotHashable() { if GenericNotHashable<String>.A("a") == .B { } let _: Int = GenericNotHashable<String>.A("a").hashValue // No error. hashValue is always synthesized, even if Hashable derivation fails GenericNotHashable<String>.A("a").hash(into: &hasher) // expected-error {{value of type 'GenericNotHashable<String>' has no member 'hash'}} } enum GenericNotHashable2<T: Equatable, U: Hashable>: Hashable { // expected-error@-1 {{type 'GenericNotHashable2' does not conform to protocol 'Hashable'}} case A(U, T) // expected-note {{associated value type 'T' does not conform to protocol 'Hashable', preventing synthesized conformance of 'GenericNotHashable2<T, U>' to 'Hashable'}} case B } // An enum with no cases should also derive conformance. enum NoCases: Hashable {} // rdar://19773050 private enum Bar<T> { case E(Unknown<T>) // expected-error {{cannot find type 'Unknown' in scope}} mutating func value() -> T { switch self { // FIXME: Should diagnose here that '.' needs to be inserted, but E has an ErrorType at this point case E(let x): return x.value } } } // Equatable extension -- rdar://20981254 enum Instrument { case Piano case Violin case Guitar } extension Instrument : Equatable {} extension Instrument : CaseIterable {} enum UnusedGeneric<T> { case a, b, c } extension UnusedGeneric : CaseIterable {} // Explicit conformance should work too public enum Medicine { case Antibiotic case Antihistamine } extension Medicine : Equatable {} public func ==(lhs: Medicine, rhs: Medicine) -> Bool { return true } // No explicit conformance; but it can be derived, for the same-file cases. enum Complex2 { case A(Int) case B } extension Complex2 : Hashable {} extension Complex2 : CaseIterable {} // expected-error {{type 'Complex2' does not conform to protocol 'CaseIterable'}} extension FromOtherFile: CaseIterable {} // expected-error {{extension outside of file declaring enum 'FromOtherFile' prevents automatic synthesis of 'allCases' for protocol 'CaseIterable'}} extension CaseIterableAcrossFiles: CaseIterable { public static var allCases: [CaseIterableAcrossFiles] { return [ .A ] } } // No explicit conformance and it cannot be derived. enum NotExplicitlyHashableAndCannotDerive { case A(NotHashable) //expected-note {{associated value type 'NotHashable' does not conform to protocol 'Hashable', preventing synthesized conformance of 'NotExplicitlyHashableAndCannotDerive' to 'Hashable'}} // expected-note@-1 {{associated value type 'NotHashable' does not conform to protocol 'Equatable', preventing synthesized conformance of 'NotExplicitlyHashableAndCannotDerive' to 'Equatable'}} } extension NotExplicitlyHashableAndCannotDerive : Hashable {} // expected-error 2 {{does not conform}} extension NotExplicitlyHashableAndCannotDerive : CaseIterable {} // expected-error {{does not conform}} // Verify that conformance (albeit manually implemented) can still be added to // a type in a different file. extension OtherFileNonconforming: Hashable { static func ==(lhs: OtherFileNonconforming, rhs: OtherFileNonconforming) -> Bool { return true } func hash(into hasher: inout Hasher) {} } // ...but synthesis in a type defined in another file doesn't work yet. extension YetOtherFileNonconforming: Equatable {} // expected-error {{extension outside of file declaring enum 'YetOtherFileNonconforming' prevents automatic synthesis of '==' for protocol 'Equatable'}} extension YetOtherFileNonconforming: CaseIterable {} // expected-error {{does not conform}} // Verify that an indirect enum doesn't emit any errors as long as its "leaves" // are conformant. enum StringBinaryTree: Hashable { indirect case tree(StringBinaryTree, StringBinaryTree) case leaf(String) } // Add some generics to make it more complex. enum BinaryTree<Element: Hashable>: Hashable { indirect case tree(BinaryTree, BinaryTree) case leaf(Element) } // Verify mutually indirect enums. enum MutuallyIndirectA: Hashable { indirect case b(MutuallyIndirectB) case data(Int) } enum MutuallyIndirectB: Hashable { indirect case a(MutuallyIndirectA) case data(Int) } // Verify that it works if the enum itself is indirect, rather than the cases. indirect enum TotallyIndirect: Hashable { case another(TotallyIndirect) case end(Int) } // Check the use of conditional conformances. enum ArrayOfEquatables : Equatable { case only([Int]) } struct NotEquatable { } enum ArrayOfNotEquatables : Equatable { // expected-error{{type 'ArrayOfNotEquatables' does not conform to protocol 'Equatable'}} case only([NotEquatable]) //expected-note {{associated value type '[NotEquatable]' does not conform to protocol 'Equatable', preventing synthesized conformance of 'ArrayOfNotEquatables' to 'Equatable'}} } // Conditional conformances should be able to be synthesized enum GenericDeriveExtension<T> { case A(T) } extension GenericDeriveExtension: Equatable where T: Equatable {} extension GenericDeriveExtension: Hashable where T: Hashable {} // Incorrectly/insufficiently conditional shouldn't work enum BadGenericDeriveExtension<T> { case A(T) //expected-note {{associated value type 'T' does not conform to protocol 'Hashable', preventing synthesized conformance of 'BadGenericDeriveExtension<T>' to 'Hashable'}} //expected-note@-1 {{associated value type 'T' does not conform to protocol 'Equatable', preventing synthesized conformance of 'BadGenericDeriveExtension<T>' to 'Equatable'}} } extension BadGenericDeriveExtension: Equatable {} // // expected-error@-1 {{type 'BadGenericDeriveExtension<T>' does not conform to protocol 'Equatable'}} extension BadGenericDeriveExtension: Hashable where T: Equatable {} // expected-error@-1 {{type 'BadGenericDeriveExtension' does not conform to protocol 'Hashable'}} // But some cases don't need to be conditional, even if they look similar to the // above struct AlwaysHashable<T>: Hashable {} enum UnusedGenericDeriveExtension<T> { case A(AlwaysHashable<T>) } extension UnusedGenericDeriveExtension: Hashable {} // Cross-file synthesis is disallowed for conditional cases just as it is for // non-conditional ones. extension GenericOtherFileNonconforming: Equatable where T: Equatable {} // expected-error@-1{{extension outside of file declaring generic enum 'GenericOtherFileNonconforming' prevents automatic synthesis of '==' for protocol 'Equatable'}} // rdar://problem/41852654 // There is a conformance to Equatable (or at least, one that implies Equatable) // in the same file as the type, so the synthesis is okay. Both orderings are // tested, to catch choosing extensions based on the order of the files, etc. protocol ImplierMain: Equatable {} enum ImpliedMain: ImplierMain { case a(Int) } extension ImpliedOther: ImplierMain {} // FIXME: Remove -verify-ignore-unknown. // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(Foo, Foo) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '<T> (Generic<T>, Generic<T>) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(InvalidCustomHashable, InvalidCustomHashable) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(EnumToUseBeforeDeclaration, EnumToUseBeforeDeclaration) -> Bool'
apache-2.0
2a57632ce017e6c6cb8d54b1aed60574
35.008696
209
0.738388
4.026904
false
false
false
false
Erickson0806/AdaptivePhotos
AdaptivePhotosUsingUIKitTraitsandSizeClasses/AdaptiveStoryboard/AdaptiveStoryboard/User.swift
2
1087
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The top level model object. Manages a list of conversations and the user's profile. */ import Foundation struct User { // MARK: Properties var name = "" var conversations = [Conversation]() var lastPhoto: Photo? // MARK: Initialization init() { } init?(dictionary: [String: AnyObject]) { guard let name = dictionary["name"] as? String else { return nil } self.name = name if let conversationDictionaries = dictionary["conversations"] as? [[String: AnyObject]] { conversations = conversationDictionaries.flatMap { conversationDictionary in return Conversation(dictionary: conversationDictionary) } } else { conversations = [] } if let lastPhotoDictionary = dictionary["lastPhoto"] as? [String: AnyObject] { lastPhoto = Photo(dictionary: lastPhotoDictionary) } } }
apache-2.0
ab2816c309ea238d34c382033d767246
26.125
97
0.617512
5
false
false
false
false
ktmswzw/FeelingClientBySwift
Pods/IBAnimatable/IBAnimatable/Animatable.swift
1
24467
// // Created by Jake Lin on 11/19/15. // Copyright © 2015 Jake Lin. All rights reserved. // import UIKit public typealias AnimatableCompletion = () -> Void public typealias AnimatableExecution = () -> Void public protocol Animatable: class { /** String value of `AnimationType` enum */ var animationType: String? { get set } /** Auto run flag, if `true` it will automatically start animation when `layoutSubviews`. Default should be `true` */ var autoRun: Bool { get set } /** Animation duration (in seconds) */ var duration: Double { get set } /** Animation delay (in seconds, default value should be 0) */ var delay: Double { get set } /** Spring animation damping (0 ~ 1, default value should be 0.7) */ var damping: CGFloat { get set } /** Spring animation velocity (default value should be 0.7) */ var velocity: CGFloat { get set } /** Animation force (default value should be 1) */ var force: CGFloat { get set } /** Repeat count for Shake, Pop, Morph, Squeeze, Flash, Wobble and Swing animations */ var repeatCount: Float { get set } /** x position for MoveTo animation */ var x: CGFloat { get set } /** y position for MoveTo animation */ var y: CGFloat { get set } } public extension Animatable where Self: UIView { public func configAnimatableProperties() { // Apply default values if duration.isNaN { duration = 0.7 } if delay.isNaN { delay = 0 } if damping.isNaN { damping = 0.7 } if velocity.isNaN { velocity = 0.7 } if force.isNaN { force = 1 } if repeatCount.isNaN { repeatCount = 1 } } public func animate(completion: AnimatableCompletion? = nil) { guard let unwrappedAnimationTypeString = animationType, animationType = AnimationType(rawValue: unwrappedAnimationTypeString) else { return } switch animationType { case .SlideInLeft: slideInLeft(completion) case .SlideInRight: slideInRight(completion) case .SlideInDown: slideInDown(completion) case .SlideInUp: slideInUp(completion) case .SlideOutLeft: slideOutLeft(completion) case .SlideOutRight: slideOutRight(completion) case .SlideOutDown: slideOutDown(completion) case .SlideOutUp: slideOutUp(completion) case .SqueezeInLeft: squeezeInLeft(completion) case .SqueezeInRight: squeezeInRight(completion) case .SqueezeInDown: squeezeInDown(completion) case .SqueezeInUp: squeezeInUp(completion) case .SqueezeOutLeft: squeezeOutLeft(completion) case .SqueezeOutRight: squeezeOutRight(completion) case .SqueezeOutDown: squeezeOutDown(completion) case .SqueezeOutUp: squeezeOutUp(completion) case .FadeIn: fadeIn(completion) case .FadeOut: fadeOut(completion) case .FadeOutIn: fadeOutIn(completion) case .FadeInOut: fadeInOut(completion) case .FadeInLeft: fadeInLeft(completion) case .FadeInRight: fadeInRight(completion) case .FadeInDown: fadeInDown(completion) case .FadeInUp: fadeInUp(completion) case .FadeOutLeft: fadeOutLeft(completion) case .FadeOutRight: fadeOutRight(completion) case .FadeOutDown: fadeOutDown(completion) case .FadeOutUp: fadeOutUp(completion) case .SqueezeFadeInLeft: squeezeFadeInLeft() case .SqueezeFadeInRight: squeezeFadeInRight() case .SqueezeFadeInDown: squeezeFadeInDown() case .SqueezeFadeInUp: squeezeFadeInUp() case .SqueezeFadeOutLeft: squeezeFadeOutLeft() case .SqueezeFadeOutRight: squeezeFadeOutRight() case .SqueezeFadeOutDown: squeezeFadeOutDown() case .SqueezeFadeOutUp: squeezeFadeOutUp() case .ZoomIn: zoomIn(completion) case .ZoomOut: zoomOut(completion) case .Shake: shake(completion) case .Pop: pop(completion) case .FlipX: flipX(completion) case .FlipY: flipY(completion) case .Morph: morph(completion) case .Squeeze: squeeze(completion) case .Flash: flash(completion) case .Wobble: wobble(completion) case .Swing: swing(completion) case .Rotate: rotate(completion: completion) case .RotateCCW: rotate(clockwise: false, completion: completion) case .MoveTo: moveTo(completion) case .MoveBy: moveBy(completion) } } /** `autoRunAnimation` method, should be called in layoutSubviews() method */ func autoRunAnimation() { if autoRun { autoRun = false animate() } } // MARK: - Animation methods public func slideInLeft(completion: AnimatableCompletion? = nil) { let x = -screenSize().width * force animateInWithX(x, completion: completion) } public func slideInRight(completion: AnimatableCompletion? = nil) { let x = screenSize().width * force animateInWithX(x, completion: completion) } public func slideInDown(completion: AnimatableCompletion? = nil) { let y = -screenSize().height * force animateInWithY(y, completion: completion) } public func slideInUp(completion: AnimatableCompletion? = nil) { let y = screenSize().height * force animateInWithY(y, completion: completion) } public func slideOutLeft(completion: AnimatableCompletion? = nil) { let x = -screenSize().width * force animateOutWithX(x, alpha: 1, completion: completion) } public func slideOutRight(completion: AnimatableCompletion? = nil) { let x = screenSize().width * force animateOutWithX(x, alpha: 1, completion: completion) } public func slideOutDown(completion: AnimatableCompletion? = nil) { let y = screenSize().height * force animateOutWithY(y, alpha: 1, completion: completion) } public func slideOutUp(completion: AnimatableCompletion? = nil) { let y = -screenSize().height * force animateOutWithY(y, alpha: 1, completion: completion) } public func squeezeInLeft(completion: AnimatableCompletion? = nil) { let x = -screenSize().width * force let scaleX = 3 * force animateInWithX(x, scaleX: scaleX, completion: completion) } public func squeezeInRight(completion: AnimatableCompletion? = nil) { let x = screenSize().width * force let scaleX = 3 * force animateInWithX(x, scaleX: scaleX, completion: completion) } public func squeezeInDown(completion: AnimatableCompletion? = nil) { let y = -screenSize().height * force let scaleY = 3 * force animateInWithY(y, scaleY: scaleY, completion: completion) } public func squeezeInUp(completion: AnimatableCompletion? = nil) { let y = screenSize().height * force let scaleY = 3 * force animateInWithY(y, scaleY: scaleY, completion: completion) } public func squeezeOutLeft(completion: AnimatableCompletion? = nil) { let x = -screenSize().width * force let scaleX = 3 * force animateOutWithX(x, scaleX: scaleX, alpha: 1, completion: completion) } public func squeezeOutRight(completion: AnimatableCompletion? = nil) { let x = screenSize().width * force let scaleX = 3 * force animateOutWithX(x, scaleX: scaleX, alpha: 1, completion: completion) } public func squeezeOutDown(completion: AnimatableCompletion? = nil) { let y = screenSize().height * force let scaleY = 3 * force animateOutWithY(y, scaleY: scaleY, alpha: 1, completion: completion) } public func squeezeOutUp(completion: AnimatableCompletion? = nil) { let y = -screenSize().height * force let scaleY = 3 * force animateOutWithY(y, scaleY: scaleY, alpha: 1, completion: completion) } public func fadeInLeft(completion: AnimatableCompletion? = nil) { alpha = 0 slideInLeft(completion) } public func fadeInRight(completion: AnimatableCompletion? = nil) { alpha = 0 slideInRight(completion) } public func fadeInDown(completion: AnimatableCompletion? = nil) { alpha = 0 slideInDown(completion) } public func fadeInUp(completion: AnimatableCompletion? = nil) { alpha = 0 slideInUp(completion) } public func fadeOutLeft(completion: AnimatableCompletion? = nil) { let x = -screenSize().width * force animateOutWithX(x, alpha: 0, completion: completion) } public func fadeOutRight(completion: AnimatableCompletion? = nil) { let x = screenSize().width * force animateOutWithX(x, alpha: 0, completion: completion) } public func fadeOutDown(completion: AnimatableCompletion? = nil) { let y = screenSize().height * force animateOutWithY(y, alpha: 0, completion: completion) } public func fadeOutUp(completion: AnimatableCompletion? = nil) { let y = -screenSize().height * force animateOutWithY(y, alpha: 0, completion: completion) } public func squeezeFadeInLeft(completion: AnimatableCompletion? = nil) { alpha = 0 squeezeInLeft(completion) } public func squeezeFadeInRight(completion: AnimatableCompletion? = nil) { alpha = 0 squeezeInRight(completion) } public func squeezeFadeInDown(completion: AnimatableCompletion? = nil) { alpha = 0 squeezeInDown(completion) } public func squeezeFadeInUp(completion: AnimatableCompletion? = nil) { alpha = 0 squeezeInUp(completion) } public func squeezeFadeOutLeft(completion: AnimatableCompletion? = nil) { let x = -screenSize().width * force let scaleX = 3 * force animateOutWithX(x, scaleX: scaleX, alpha: 0, completion: completion) } public func squeezeFadeOutRight(completion: AnimatableCompletion? = nil) { let x = screenSize().width * force let scaleX = 3 * force animateOutWithX(x, scaleX: scaleX, alpha: 0, completion: completion) } public func squeezeFadeOutDown(completion: AnimatableCompletion? = nil) { let y = screenSize().height * force let scaleY = 3 * force animateOutWithY(y, scaleY: scaleY, alpha: 0, completion: completion) } public func squeezeFadeOutUp(completion: AnimatableCompletion? = nil) { let y = -screenSize().height * force let scaleY = 3 * force animateOutWithY(y, scaleY: scaleY, alpha: 0, completion: completion) } public func fadeIn(completion: AnimatableCompletion? = nil) { alpha = 0 animateWithAlpha(1, completion: completion) } public func fadeOut(completion: AnimatableCompletion? = nil) { alpha = 1 animateWithAlpha(0, completion: completion) } public func fadeOutIn(completion: AnimatableCompletion? = nil) { animateLayer({ let animation = CABasicAnimation(keyPath: "opacity") animation.fromValue = 1 animation.toValue = 0 animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) animation.duration = CFTimeInterval(self.duration) animation.beginTime = CACurrentMediaTime() + CFTimeInterval(self.delay) animation.autoreverses = true self.layer.addAnimation(animation, forKey: "fade") }, completion: completion) } public func fadeInOut(completion: AnimatableCompletion? = nil) { animateLayer({ let animation = CABasicAnimation(keyPath: "opacity") animation.fromValue = 0 animation.toValue = 1 animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) animation.duration = CFTimeInterval(self.duration) animation.beginTime = CACurrentMediaTime() + CFTimeInterval(self.delay) animation.autoreverses = true animation.removedOnCompletion = false self.layer.addAnimation(animation, forKey: "fade") }, completion: { self.alpha = 0 completion?() }) } public func zoomIn(completion: AnimatableCompletion? = nil) { let scaleX = 2 * force let scaleY = 2 * force alpha = 0 let toAlpha: CGFloat = 1 animateInWithScaleX(scaleX, scaleY: scaleY, alpha: toAlpha, completion: completion) } public func zoomOut(completion: AnimatableCompletion? = nil) { let scaleX = 2 * force let scaleY = 2 * force alpha = 1 let toAlpha: CGFloat = 0 animateOutWithScaleX(scaleX, scaleY: scaleY, alpha: toAlpha, completion: completion) } public func shake(completion: AnimatableCompletion? = nil) { animateLayer({ let animation = CAKeyframeAnimation(keyPath: "position.x") animation.values = [0, 30 * self.force, -30 * self.force, 30 * self.force, 0] animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) animation.duration = CFTimeInterval(self.duration) animation.additive = true animation.repeatCount = self.repeatCount animation.beginTime = CACurrentMediaTime() + CFTimeInterval(self.delay) self.layer.addAnimation(animation, forKey: "shake") }, completion: completion) } public func pop(completion: AnimatableCompletion? = nil) { animateLayer({ let animation = CAKeyframeAnimation(keyPath: "transform.scale") animation.values = [0, 0.2 * self.force, -0.2 * self.force, 0.2 * self.force, 0] animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) animation.duration = CFTimeInterval(self.duration) animation.additive = true animation.repeatCount = self.repeatCount animation.beginTime = CACurrentMediaTime() + CFTimeInterval(self.delay) self.layer.addAnimation(animation, forKey: "pop") }, completion: completion) } public func morph(completion: AnimatableCompletion? = nil) { animateLayer({ let morphX = CAKeyframeAnimation(keyPath: "transform.scale.x") morphX.values = [1, 1.3 * self.force, 0.7, 1.3 * self.force, 1] morphX.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] morphX.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) let morphY = CAKeyframeAnimation(keyPath: "transform.scale.y") morphY.values = [1, 0.7, 1.3 * self.force, 0.7, 1] morphY.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] morphY.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) let animationGroup = CAAnimationGroup() animationGroup.animations = [morphX, morphY] animationGroup.duration = CFTimeInterval(self.duration) animationGroup.repeatCount = self.repeatCount animationGroup.beginTime = CACurrentMediaTime() + CFTimeInterval(self.delay) self.layer.addAnimation(animationGroup, forKey: "morph") }, completion: completion) } public func squeeze(completion: AnimatableCompletion? = nil) { animateLayer({ let squeezeX = CAKeyframeAnimation(keyPath: "transform.scale.x") squeezeX.values = [1, 1.5 * self.force, 0.5, 1.5 * self.force, 1] squeezeX.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] squeezeX.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) let squeezeY = CAKeyframeAnimation(keyPath: "transform.scale.y") squeezeY.values = [1, 0.5, 1, 0.5, 1] squeezeY.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] squeezeY.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) let animationGroup = CAAnimationGroup() animationGroup.animations = [squeezeX, squeezeY] animationGroup.duration = CFTimeInterval(self.duration) animationGroup.repeatCount = self.repeatCount animationGroup.beginTime = CACurrentMediaTime() + CFTimeInterval(self.delay) self.layer.addAnimation(animationGroup, forKey: "squeeze") }, completion: completion) } public func flipX(completion: AnimatableCompletion? = nil) { let scaleX: CGFloat = 1 let scaleY: CGFloat = -1 animateInWithScaleX(scaleX, scaleY: scaleY, alpha: 1, completion: completion) } public func flipY(completion: AnimatableCompletion? = nil) { let scaleX: CGFloat = -1 let scaleY: CGFloat = 1 animateInWithScaleX(scaleX, scaleY: scaleY, alpha: 1, completion: completion) } public func flash(completion: AnimatableCompletion? = nil) { animateLayer({ let animation = CABasicAnimation(keyPath: "opacity") animation.fromValue = 1 animation.toValue = 0 animation.duration = CFTimeInterval(self.duration) animation.repeatCount = self.repeatCount * 2.0 animation.autoreverses = true animation.beginTime = CACurrentMediaTime() + CFTimeInterval(self.delay) self.layer.addAnimation(animation, forKey: "flash") }, completion: completion) } public func wobble(completion: AnimatableCompletion? = nil) { animateLayer({ let rotation = CAKeyframeAnimation(keyPath: "transform.rotation") rotation.values = [0, 0.3 * self.force, -0.3 * self.force, 0.3 * self.force, 0] rotation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] rotation.additive = true let positionX = CAKeyframeAnimation(keyPath: "position.x") positionX.values = [0, 30 * self.force, -30 * self.force, 30 * self.force, 0] positionX.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] positionX.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) positionX.additive = true let animationGroup = CAAnimationGroup() animationGroup.animations = [rotation, positionX] animationGroup.duration = CFTimeInterval(self.duration) animationGroup.beginTime = CACurrentMediaTime() + CFTimeInterval(self.delay) animationGroup.repeatCount = self.repeatCount self.layer.addAnimation(animationGroup, forKey: "wobble") }, completion: completion) } public func swing(completion: AnimatableCompletion? = nil) { animateLayer({ let animation = CAKeyframeAnimation(keyPath: "transform.rotation") animation.values = [0, 0.3 * self.force, -0.3 * self.force, 0.3 * self.force, 0] animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] animation.duration = CFTimeInterval(self.duration) animation.additive = true animation.repeatCount = self.repeatCount animation.beginTime = CACurrentMediaTime() + CFTimeInterval(self.delay) self.layer.addAnimation(animation, forKey: "swing") }, completion: completion) } public func rotate(clockwise clockwise: Bool = true, completion: AnimatableCompletion? = nil) { animateLayer({ let animation = CABasicAnimation(keyPath: "transform.rotation") animation.fromValue = clockwise ? 0 : ((360 * M_PI) / 180) animation.toValue = clockwise ? ((360 * M_PI) / 180) : 0 animation.duration = CFTimeInterval(self.duration) animation.repeatCount = self.repeatCount animation.autoreverses = false animation.beginTime = CACurrentMediaTime() + CFTimeInterval(self.delay) self.layer.addAnimation(animation, forKey: "rotate") }, completion: completion) } public func moveTo(completion: AnimatableCompletion? = nil) { if x.isNaN && y.isNaN { return } // Get the absolute position let absolutePosition = convertPoint(frame.origin, toView: nil) var xOffsetToMove: CGFloat if x.isNaN { xOffsetToMove = 0 } else { xOffsetToMove = x - absolutePosition.x } var yOffsetToMove: CGFloat if y.isNaN { yOffsetToMove = 0 } else { yOffsetToMove = y - absolutePosition.y } animateToWithX(xOffsetToMove, y: yOffsetToMove, completion: completion) } public func moveBy(completion: AnimatableCompletion? = nil) { if x.isNaN && y.isNaN { return } let xOffsetToMove = x.isNaN ? 0: x let yOffsetToMove = y.isNaN ? 0: y animateToWithX(xOffsetToMove, y: yOffsetToMove, completion: completion) } // MARK: - Private private func animateLayer(animation: AnimatableExecution, completion: AnimatableCompletion? = nil) { CATransaction.begin() if let completion = completion { CATransaction.setCompletionBlock { completion() } } animation() CATransaction.commit() } private func animateInWithX(x: CGFloat, completion: AnimatableCompletion? = nil) { animateIn(x, 0, 1, 1, 1, completion) } private func animateOutWithX(x: CGFloat, alpha: CGFloat, completion: AnimatableCompletion? = nil) { animateOut(x, 0, 1, 1, alpha, completion) } private func animateInWithY(y: CGFloat, completion: AnimatableCompletion? = nil) { animateIn(0, y, 1, 1, 1, completion) } private func animateOutWithY(y: CGFloat, alpha: CGFloat, completion: AnimatableCompletion? = nil) { animateOut(0, y, 1, 1, alpha, completion) } private func animateInWithX(x: CGFloat, scaleX: CGFloat, completion: AnimatableCompletion? = nil) { animateIn(x, 0, scaleX, 1, 1, completion) } private func animateOutWithX(x: CGFloat, scaleX: CGFloat, alpha: CGFloat, completion: AnimatableCompletion? = nil) { animateOut(x, 0, scaleX, 1, alpha, completion) } private func animateInWithY(y: CGFloat, scaleY: CGFloat, completion: AnimatableCompletion? = nil) { animateIn(0, y, 1, scaleY, 1, completion) } private func animateOutWithY(y: CGFloat, scaleY: CGFloat, alpha: CGFloat, completion: AnimatableCompletion? = nil) { animateOut(0, y, 1, scaleY, alpha, completion) } private func animateInWithScaleX(scaleX: CGFloat, scaleY: CGFloat, alpha: CGFloat, completion: AnimatableCompletion? = nil) { animateIn(0, 0, scaleX, scaleY, alpha, completion) } private func animateOutWithScaleX(scaleX: CGFloat, scaleY: CGFloat, alpha: CGFloat, completion: AnimatableCompletion? = nil) { animateOut(0, 0, scaleX, scaleY, alpha, completion) } private func animateWithAlpha(alpha: CGFloat, completion: AnimatableCompletion? = nil) { UIView.animateWithDuration(duration, delay: delay, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: [], animations: { () -> Void in self.alpha = alpha }, completion: { (completed) -> Void in completion?() }) } private func animateToWithX(x: CGFloat, y: CGFloat, completion: AnimatableCompletion? = nil) { animateTo(x, y, completion) } private func animateTo(x: CGFloat, _ y: CGFloat, _ completion: AnimatableCompletion? = nil) { let translate = CGAffineTransformMakeTranslation(x, y) UIView.animateWithDuration(duration, delay:delay, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: [], animations: { () -> Void in self.transform = translate }, completion: { (completed) -> Void in completion?() }) } private func animateIn(x: CGFloat, _ y: CGFloat, _ scaleX: CGFloat, _ scaleY: CGFloat, _ alpha: CGFloat, _ completion: AnimatableCompletion? = nil) { let translate = CGAffineTransformMakeTranslation(x, y) let scale = CGAffineTransformMakeScale(scaleX, scaleY) let translateAndScale = CGAffineTransformConcat(translate, scale) transform = translateAndScale UIView.animateWithDuration(duration, delay:delay, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: [], animations: { () -> Void in self.transform = CGAffineTransformIdentity self.alpha = alpha }, completion: { (completed) -> Void in completion?() }) } private func animateOut(x: CGFloat, _ y: CGFloat, _ scaleX: CGFloat, _ scaleY: CGFloat, _ alpha: CGFloat, _ completion: AnimatableCompletion? = nil) { let translate = CGAffineTransformMakeTranslation(x, y) let scale = CGAffineTransformMakeScale(scaleX, scaleY) let translateAndScale = CGAffineTransformConcat(translate, scale) UIView.animateWithDuration(duration, delay:delay, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: [], animations: { () -> Void in self.transform = translateAndScale self.alpha = alpha }, completion: { (completed) -> Void in completion?() }) } // MARK: Private helper private func screenSize() -> CGSize { return UIScreen.mainScreen().bounds.size } } public extension Animatable where Self: UIBarItem { // TODO: animations for `UIBarItem` public func animate(completion: AnimatableCompletion? = nil) { } }
mit
7a8d880c8785b1622e61492af4bef28d
32.792818
161
0.683479
4.413855
false
false
false
false
Tulakshana/FileCache
FileCache/Example/FileCache/Users/UsersVC.swift
1
2596
// // UsersVC.swift // FileCacheExample // // Created by Weerasooriya, Tulakshana on 5/11/17. // Copyright © 2017 Tulakshana. All rights reserved. // import UIKit import SVProgressHUD class UsersVC: UIViewController { let dataSource: UsersDS = UsersDS() let categoriesSegue: String = "categoriesSegue" private let refreshControl: UIRefreshControl = UIRefreshControl.init() @IBOutlet var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() dataSource.delegate = self dataSource.loadUsers() self.setupPullToRefresh() self.title = "Users" } override func viewWillDisappear(_ animated: Bool) { SVProgressHUD.dismiss() super.viewWillDisappear(animated) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == categoriesSegue { if let vc: CategoriesVC = segue.destination as? CategoriesVC { if let row: Int = tableView.indexPathForSelectedRow?.row { if let user: User = dataSource.usersArray.object(at: row) as? User { vc.user = user } } } } } //MARK:- func setupPullToRefresh() { refreshControl.addTarget(self, action: #selector(handleRefresh), for: UIControlEvents.valueChanged) tableView.addSubview(refreshControl) } @objc func handleRefresh() { dataSource.resetCache() dataSource.loadUsers() refreshControl.endRefreshing() } } extension UsersVC: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell: UserCell = tableView.dequeueReusableCell(withIdentifier: "userCellIdentifier") as? UserCell { if let user: User = dataSource.usersArray.object(at: indexPath.row) as? User { cell.setUserDetails(user: user, indexPath: indexPath) } return cell } return UITableViewCell() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.usersArray.count } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.performSegue(withIdentifier: categoriesSegue, sender: self) } } extension UsersVC: UsersDSDelegate { func usersDSDidChange() { tableView.reloadData() } }
mit
ea350c733d56b96d7341c1e9fb8c571a
29.174419
114
0.63237
5.128458
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab2Search/SLV_204_SearchStyle.swift
1
12916
// // SLV_204_SearchStyle.swift // selluv-ios // // Created by 조백근 on 2016. 11. 8.. // Copyright © 2016년 BitBoy Labs. All rights reserved. // /* 검색뷰 서브탭 스타일 */ import UIKit import SwifterSwift import PullToRefresh class SLV_204_SearchStyle: SLVBaseStatusShowController { let refresher = PullToRefresh() var itemInfo: IndicatorInfo = IndicatorInfo(title: "스타일")//tab 정보 weak var delegate: SLVButtonBarDelegate?// 델리게이트. weak var myNavigationDelegate: SLVNavigationControllerDelegate?// push를 위한 네비게이션 @IBOutlet weak var collectView: UICollectionView! var bannerList: [SLVBanner] = [] var itemList: [SLVDetailProduct] = [] override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.loadStyles(same: false) } override func viewDidLoad() { super.viewDidLoad() self.prepare() self.loadData(same: false) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func linkDelegate(controller: AnyObject) { self.delegate = controller as? SLVButtonBarDelegate self.myNavigationDelegate = controller as? SLVNavigationControllerDelegate if self.delegate != nil { let parent = self.delegate as! SLV_200_SearchMainController } } func prepare() { self.view.backgroundColor = UIColor.clear self.extendedLayoutIncludesOpaqueBars = true self.automaticallyAdjustsScrollViewInsets = false // let width = UIScreen.main.bounds.width // let layout = self.collectView.collectionViewLayout as! UICollectionViewFlowLayout // layout.itemSize = CGSize(width: width, height: 175) // layout.minimumLineSpacing = 1 // layout.minimumInteritemSpacing = 1 // layout.invalidateLayout() self.collectView.setCollectionViewLayout(CHTCollectionViewWaterfallLayout(), animated: false) // self.collectView.register(UINib(nibName: "SLV_SearchStylesFirstCell", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "SLV_SearchStylesFirstCell")//for section self.collectView.register(UINib(nibName: "SLV_SearchStylesFirstCell", bundle: nil), forCellWithReuseIdentifier: "SLV_SearchStylesFirstCell") self.collectView.register(UINib(nibName: "SLVUserStyleCell", bundle: nil), forCellWithReuseIdentifier: "SLVUserStyleCell") self.collectView.remembersLastFocusedIndexPath = true self.collectView.delegate = self self.collectView.dataSource = self self.collectView.contentInset = UIEdgeInsetsMake(10, 0, 64, 0) refresher.position = .bottom self.collectView.addPullToRefresh(refresher) { self.loadStyles(same: true) } } deinit { self.collectView?.removePullToRefresh((self.collectView?.bottomPullToRefresh!)!) } func setupLongPress() { let overlay = GHContextMenuView() overlay.delegate = self overlay.dataSource = self let selector = #selector(GHContextMenuView.longPressDetected(_:)) let longPress = UILongPressGestureRecognizer(target: overlay, action: selector) self.collectView?.addGestureRecognizer(longPress) } func loadData(same: Bool) { self.bannerList.removeAll() SearchTabModel.shared.banners { (success, banners) in if success == true { if let banners = banners { self.bannerList.append(contentsOf: banners) } } } } func loadStyles(same: Bool) { if same == false { self.itemList.removeAll() } SearchTabModel.shared.productsForStyles(kind: "all", same: same) { (success, products) in if success == true { if let products = products { self.itemList.append(contentsOf: products) } } self.collectView.reloadData() } } } // MARK: - IndicatorInfoProvider extension SLV_204_SearchStyle: IndicatorInfoProvider { func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo { return itemInfo } } // MARK: - Collection View extension SLV_204_SearchStyle: UICollectionViewDataSource, UICollectionViewDelegate { public func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == self.collectView { let off = scrollView.contentOffset if off.y > 0 { // hide self.delegate?.hideByScroll() } else { //show self.delegate?.showByScroll() } } } public func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } // public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { // let cell = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier:"SLV_UserReviewGroupView", for: indexPath) as! SLV_UserReviewGroupView // return cell // } // public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { // let w = UIScreen.main.bounds.width // return CGSize(width: w, height: 54) // } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return (self.itemList.count + 1) } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let row = indexPath.row if row == 0 { let collectionCell: SLV_SearchStylesFirstCell = collectionView.dequeueReusableCell(withReuseIdentifier: "SLV_SearchStylesFirstCell", for: indexPath as IndexPath) as! SLV_SearchStylesFirstCell collectionCell.setupData(items: self.bannerList) return collectionCell } else { let collectionCell: SLVUserStyleCell = collectionView.dequeueReusableCell(withReuseIdentifier: "SLVUserStyleCell", for: indexPath as IndexPath) as! SLVUserStyleCell collectionCell.delegate = self let item = self.itemList[indexPath.row - 1] collectionCell.setupData(item: item) return collectionCell } } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { } } extension SLV_204_SearchStyle: CHTCollectionViewDelegateWaterfallLayout, SLVCollectionTransitionProtocol { func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{ let row = indexPath.row if row == 0 { return CGSize(width: self.view.bounds.width, height: 170) } else { var itemSize = DEFAULT_PHOTO_SIZE var isFinish = true if self.itemList.count > 0 && self.itemList.count >= indexPath.row + 1 { let info = self.itemList[indexPath.row] var name = "" if info.styles != nil { if (info.styles?.count)! > 0 { name = (info.styles?.first)! } } if name != "" { let from = URL(string: "\(dnStyle)\(name)") isFinish = false ImageScout.shared.scoutImage(url: from!) { error, size, type in isFinish = true if let error = error { print(error.code) } else { print("Size: \(size)") print("Type: \(type.rawValue)") itemSize = size } } } } var cnt: Int = 0 var sec: Double = 0 while(isFinish == false && 2 < sec ) { RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.01)) cnt = cnt + 1 sec = Double(cnt) * Double(0.01) } let imageHeight = itemSize.height*gridWidth/itemSize.width + SLVUserProductCell.infoHeight + SLVUserProductCell.humanHeight log.debug("remote image calc cell width: \(gridWidth) , height: \(imageHeight)") return CGSize(width: gridWidth, height: imageHeight) } } func transitionTabCollectionView() -> UICollectionView!{ return self.collectView } } extension SLV_204_SearchStyle: SLVCollectionLinesDelegate { // 스타일 영역을 터치한다. func didTouchedStyleThumbnail(info: AnyObject) { } // 좋아요를 터치한다. func didTouchedLikeButton(info: AnyObject) { } func didTouchedItemDescription(info: AnyObject) { } func didTouchedUserDescription(info: AnyObject) { } } extension SLV_204_SearchStyle: GHContextOverlayViewDataSource, GHContextOverlayViewDelegate { func shouldShowMenu(at point: CGPoint) -> Bool { let path = self.collectView?.indexPathForItem(at: point) if path != nil { let cell = self.collectView?.cellForItem(at: path!) return cell != nil } return false } func shouldShowMenuOnParentImage(at point: CGPoint) -> UIImage! { let path = self.collectView?.indexPathForItem(at: point) if path != nil { let cell = self.collectView?.cellForItem(at: path!) as? SLVUserStyleCell if cell != nil { let image = cell!.imageViewContent?.image return image } } return nil } func shouldShowMenuParentImageFrame(at point: CGPoint) -> CGRect { let path = self.collectView?.indexPathForItem(at: point) if path != nil { let cell = self.collectView?.cellForItem(at: path!) as? SLVUserStyleCell if cell != nil { let frame = cell?.imageViewContent?.frame var newFrame = self.view?.convert(frame!, to: nil) let x = ((screenWidth/2) > point.x) ? 17:(screenWidth/2 + 5) newFrame?.origin.x = x return newFrame! } } return .zero } func numberOfMenuItems() -> Int { return 4 } func itemInfoForItem(at index: Int) -> GHContextItemView! { let itemView = GHContextItemView() switch index { case 0: itemView.typeDesc = "좋아요" itemView.baseImage = UIImage(named: "longpress-like-nor.png") itemView.selectedImage = UIImage(named: "longpress-like-focus.png") // itemView.baseImage = UIImage(named: "longpress-like-not-nor.png") // itemView.selectedImage = UIImage(named: "longpress-like-not-focus.png") break case 1: itemView.typeDesc = "피드" itemView.baseImage = UIImage(named: "longpress-feed-nor.png") itemView.selectedImage = UIImage(named: "longpress-feed-focus.png") break case 2: itemView.typeDesc = "공유" itemView.baseImage = UIImage(named: "longpress-share-nor.png") itemView.selectedImage = UIImage(named: "longpress-share-focus.png") break case 3: itemView.typeDesc = "더보기" itemView.baseImage = UIImage(named: "longpress-more-nor.png") itemView.selectedImage = UIImage(named: "longpress-more-focus.png") break default: break } return itemView } func didSelectItem(at selectedIndex: Int, forMenuAt point: CGPoint) { // let path = self.collectionView?.indexPathForItem(at: point) var message = "" switch selectedIndex { case 0: message = "좋아요 selected" break case 1: message = "피드 selected" break case 2: message = "공유 selected" break case 3: message = "더보기 selected" break default: break } AlertHelper.alert(message: message) } }
mit
3e90d88a82f112fc9e05e23da0dd0d0b
35.09322
222
0.598028
5.062203
false
false
false
false
Pluto-Y/SwiftyImpress
Source/View+Extension.swift
1
2401
// // View+Extension.swift // SwiftyImpress // // Created by Pluto Y on 24/09/2016. // Copyright © 2016 com.pluto-y. All rights reserved. // extension View: SwiftyImpressCompatible { } // MARK: - Associated Key private var transform3DKey: Void? private var completionKey: Void? public typealias CompletionHandler = (_ view: View) -> () public struct CompleteClosureWrapper { var closure: CompletionHandler init(_ closure: @escaping CompletionHandler) { self.closure = closure } } public extension SwiftyImpress where Base: View { public var transform3D: CATransform3D { get { if let transform = objc_getAssociatedObject(base, &transform3DKey) as? CATransform3D { return transform } return CATransform3DIdentity } set { objc_setAssociatedObject(base, &transform3DKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } public var size: CGSize { set { base.frame = CGRect(origin: base.frame.origin, size: newValue) } get { return base.bounds.size } } public var completion: CompleteClosureWrapper? { get { if let completion = objc_getAssociatedObject(base, &completionKey) as? CompleteClosureWrapper { return completion } return nil } set { objc_setAssociatedObject(base, &completionKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) } } @discardableResult public func from(_ base: View, transform: CATransform3D) -> SwiftyImpress { let view = base self.transform3D = makeTransforms([pure(transform)], from: view.si.transform3D) return self } @discardableResult public func with(transform: CATransform3D) -> SwiftyImpress { self.transform3D = transform return self } @discardableResult public func config(clouse: (_: Base) -> ()) -> SwiftyImpress { clouse(base) return self } @discardableResult public func when(entered completion: CompletionHandler?) -> SwiftyImpress { if let closure = completion { self.completion = CompleteClosureWrapper(closure) } else { self.completion = nil } return self } }
mit
ea96fa8d12e85713deaa8ede271cf38e
26.586207
107
0.607083
4.651163
false
false
false
false
inon29/INOMessageTextBox
Example/INOMessageTextBox/ViewController.swift
1
3174
// // ViewController.swift // INOMessageTextBox // // Created by Your Name Heiya on 11/02/2015. // Copyright (c) 2015 Your Name Heiya. All rights reserved. // import UIKit import INOMessageTextBox class ViewController: UIViewController { @IBOutlet weak var _tableView: UITableView! @IBOutlet weak var _textBox: INOMessageTextBox! @IBOutlet weak var _bottomConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() _textBox.rightButtonTouchEvent = { (textBox: INOMessageTextBox, text: String) -> Void in print(text) } _textBox.contentSizeDidChangeEvent = { (textBox: INOMessageTextBox, differenceWidth: CGFloat, differenceHeight: CGFloat) -> Void in print("diff width: ", differenceWidth,"height: ", differenceHeight) } _textBox.placeHolder = "PlaceHolder" NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func keyboardWillShow(notification: NSNotification) -> Void { let rect = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() let duration:NSTimeInterval = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! Double self._bottomConstraint?.constant = rect.height UIView.animateWithDuration(duration) { self._textBox.layoutIfNeeded() } } func keyboardWillHide(notification: NSNotification) -> Void { let rect = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() let duration:NSTimeInterval = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! Double self._bottomConstraint?.constant = rect.height UIView.animateWithDuration(duration) { self._textBox.layoutIfNeeded() } } } extension ViewController: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 30 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell") cell?.textLabel?.text = String(indexPath.row) return cell! } } extension UIView { internal func constraint(firstItem firstItem: NSObject, firstAttribute: NSLayoutAttribute) -> NSLayoutConstraint? { let items = self.constraints.filter { $0.firstItem as! NSObject === firstItem && $0.firstAttribute == firstAttribute } return items.count > 0 ? items.first : nil } }
mit
09e51c9b78e593c1191535df740812ec
35.906977
139
0.679584
5.388795
false
false
false
false
willhains/Kotoba
code/Kotoba/AddWordViewController.swift
1
12054
// // Created by Will Hains on 06/17. // Copyright © 2016 Will Hains. All rights reserved. // import Foundation import UIKit class AddWordViewController: UIViewController { @IBOutlet weak var textField: UITextField! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var searchingIndicator: UIActivityIndicatorView! @IBOutlet weak var suggestionToggleButton: UIButton! @IBOutlet weak var typingViewBottomLayoutConstraint: NSLayoutConstraint! @IBOutlet weak var suggestionViewBottomLayoutConstraint: NSLayoutConstraint! @IBOutlet weak var suggestionViewHeightLayoutConstraint: NSLayoutConstraint! var suggestionsVisible = false var suggestionHeight = CGFloat(200) let suggestionHeaderHeight = CGFloat(44) // NOTE: This value should match "Header View" in the storyboard var pasteboardWords: [Word] = [] var keyboardVisible = false var keyboardHeight = CGFloat(0) deinit { NotificationCenter.default.removeObserver(self) } override func viewDidLoad() { super.viewDidLoad() prepareKeyboardNotifications() // NOTE: This improves the initial view animation, when the keyboard and suggestions appear, but it also // generates the warning below. If we wait until the tableView is in the view hierarchy (in viewDidAppear) the // keyboard animation is already in progress and it's too late to adjust the width of the top-level view. self.view.layoutIfNeeded() /* [TableView] Warning once only: UITableView was told to layout its visible cells and other contents without being in the view hierarchy (the table view or one of its superviews has not been added to a window). This may cause bugs by forcing views inside the table view to load and perform layout without accurate information (e.g. table view bounds, trait collection, layout margins, safe area insets, etc), and will also cause unnecessary performance overhead due to extra layout passes. Make a symbolic breakpoint at UITableViewAlertForLayoutOutsideViewHierarchy to catch this in the debugger and see what caused this to occur, so you can avoid this action altogether if possible, or defer it until the table view has been added to a window. Table view: <UITableView: 0x7f8064035e00; frame = (0 44; 414 156); clipsToBounds = YES; autoresize = RM+BM; gestureRecognizers = <NSArray: 0x600001310b10>; layer = <CALayer: 0x600001d2d2c0>; contentOffset: {0, 0}; contentSize: {414, 0}; adjustedContentInset: {0, 0, 0, 0}; dataSource: <Kotoba .AddWordViewController: 0x7f806370ac80>> */ NotificationCenter.default.addObserver( self, selector: #selector(applicationDidBecomeActive(notification:)), name: UIApplication.didBecomeActiveNotification, object: nil) } override func viewWillAppear(_ animated: Bool) { debugLog() super.viewWillAppear(animated) // TODO: Decide if the keyboard should appear before or after the view. showKeyboard() } override func viewDidAppear(_ animated: Bool) { debugLog() super.viewDidAppear(animated) } override func viewWillDisappear(_ animated: Bool) { debugLog() super.viewWillDisappear(animated) hideKeyboard() } @objc func applicationDidBecomeActive(notification: NSNotification) { debugLog() #if true suggestionsVisible = !UIPasteboard.general.ignoreSuggestions let duration: TimeInterval = 0.2 UIView.animate(withDuration: duration) { self.updateLayoutFromPasteboard() self.updateLayersForSuggestions() self.updateTableView() self.view.layoutIfNeeded() } #endif } } // MARK:- Async word lookup extension AddWordViewController { func initiateSearch(forWord word: Word) { debugLog("word = \(word)") self.searchingIndicator.startAnimating() // NOTE: On iOS 13, UIReferenceLibraryViewController got slow, both to return a view controller and do a // definition lookup. Previously, Kotoba did both these things at the same time on the same queue. // // The gymnastics below are to hide the slowness: after the view controller is presented, the definition lookup // proceeds on a background queue. If there's a definition, the text field is cleared: if you spend little time // reading the definition, you'll notice that the field is cleared while you're looking at it. If you're really // quick, you can see it not appear in the History view, too. Better this than slowness. // // TODO: This has to be a regression in UIReferenceLibraryViewController. I'll file a radar for this. self.showDefinition(forWord: word) { debugLog("presented dictionary view controlller") DispatchQueue.global().async { debugLog("checking definition") let hasDefinition = UIReferenceLibraryViewController.dictionaryHasDefinition(forTerm: word.text) debugLog("hasDefinition = \(hasDefinition)") DispatchQueue.main.async { if hasDefinition { var words = wordListStore.data words.add(word: word) self.textField.text = nil } self.searchingIndicator.stopAnimating() } } } } } // MARK:- Actions extension AddWordViewController { @IBAction func openSettings(_: AnyObject) { debugLog() if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url) } } @IBAction func dismissSuggestions(_: AnyObject) { debugLog() self.suggestionsVisible.toggle() UIPasteboard.general.ignoreSuggestions = !suggestionsVisible let duration: TimeInterval = 0.2 UIView.animate(withDuration: duration) { self.updateConstraintsForKeyboardAndSuggestions() self.updateLayersForSuggestions() self.view.layoutIfNeeded() } } } // MARK:- Keyboard notifications extension AddWordViewController { func prepareKeyboardNotifications() { NotificationCenter.default.addObserver( self, selector: #selector(AddWordViewController.keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil); NotificationCenter.default.addObserver( self, selector: #selector(AddWordViewController.keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil); } private func updateConstraintsForKeyboardAndSuggestions() { debugLog("keyboardHeight = \(keyboardHeight), suggestionHeight = \(suggestionHeight)") // NOTE: There are two primary views, each with a layout contraint for the bottom of the view. // // The first is the "suggestion view" that attaches either to the top of the keyboard (when shown) or a // negative offset of its height (to hide the view.) // // The second view is the "typing view" that is either attached to the top of the suggestion view (when it's // visible) or to the bottom safe area inset (when it's not.) self.suggestionViewHeightLayoutConstraint.constant = suggestionHeight if self.suggestionsVisible { if self.keyboardVisible { self.typingViewBottomLayoutConstraint.constant = keyboardHeight + suggestionHeight self.suggestionViewBottomLayoutConstraint.constant = keyboardHeight } else { self.typingViewBottomLayoutConstraint.constant = self.view.safeAreaInsets.bottom + suggestionHeight self.suggestionViewBottomLayoutConstraint.constant = self.view.safeAreaInsets.bottom } } else { if self.keyboardVisible { self.typingViewBottomLayoutConstraint.constant = keyboardHeight + suggestionHeaderHeight self.suggestionViewBottomLayoutConstraint.constant = keyboardHeight - suggestionHeight + suggestionHeaderHeight } else { // TODO: Technically, the safeAreaInsets are the "bottom", but that leaves a weird little bit of the // first suggestion visible under the home indicator. If the offset is flush against the container view // (e.g. 0), it puts the button and text in the home indicator area. Choose the lesser evil... // let offset = self.view.safeAreaInsets.bottom let offset = CGFloat.zero self.typingViewBottomLayoutConstraint.constant = offset + suggestionHeaderHeight self.suggestionViewBottomLayoutConstraint.constant = offset - suggestionHeight + suggestionHeaderHeight } } } func updateLayersForSuggestions() { debugLog() if self.suggestionsVisible { self.suggestionToggleButton.layer.transform = CATransform3DIdentity; } else { self.suggestionToggleButton.layer.transform = CATransform3DMakeScale(1.0, -1.0, 1.0) } } @objc func keyboardWillShow(notification: Notification) { let info = notification.userInfo! keyboardVisible = true keyboardHeight = (info[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height debugLog("keyboardHeight = \(keyboardHeight)") let duration: TimeInterval = (info[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue UIView.animate(withDuration: duration) { self.updateConstraintsForKeyboardAndSuggestions() self.view.layoutIfNeeded() } } @objc func keyboardWillHide(notification: Notification) { debugLog() let info = notification.userInfo! keyboardVisible = false keyboardHeight = 0 let duration: TimeInterval = (info[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue UIView.animate(withDuration: duration) { self.updateConstraintsForKeyboardAndSuggestions() self.view.layoutIfNeeded() } } } // MARK:- Utility extension AddWordViewController { func showKeyboard() { self.textField.becomeFirstResponder() } func hideKeyboard() { self.textField.resignFirstResponder() } func updateLayoutFromPasteboard() { pasteboardWords = UIPasteboard.general.suggestedWords // NOTE: This isn't the most elegant way to handle the compact height layout (landscape orientation) // but it gets the job done with a minimum amount of work. I'm actually questioning the need for // landscape support: the entire experience feels kinda clunky. // CHOCK: I'd be happy to drop landscape support, tbh. let maximumHeight: CGFloat = view.frame.size.height > view.frame.size.width ? 200 : 100 var computedSuggestionHeight = suggestionHeaderHeight for row in 0..<pasteboardWords.count { if let cell = tableView.cellForRow(at: IndexPath(row: row, section: 0)) { computedSuggestionHeight += cell.frame.size.height } else { computedSuggestionHeight += 44 } if computedSuggestionHeight > maximumHeight { break } } if computedSuggestionHeight > maximumHeight { suggestionHeight = maximumHeight } else { suggestionHeight = computedSuggestionHeight } suggestionsVisible = !UIPasteboard.general.ignoreSuggestions updateConstraintsForKeyboardAndSuggestions() updateLayersForSuggestions() } func updateTableView() { tableView.reloadData() if (pasteboardWords.count > 0) { tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false) } } } // MARK:- Text Field delegate extension AddWordViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { if let text = textField.text { let word = Word(text: text) initiateSearch(forWord: word) } return true } } // MARK:- Table View delegate/datasource extension AddWordViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { pasteboardWords.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Word", for: indexPath) let text = pasteboardWords[indexPath.row].text cell.textLabel?.text = text cell.textLabel?.font = .preferredFont(forTextStyle: UIFont.TextStyle.body) // TODO: Move to extension of UILabel return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard indexPath.row >= 0 else { return } let word = pasteboardWords[indexPath.row] self.textField.text = word.text initiateSearch(forWord: word) tableView.selectRow(at: nil, animated: true, scrollPosition: .none) } }
mit
b5468f72c049ab93a41a1b30a8c70641
29.591371
114
0.753588
4.115056
false
false
false
false
samnm/material-components-ios
components/TextFields/tests/unit/TextFieldControllerClassPropertiesLegacyTests.swift
2
21489
/* Copyright 2017-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // swiftlint:disable function_body_length // swiftlint:disable type_body_length import XCTest import MaterialComponents.MaterialPalettes import MaterialComponents.MaterialTextFields import MaterialComponents.MaterialTypography class TextFieldControllerClassPropertiesLegacyTests: XCTestCase { override func tearDown() { super.tearDown() MDCTextInputControllerLegacyDefault.errorColorDefault = nil MDCTextInputControllerLegacyDefault.inlinePlaceholderColorDefault = nil MDCTextInputControllerLegacyDefault.mdc_adjustsFontForContentSizeCategoryDefault = true MDCTextInputControllerLegacyDefault.activeColorDefault = nil MDCTextInputControllerLegacyDefault.normalColorDefault = nil MDCTextInputControllerLegacyDefault.underlineViewModeDefault = .whileEditing MDCTextInputControllerLegacyDefault.leadingUnderlineLabelTextColorDefault = nil MDCTextInputControllerLegacyDefault.trailingUnderlineLabelTextColorDefault = nil MDCTextInputControllerLegacyDefault.inlinePlaceholderFontDefault = nil MDCTextInputControllerLegacyDefault.leadingUnderlineLabelFontDefault = nil MDCTextInputControllerLegacyDefault.trailingUnderlineLabelFontDefault = nil MDCTextInputControllerLegacyDefault.floatingPlaceholderNormalColorDefault = nil MDCTextInputControllerLegacyDefault.floatingPlaceholderScaleDefault = 0.75 MDCTextInputControllerLegacyDefault.isFloatingEnabledDefault = true MDCTextInputControllerLegacyFullWidth.errorColorDefault = nil MDCTextInputControllerLegacyFullWidth.inlinePlaceholderColorDefault = nil MDCTextInputControllerLegacyFullWidth.mdc_adjustsFontForContentSizeCategoryDefault = true MDCTextInputControllerLegacyFullWidth.activeColorDefault = nil MDCTextInputControllerLegacyFullWidth.normalColorDefault = nil MDCTextInputControllerLegacyFullWidth.underlineViewModeDefault = .never MDCTextInputControllerLegacyFullWidth.leadingUnderlineLabelTextColorDefault = nil MDCTextInputControllerLegacyFullWidth.trailingUnderlineLabelTextColorDefault = nil MDCTextInputControllerLegacyFullWidth.inlinePlaceholderFontDefault = nil MDCTextInputControllerLegacyFullWidth.leadingUnderlineLabelFontDefault = nil MDCTextInputControllerLegacyFullWidth.trailingUnderlineLabelFontDefault = nil } func testLegacyDefault() { // Test the values of the class properties. XCTAssertEqual(MDCTextInputControllerLegacyDefault.errorColorDefault, MDCPalette.red.accent400) XCTAssertEqual(MDCTextInputControllerLegacyDefault.inlinePlaceholderColorDefault, UIColor(white: 0, alpha: CGFloat(Float(0.54)))) XCTAssertEqual(MDCTextInputControllerLegacyDefault.mdc_adjustsFontForContentSizeCategoryDefault, true) XCTAssertEqual(MDCTextInputControllerLegacyDefault.activeColorDefault, MDCPalette.blue.accent700) XCTAssertEqual(MDCTextInputControllerLegacyDefault.normalColorDefault, .lightGray) XCTAssertEqual(MDCTextInputControllerLegacyDefault.underlineHeightActiveDefault, 2) XCTAssertEqual(MDCTextInputControllerLegacyDefault.underlineHeightNormalDefault, 1) XCTAssertEqual(MDCTextInputControllerLegacyDefault.underlineViewModeDefault, .whileEditing) XCTAssertEqual(MDCTextInputControllerLegacyDefault.leadingUnderlineLabelTextColorDefault, UIColor(white: 0, alpha: CGFloat(Float(0.54)))) XCTAssertEqual(MDCTextInputControllerLegacyDefault.trailingUnderlineLabelTextColorDefault, UIColor(white: 0, alpha: CGFloat(Float(0.54)))) XCTAssertEqual(MDCTextInputControllerLegacyDefault.leadingUnderlineLabelTextColorDefault, MDCTextInputControllerLegacyDefault.inlinePlaceholderColorDefault) XCTAssertEqual(MDCTextInputControllerLegacyDefault.trailingUnderlineLabelTextColorDefault, MDCTextInputControllerLegacyDefault.inlinePlaceholderColorDefault) XCTAssertEqual(MDCTextInputControllerLegacyDefault.inlinePlaceholderFontDefault, UIFont.mdc_preferredFont(forMaterialTextStyle: .body1)) XCTAssertEqual(MDCTextInputControllerLegacyDefault.leadingUnderlineLabelFontDefault, MDCTextInputControllerLegacyDefault.trailingUnderlineLabelFontDefault) XCTAssertEqual(MDCTextInputControllerLegacyDefault.leadingUnderlineLabelFontDefault, UIFont.mdc_preferredFont(forMaterialTextStyle: .caption)) // Default specific properties XCTAssertEqual(MDCTextInputControllerLegacyDefault.floatingPlaceholderNormalColorDefault, UIColor(white: 0, alpha: CGFloat(Float(0.54)))) XCTAssertEqual(Float(MDCTextInputControllerLegacyDefault.floatingPlaceholderScaleDefault), 0.75) XCTAssertEqual(MDCTextInputControllerLegacyDefault.isFloatingEnabledDefault, true) // Test the use of the class properties. let textField = MDCTextField() var controller = MDCTextInputControllerLegacyDefault(textInput: textField) XCTAssertEqual(controller.errorColor, MDCTextInputControllerLegacyDefault.errorColorDefault) XCTAssertEqual(controller.inlinePlaceholderColor, MDCTextInputControllerLegacyDefault.inlinePlaceholderColorDefault) XCTAssertEqual(controller.mdc_adjustsFontForContentSizeCategory, MDCTextInputControllerLegacyDefault.mdc_adjustsFontForContentSizeCategoryDefault) XCTAssertEqual(controller.activeColor, MDCTextInputControllerLegacyDefault.activeColorDefault) XCTAssertEqual(controller.normalColor, MDCTextInputControllerLegacyDefault.normalColorDefault) XCTAssertEqual(controller.underlineHeightActive, MDCTextInputControllerLegacyDefault.underlineHeightActiveDefault) XCTAssertEqual(controller.underlineHeightNormal, MDCTextInputControllerLegacyDefault.underlineHeightNormalDefault) XCTAssertEqual(controller.underlineViewMode, MDCTextInputControllerLegacyDefault.underlineViewModeDefault) XCTAssertEqual(controller.leadingUnderlineLabelTextColor, MDCTextInputControllerLegacyDefault.leadingUnderlineLabelTextColorDefault) XCTAssertEqual(controller.trailingUnderlineLabelTextColor, MDCTextInputControllerLegacyDefault.trailingUnderlineLabelTextColorDefault) XCTAssertEqual(controller.inlinePlaceholderFont, MDCTextInputControllerLegacyDefault.inlinePlaceholderFontDefault) XCTAssertEqual(controller.leadingUnderlineLabelFont, MDCTextInputControllerLegacyDefault.leadingUnderlineLabelFontDefault) XCTAssertEqual(controller.trailingUnderlineLabelFont, MDCTextInputControllerLegacyDefault.trailingUnderlineLabelFontDefault) // Default specific properties XCTAssertEqual(controller.floatingPlaceholderNormalColor, MDCTextInputControllerLegacyDefault.floatingPlaceholderNormalColorDefault) XCTAssertEqual(controller.isFloatingEnabled, MDCTextInputControllerLegacyDefault.isFloatingEnabledDefault) // Test the changes to the class properties. MDCTextInputControllerLegacyDefault.errorColorDefault = .green XCTAssertEqual(MDCTextInputControllerLegacyDefault.errorColorDefault, .green) MDCTextInputControllerLegacyDefault.inlinePlaceholderColorDefault = .orange XCTAssertEqual(MDCTextInputControllerLegacyDefault.inlinePlaceholderColorDefault, .orange) MDCTextInputControllerLegacyDefault.mdc_adjustsFontForContentSizeCategoryDefault = false XCTAssertEqual(MDCTextInputControllerLegacyDefault.mdc_adjustsFontForContentSizeCategoryDefault, false) MDCTextInputControllerLegacyDefault.activeColorDefault = .purple XCTAssertEqual(MDCTextInputControllerLegacyDefault.activeColorDefault, .purple) MDCTextInputControllerLegacyDefault.normalColorDefault = .white XCTAssertEqual(MDCTextInputControllerLegacyDefault.normalColorDefault, .white) MDCTextInputControllerLegacyDefault.underlineHeightActiveDefault = 11 XCTAssertEqual(MDCTextInputControllerLegacyDefault.underlineHeightActiveDefault, 11) MDCTextInputControllerLegacyDefault.underlineHeightNormalDefault = 5 XCTAssertEqual(MDCTextInputControllerLegacyDefault.underlineHeightNormalDefault, 5) MDCTextInputControllerLegacyDefault.underlineViewModeDefault = .unlessEditing XCTAssertEqual(MDCTextInputControllerLegacyDefault.underlineViewModeDefault, .unlessEditing) MDCTextInputControllerLegacyDefault.leadingUnderlineLabelTextColorDefault = .blue XCTAssertEqual(MDCTextInputControllerLegacyDefault.leadingUnderlineLabelTextColorDefault, .blue) MDCTextInputControllerLegacyDefault.trailingUnderlineLabelTextColorDefault = .white XCTAssertEqual(MDCTextInputControllerLegacyDefault.trailingUnderlineLabelTextColorDefault, .white) MDCTextInputControllerLegacyDefault.inlinePlaceholderFontDefault = UIFont.systemFont(ofSize: 4) XCTAssertEqual(MDCTextInputControllerLegacyDefault.inlinePlaceholderFontDefault, UIFont.systemFont(ofSize: 4)) MDCTextInputControllerLegacyDefault.inlinePlaceholderFontDefault = UIFont.systemFont(ofSize: 5) XCTAssertEqual(MDCTextInputControllerLegacyDefault.inlinePlaceholderFontDefault, UIFont.systemFont(ofSize: 5)) MDCTextInputControllerLegacyDefault.inlinePlaceholderFontDefault = UIFont.systemFont(ofSize: 6) XCTAssertEqual(MDCTextInputControllerLegacyDefault.inlinePlaceholderFontDefault, UIFont.systemFont(ofSize: 6)) // Default specific properties MDCTextInputControllerLegacyDefault.floatingPlaceholderNormalColorDefault = .red XCTAssertEqual(MDCTextInputControllerLegacyDefault.floatingPlaceholderNormalColorDefault, .red) MDCTextInputControllerLegacyDefault.floatingPlaceholderScaleDefault = 0.6 XCTAssertEqual(Float(MDCTextInputControllerLegacyDefault.floatingPlaceholderScaleDefault), 0.6) MDCTextInputControllerLegacyDefault.isFloatingEnabledDefault = false XCTAssertEqual(MDCTextInputControllerLegacyDefault.isFloatingEnabledDefault, false) // Test the changes to the class properties can propogate to an instance. controller = MDCTextInputControllerLegacyDefault(textInput: textField) XCTAssertEqual(controller.errorColor, MDCTextInputControllerLegacyDefault.errorColorDefault) XCTAssertEqual(controller.inlinePlaceholderColor, MDCTextInputControllerLegacyDefault.inlinePlaceholderColorDefault) XCTAssertEqual(controller.mdc_adjustsFontForContentSizeCategory, MDCTextInputControllerLegacyDefault.mdc_adjustsFontForContentSizeCategoryDefault) XCTAssertEqual(controller.activeColor, MDCTextInputControllerLegacyDefault.activeColorDefault) XCTAssertEqual(controller.normalColor, MDCTextInputControllerLegacyDefault.normalColorDefault) XCTAssertEqual(controller.underlineHeightActive, MDCTextInputControllerLegacyDefault.underlineHeightActiveDefault) XCTAssertEqual(controller.underlineHeightNormal, MDCTextInputControllerLegacyDefault.underlineHeightNormalDefault) XCTAssertEqual(controller.underlineViewMode, MDCTextInputControllerLegacyDefault.underlineViewModeDefault) XCTAssertEqual(controller.leadingUnderlineLabelTextColor, MDCTextInputControllerLegacyDefault.leadingUnderlineLabelTextColorDefault) XCTAssertEqual(controller.trailingUnderlineLabelTextColor, MDCTextInputControllerLegacyDefault.trailingUnderlineLabelTextColorDefault) XCTAssertEqual(controller.inlinePlaceholderFont, MDCTextInputControllerLegacyDefault.inlinePlaceholderFontDefault) XCTAssertEqual(controller.leadingUnderlineLabelFont, MDCTextInputControllerLegacyDefault.leadingUnderlineLabelFontDefault) XCTAssertEqual(controller.trailingUnderlineLabelFont, MDCTextInputControllerLegacyDefault.trailingUnderlineLabelFontDefault) // Default specific properties XCTAssertEqual(controller.floatingPlaceholderNormalColor, MDCTextInputControllerLegacyDefault.floatingPlaceholderNormalColorDefault) XCTAssertEqual(controller.isFloatingEnabled, MDCTextInputControllerLegacyDefault.isFloatingEnabledDefault) } func testLegacyFullWidth() { // Test the values of the class properties. XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.disabledColorDefault, .clear) XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.errorColorDefault, MDCPalette.red.accent400) XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.inlinePlaceholderColorDefault, UIColor(white: 0, alpha: CGFloat(Float(0.54)))) XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.mdc_adjustsFontForContentSizeCategoryDefault, true) XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.activeColorDefault, .clear) XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.normalColorDefault, .clear) XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.underlineHeightActiveDefault, 0) XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.underlineHeightNormalDefault, 0) XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.underlineViewModeDefault, .never) XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.leadingUnderlineLabelTextColorDefault, .clear) XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.trailingUnderlineLabelTextColorDefault, UIColor(white: 0, alpha: CGFloat(Float(0.54)))) XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.inlinePlaceholderFontDefault, UIFont.mdc_preferredFont(forMaterialTextStyle: .body1)) XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.leadingUnderlineLabelFontDefault, MDCTextInputControllerLegacyFullWidth.trailingUnderlineLabelFontDefault) XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.leadingUnderlineLabelFontDefault, UIFont.mdc_preferredFont(forMaterialTextStyle: .caption)) // Test the use of the class properties. let textField = MDCTextField() var controller = MDCTextInputControllerLegacyFullWidth(textInput: textField) XCTAssertEqual(controller.disabledColor, .clear) XCTAssertEqual(controller.errorColor, MDCTextInputControllerLegacyFullWidth.errorColorDefault) XCTAssertEqual(controller.inlinePlaceholderColor, MDCTextInputControllerLegacyFullWidth.inlinePlaceholderColorDefault) XCTAssertEqual(controller.mdc_adjustsFontForContentSizeCategory, MDCTextInputControllerLegacyFullWidth.mdc_adjustsFontForContentSizeCategoryDefault) XCTAssertEqual(controller.activeColor, MDCTextInputControllerLegacyFullWidth.activeColorDefault) XCTAssertEqual(controller.normalColor, MDCTextInputControllerLegacyFullWidth.normalColorDefault) XCTAssertEqual(controller.underlineHeightActive, MDCTextInputControllerLegacyFullWidth.underlineHeightActiveDefault) XCTAssertEqual(controller.underlineHeightNormal, MDCTextInputControllerLegacyFullWidth.underlineHeightNormalDefault) XCTAssertEqual(controller.underlineViewMode, MDCTextInputControllerLegacyFullWidth.underlineViewModeDefault) XCTAssertEqual(controller.leadingUnderlineLabelTextColor, MDCTextInputControllerLegacyFullWidth.leadingUnderlineLabelTextColorDefault) XCTAssertEqual(controller.trailingUnderlineLabelTextColor, MDCTextInputControllerLegacyFullWidth.trailingUnderlineLabelTextColorDefault) XCTAssertEqual(controller.inlinePlaceholderFont, MDCTextInputControllerLegacyFullWidth.inlinePlaceholderFontDefault) XCTAssertEqual(controller.leadingUnderlineLabelFont, nil) XCTAssertEqual(controller.trailingUnderlineLabelFont, MDCTextInputControllerLegacyFullWidth.trailingUnderlineLabelFontDefault) // Test the changes to the class properties. MDCTextInputControllerLegacyFullWidth.disabledColorDefault = .red XCTAssertNotEqual(MDCTextInputControllerLegacyFullWidth.disabledColorDefault, .red) MDCTextInputControllerLegacyFullWidth.errorColorDefault = .green XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.errorColorDefault, .green) MDCTextInputControllerLegacyFullWidth.inlinePlaceholderColorDefault = .orange XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.inlinePlaceholderColorDefault, .orange) MDCTextInputControllerLegacyFullWidth.mdc_adjustsFontForContentSizeCategoryDefault = false XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.mdc_adjustsFontForContentSizeCategoryDefault, false) MDCTextInputControllerLegacyFullWidth.activeColorDefault = .purple XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.activeColorDefault, .clear) MDCTextInputControllerLegacyFullWidth.normalColorDefault = .white XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.normalColorDefault, .clear) // The underline is not shown in this controller MDCTextInputControllerLegacyFullWidth.underlineHeightActiveDefault = 8 XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.underlineHeightActiveDefault, 0) MDCTextInputControllerLegacyFullWidth.underlineHeightNormalDefault = 7 XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.underlineHeightNormalDefault, 0) MDCTextInputControllerLegacyFullWidth.underlineViewModeDefault = .unlessEditing XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.underlineViewModeDefault, .never) MDCTextInputControllerLegacyFullWidth.leadingUnderlineLabelTextColorDefault = .brown XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.leadingUnderlineLabelTextColorDefault, .clear) MDCTextInputControllerLegacyFullWidth.trailingUnderlineLabelTextColorDefault = .cyan XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.trailingUnderlineLabelTextColorDefault, .cyan) MDCTextInputControllerLegacyFullWidth.inlinePlaceholderFontDefault = UIFont.systemFont(ofSize: 4) XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.inlinePlaceholderFontDefault, UIFont.systemFont(ofSize: 4)) MDCTextInputControllerLegacyFullWidth.inlinePlaceholderFontDefault = UIFont.systemFont(ofSize: 5) XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.inlinePlaceholderFontDefault, UIFont.systemFont(ofSize: 5)) MDCTextInputControllerLegacyFullWidth.inlinePlaceholderFontDefault = UIFont.systemFont(ofSize: 6) XCTAssertEqual(MDCTextInputControllerLegacyFullWidth.inlinePlaceholderFontDefault, UIFont.systemFont(ofSize: 6)) // Test the changes to the class properties can propogate to an instance. controller = MDCTextInputControllerLegacyFullWidth(textInput: textField) XCTAssertEqual(controller.disabledColor, .clear) XCTAssertEqual(controller.errorColor, MDCTextInputControllerLegacyFullWidth.errorColorDefault) XCTAssertEqual(controller.inlinePlaceholderColor, MDCTextInputControllerLegacyFullWidth.inlinePlaceholderColorDefault) XCTAssertEqual(controller.mdc_adjustsFontForContentSizeCategory, MDCTextInputControllerLegacyFullWidth.mdc_adjustsFontForContentSizeCategoryDefault) XCTAssertEqual(controller.activeColor, MDCTextInputControllerLegacyFullWidth.activeColorDefault) XCTAssertEqual(controller.normalColor, MDCTextInputControllerLegacyFullWidth.normalColorDefault) XCTAssertEqual(controller.underlineHeightActive, MDCTextInputControllerLegacyFullWidth.underlineHeightActiveDefault) XCTAssertEqual(controller.underlineHeightNormal, MDCTextInputControllerLegacyFullWidth.underlineHeightNormalDefault) XCTAssertEqual(controller.underlineViewMode, MDCTextInputControllerLegacyFullWidth.underlineViewModeDefault) XCTAssertEqual(controller.leadingUnderlineLabelTextColor, MDCTextInputControllerLegacyFullWidth.leadingUnderlineLabelTextColorDefault) XCTAssertEqual(controller.trailingUnderlineLabelTextColor, MDCTextInputControllerLegacyFullWidth.trailingUnderlineLabelTextColorDefault) XCTAssertEqual(controller.inlinePlaceholderFont, MDCTextInputControllerLegacyFullWidth.inlinePlaceholderFontDefault) XCTAssertEqual(controller.leadingUnderlineLabelFont, nil) XCTAssertEqual(controller.trailingUnderlineLabelFont, MDCTextInputControllerLegacyFullWidth.trailingUnderlineLabelFontDefault) } }
apache-2.0
80808f75f6a9716f008d62b570a438b0
58.857939
106
0.815347
7.103802
false
false
false
false
aryshin2016/swfWeibo
WeiBoSwift/WeiBoSwift/Classes/SwiftClass/Visitor/VisitorController.swift
1
2242
// // VisitorController.swift // WeiBoSwift // // Created by itogame on 2017/8/23. // Copyright © 2017年 itogame. All rights reserved. // import UIKit class VisitorController: UIViewController { @objc lazy var gradientLayer: CAGradientLayer = { let layT : CAGradientLayer = CAGradientLayer() layT.frame = self.gradientView.bounds layT.colors = [UIColor(white: 1, alpha: 1).cgColor, UIColor(white: 1, alpha: 0).cgColor] layT.startPoint = CGPoint(x: 0, y: 0.6) layT.endPoint = CGPoint(x: 0, y: 0) return layT }() // 旋转图 @IBOutlet weak var rotaIcon: UIImageView! // 渐变图 @IBOutlet weak var gradientView: UIView! override func viewDidLoad() { super.viewDidLoad() gradientView.backgroundColor = UIColor.clear // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let ani = CABasicAnimation(keyPath: "transform.rotation") ani.toValue = Double.pi * 2 ani.duration = 8.0 ani.repeatCount = Float(CGFloat.greatestFiniteMagnitude) ani.autoreverses = false ani.isRemovedOnCompletion = false ani.fillMode = kCAFillModeForwards rotaIcon.layer.add(ani, forKey: "rotation") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // ASLog(t: gradientView.frame) gradientView.layer.addSublayer(gradientLayer) //gradientView.layer.mask = gradientLayer } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) rotaIcon.layer.removeAllAnimations() } // 找感兴趣的人 @IBAction func findInterests(_ sender: UIButton) { ASLog("") } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
cbf8b0f7cf2b42bf7ddbb68df9b698b6
29.342466
106
0.645147
4.474747
false
false
false
false
flockoffiles/FFDataWrapper
FFDataWrapper/FFDataWrapper.swift
1
2713
// // FFDataWrapper.swift // FFDataWrapper // // Created by Sergey Novitsky on 21/09/2017. // Copyright © 2017 Flock of Files. All rights reserved. // import Foundation /// FFDataWrapper is a struct which wraps a piece of data and provides some custom internal representation for it. /// Conversions between original and internal representations can be specified with encoder and decoder closures. public struct FFDataWrapper { /// This coder transforms data in its first argument and writes the result into its second argument. public typealias Coder = (UnsafeBufferPointer<UInt8>, UnsafeMutableBufferPointer<UInt8>) -> Void public typealias Coders = (encoder: Coder, decoder: Coder) /// This coder transforms data in its first argument and writes the result into its second argument. /// It optionally takes some extra info that it can use to perform the transformation public typealias InfoCoder = (UnsafeBufferPointer<UInt8>, UnsafeMutableBufferPointer<UInt8>, Any?) -> Void public typealias InfoCoders = (encoder: InfoCoder, decoder: InfoCoder) internal enum CodersEnum { case coders(encoder: Coder, decoder: Coder) case infoCoders(encoder: InfoCoder, decoder: InfoCoder) } /// Class holding the data buffer and responsible for wiping the data when FFDataWrapper is destroyed. internal let dataRef: FFDataRef /// Closures to convert external representation to internal and back internal let storedCoders: CodersEnum /// Returns true if the wrapped data is empty; false otherwise. public var isEmpty: Bool { return dataRef.dataBuffer.count == 0 } /// Returns the length of the underlying data public var length: Int { return dataRef.dataBuffer.count } /// Returns the raw internal storage data. public var rawData: Data { return Data(dataRef.dataBuffer) } } /// Perform the given closure on the underlying data of two wrappers. /// /// - Parameters: /// - w1: First wrapper /// - w2: Second wrapper /// - block: The closure to perform on the underlying data of two wrappers. /// - Returns: Parametrized. /// - Throws: Will only throw if the provided closure throws. @discardableResult public func withDecodedData<ResultType>(_ w1: FFDataWrapper, _ w2: FFDataWrapper, _ block: (inout Data, inout Data) throws -> ResultType) rethrows -> ResultType { return try w1.mapData({ (w1Data: inout Data) -> ResultType in return try w2.mapData({ (w2Data: inout Data) -> ResultType in return try block(&w1Data, &w2Data) }) }) }
mit
debf18c80714748dbbb8be2b86d4ef63
36.150685
118
0.683997
4.749562
false
false
false
false
RevenueCat/purchases-ios
Sources/Purchasing/ReceiptFetcher.swift
1
5867
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // ReceiptFetcher.swift // // Created by Javier de Martín Gil on 8/7/21. // import Foundation class ReceiptFetcher { private let requestFetcher: StoreKitRequestFetcher private let receiptParser: ReceiptParser private let fileReader: FileReader let systemInfo: SystemInfo init( requestFetcher: StoreKitRequestFetcher, systemInfo: SystemInfo, receiptParser: ReceiptParser = .default, fileReader: FileReader = DefaultFileReader() ) { self.requestFetcher = requestFetcher self.systemInfo = systemInfo self.receiptParser = receiptParser self.fileReader = fileReader } func receiptData(refreshPolicy: ReceiptRefreshPolicy, completion: @escaping (Data?) -> Void) { switch refreshPolicy { case .always: Logger.debug(Strings.receipt.force_refreshing_receipt) self.refreshReceipt(completion) case .onlyIfEmpty: let receiptData = self.receiptData() let isReceiptEmpty = receiptData?.isEmpty ?? true if isReceiptEmpty { Logger.debug(Strings.receipt.refreshing_empty_receipt) self.refreshReceipt(completion) } else { completion(receiptData) } case let .retryUntilProductIsFound(productIdentifier, maximumRetries, sleepDuration): if #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) { Async.call(with: completion) { await self.refreshReceipt(untilProductIsFound: productIdentifier, maximumRetries: maximumRetries, sleepDuration: sleepDuration) } } else { Logger.warn(Strings.receipt.receipt_retrying_mechanism_not_available) self.receiptData(refreshPolicy: .always, completion: completion) } case .never: completion(self.receiptData()) } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func receiptData(refreshPolicy: ReceiptRefreshPolicy) async -> Data? { return await withCheckedContinuation { continuation in self.receiptData(refreshPolicy: refreshPolicy) { result in continuation.resume(returning: result) } } } } extension ReceiptFetcher { var receiptURL: URL? { guard var receiptURL = self.systemInfo.bundle.appStoreReceiptURL else { Logger.debug(Strings.receipt.no_sandbox_receipt_restore) return nil } #if os(watchOS) return self.watchOSReceiptURL(receiptURL) #else return receiptURL #endif } } // @unchecked because: // - Class is not `final` (it's mocked). This implicitly makes subclasses `Sendable` even if they're not thread-safe. extension ReceiptFetcher: @unchecked Sendable {} // MARK: - private extension ReceiptFetcher { func receiptData() -> Data? { guard let receiptURL = self.receiptURL else { return nil } guard let data = self.fileReader.contents(of: receiptURL) else { Logger.debug(Strings.receipt.unable_to_load_receipt) return nil } Logger.debug(Strings.receipt.loaded_receipt(url: receiptURL)) return data } func refreshReceipt(_ completion: @escaping (Data) -> Void) { self.requestFetcher.fetchReceiptData { let data = self.receiptData() guard let receiptData = data, !receiptData.isEmpty else { Logger.appleWarning(Strings.receipt.unable_to_load_receipt) completion(Data()) return } completion(receiptData) } } /// `async` version of `refreshReceipt(_:)` @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) func refreshReceipt() async -> Data { await withCheckedContinuation { continuation in self.refreshReceipt { continuation.resume(returning: $0) } } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) @MainActor private func refreshReceipt( untilProductIsFound productIdentifier: String, maximumRetries: Int, sleepDuration: DispatchTimeInterval ) async -> Data { var retries = 0 var data: Data = .init() repeat { retries += 1 data = await self.refreshReceipt() if !data.isEmpty { do { let receipt = try self.receiptParser.parse(from: data) if receipt.containsActivePurchase(forProductIdentifier: productIdentifier) { return data } else { Logger.appleWarning(Strings.receipt.local_receipt_missing_purchase( receipt, forProductIdentifier: productIdentifier )) } } catch { Logger.error(Strings.receipt.parse_receipt_locally_error(error: error)) } } Logger.debug(Strings.receipt.retrying_receipt_fetch_after(sleepDuration: sleepDuration)) try? await Task.sleep(nanoseconds: UInt64(sleepDuration.nanoseconds)) } while retries <= maximumRetries && !Task.isCancelled return data } }
mit
1fcf592b24f92f5da6fd79dc7af3b2d9
31.054645
117
0.587112
4.888333
false
false
false
false
nathantannar4/Parse-Dashboard-for-iOS-Pro
Parse Dashboard for iOS/Views/RippleButton.swift
1
8796
/* MIT License Copyright © 2018 Nathan Tannar. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit import QuartzCore open class RippleButton: UIButton { // MARK: - Initialization public override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override var backgroundColor: UIColor? { get { return super.backgroundColor } set { super.backgroundColor = newValue rippleBackgroundColor = newValue ?? .clear rippleColor = rippleBackgroundColor.isLight ? rippleBackgroundColor.darker() : rippleBackgroundColor.lighter() if let color = newValue { setTitleColor(color.isLight ? .black : .white, for: .normal) if tintColor.isDark && color.isDark { tintColor = .white } } } } open var ripplePercent: Float = 0.8 { didSet { setupRippleView() } } open var rippleColor: UIColor = UIColor(white: 0.9, alpha: 1) { didSet { rippleView.backgroundColor = rippleColor } } open var rippleBackgroundColor: UIColor { get { return rippleBackgroundView.backgroundColor ?? .clear } set { rippleBackgroundView.backgroundColor = newValue } } open var buttonCornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = buttonCornerRadius rippleBackgroundView.layer.cornerRadius = buttonCornerRadius } } open var rippleOverBounds: Bool = false open var shadowRippleRadius: Float = 1 open var shadowRippleEnable: Bool = false open var trackTouchLocation: Bool = true open var touchUpAnimationTime: Double = 0.6 let rippleView = UIView() let rippleBackgroundView = UIView() fileprivate var tempShadowRadius: CGFloat = 0 fileprivate var tempShadowOpacity: Float = 0 fileprivate var touchCenterLocation: CGPoint? fileprivate var rippleMask: CAShapeLayer? { if !rippleOverBounds { let maskLayer = CAShapeLayer() maskLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: layer.cornerRadius).cgPath return maskLayer } else { return nil } } open func pullImageToRight() { transform = CGAffineTransform(scaleX: -1.0, y: 1.0) titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0) imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0) } fileprivate func setup() { contentHorizontalAlignment = .center titleLabel?.textAlignment = .center imageView?.contentMode = .scaleAspectFit adjustsImageWhenHighlighted = false setupRippleView() addSubview(rippleBackgroundView) rippleBackgroundView.backgroundColor = rippleBackgroundColor rippleBackgroundView.fillSuperview() rippleBackgroundView.addSubview(rippleView) rippleBackgroundView.alpha = 0 if let imageView = imageView { bringSubview(toFront: imageView) } if let label = titleLabel { bringSubview(toFront: label) } } fileprivate func setupRippleView() { let size: CGFloat = bounds.width * CGFloat(ripplePercent) let x: CGFloat = (bounds.width/2) - (size/2) let y: CGFloat = (bounds.height/2) - (size/2) let corner: CGFloat = size/2 rippleView.backgroundColor = rippleColor rippleView.frame = CGRect(x: x, y: y, width: size, height: size) rippleView.layer.cornerRadius = corner } override open func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { if trackTouchLocation { touchCenterLocation = touch.location(in: self) } else { touchCenterLocation = CGPoint(x: bounds.width / 2, y: bounds.height / 2) } animate() return super.beginTracking(touch, with: event) } override open func cancelTracking(with event: UIEvent?) { super.cancelTracking(with: event) animateToNormal() } override open func endTracking(_ touch: UITouch?, with event: UIEvent?) { super.endTracking(touch, with: event) animateToNormal() } open func animate() { UIView.animate(withDuration: 0.1, delay: 0, options: UIViewAnimationOptions.allowUserInteraction, animations: { self.rippleBackgroundView.alpha = 1 }, completion: nil) rippleView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5) UIView.animate(withDuration: 0.7, delay: 0, options: [UIViewAnimationOptions.curveEaseOut, UIViewAnimationOptions.allowUserInteraction], animations: { self.rippleView.transform = CGAffineTransform.identity }, completion: nil) if shadowRippleEnable { let shadowAnim = CABasicAnimation(keyPath:"shadowRadius") shadowAnim.toValue = shadowRippleRadius let opacityAnim = CABasicAnimation(keyPath:"shadowOpacity") opacityAnim.toValue = 1 let groupAnim = CAAnimationGroup() groupAnim.duration = 0.7 groupAnim.fillMode = kCAFillModeForwards groupAnim.isRemovedOnCompletion = false groupAnim.animations = [shadowAnim, opacityAnim] layer.add(groupAnim, forKey:"shadow") } } open func animateToNormal() { UIView.animate(withDuration: 0.3, delay: 0.3, options: UIViewAnimationOptions.allowUserInteraction, animations: { self.rippleBackgroundView.alpha = 1 }, completion: { (success: Bool) -> Void in UIView.animate(withDuration: self.touchUpAnimationTime, delay: 0, options: UIViewAnimationOptions.allowUserInteraction, animations: { self.rippleBackgroundView.alpha = 0 }, completion: nil) }) UIView.animate(withDuration: 0.7, delay: 0, options: [.curveEaseOut, .beginFromCurrentState, .allowUserInteraction], animations: { self.rippleView.transform = CGAffineTransform.identity if self.shadowRippleEnable { let shadowAnim = CABasicAnimation(keyPath:"shadowRadius") shadowAnim.toValue = 0 let opacityAnim = CABasicAnimation(keyPath:"shadowOpacity") opacityAnim.toValue = 0 let groupAnim = CAAnimationGroup() groupAnim.duration = 0.7 groupAnim.fillMode = kCAFillModeForwards groupAnim.isRemovedOnCompletion = false groupAnim.animations = [shadowAnim, opacityAnim] self.layer.add(groupAnim, forKey:"shadowBack") } }, completion: nil) } override open func layoutSubviews() { super.layoutSubviews() setupRippleView() if let knownTouchCenterLocation = touchCenterLocation { rippleView.center = knownTouchCenterLocation } rippleBackgroundView.layer.frame = bounds rippleBackgroundView.layer.mask = rippleMask } }
mit
86eba5e1564476bd2cc2f4bd896d7b08
34.897959
145
0.612848
5.545397
false
false
false
false
Vaseltior/OYThisUI
Sources/OYTRecyclableViewRecycler.swift
1
2659
/* Copyright 2011-present Samuel GRAU Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import UIKit /** An object for efficiently reusing views by recycling and dequeuing them from a pool of views. This sort of object is what UITableView and AVPagingScrollView use to recycle their views. */ public class OYTRecyclableViewRecycler { public var reuseIdentifiersToRecycledViews: [String: [UIView]] = [String: [UIView]]() /** Dequeues a reusable view from the recycled views pool if one exists, otherwise returns nil. - parameter reuseIdentifier: Often the name of the class of view you wish to fetch. - returns: the reusable view if a view is found with the given identifier, otherwise `nil` */ public func dequeueReusableViewWithIdentifier(reuseIdentifier: String) -> UIView? { guard var views: [UIView] = self.reuseIdentifiersToRecycledViews[reuseIdentifier] else { return nil } let view = views.last! views.removeLast() if let v = view as? OYTRecyclable { v.oytPrepareForReuse() } return view } /** Adds a given view to the recycled views pool. - parameter view: The view to recycle. The reuse identifier will be retrieved from the view via the OVTRecyclable protocol */ public func recycleView(view: UIView) { view.removeFromSuperview() var reuseIdentifier: String? = nil if let v = view as? OYTRecyclable { reuseIdentifier = v.oytReuseIdentifier } if reuseIdentifier == nil { reuseIdentifier = NSStringFromClass(view.dynamicType) } if var views: [UIView] = self.reuseIdentifiersToRecycledViews[reuseIdentifier!] { views.append(view) } else { let views: [UIView] = [UIView](arrayLiteral: view) self.reuseIdentifiersToRecycledViews[reuseIdentifier!] = views } } /** Removes all of the views from the recycled views pool. */ public func reduceMemoryUsage() { self.removeAllViews() } // MARK: - Private /** Removes all the views in the recycler */ private func removeAllViews() { self.reuseIdentifiersToRecycledViews.removeAll(keepCapacity: false) } }
apache-2.0
b30855ee9bf5aefdf5c6fb04db6f90aa
29.918605
125
0.718315
4.468908
false
false
false
false
AnRanScheme/MagiRefresh
MagiRefresh/Classes/Layer/MagiReplicatorLayer.swift
3
15443
// // MagiReplicatorLayer.swift // MagiRefresh // // Created by anran on 2018/9/19. // Copyright © 2018年 anran. All rights reserved. // import UIKit public enum MagiReplicatorLayerAnimationStyle: Int { case woody case allen case circle case dot case arc case triangle } public class MagiReplicatorLayer: CALayer { struct RuntimeKey { static let leftDot = UnsafeRawPointer.init( bitPattern: "leftDot".hashValue) static let rightDot = UnsafeRawPointer.init( bitPattern: "RightDot".hashValue) } public var leftCircle: CAShapeLayer { set { objc_setAssociatedObject( self, RuntimeKey.leftDot!, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get { if let objc = objc_getAssociatedObject( self, RuntimeKey.leftDot!) as? CAShapeLayer { return objc } else { let objc = CAShapeLayer() objc.strokeColor = themeColor.cgColor objc.backgroundColor = themeColor.cgColor objc_setAssociatedObject( self, RuntimeKey.leftDot!, objc, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return objc } } } public var rightCircle: CAShapeLayer { set { objc_setAssociatedObject( self, RuntimeKey.rightDot!, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get { if let objc = objc_getAssociatedObject( self, RuntimeKey.rightDot!) as? CAShapeLayer { return objc } else { let objc = CAShapeLayer() objc.strokeColor = themeColor.cgColor objc.backgroundColor = themeColor.cgColor objc_setAssociatedObject( self, RuntimeKey.rightDot!, objc, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return objc } } } public lazy var replicatorLayer: CAReplicatorLayer = { let replicatorLayer = CAReplicatorLayer() replicatorLayer.backgroundColor = UIColor.clear.cgColor replicatorLayer.shouldRasterize = true replicatorLayer.rasterizationScale = UIScreen.main.scale return replicatorLayer }() public lazy var indicatorShapeLayer: CAShapeLayer = { let indicatorShapeLayer = CAShapeLayer() indicatorShapeLayer.contentsScale = UIScreen.main.scale indicatorShapeLayer.lineCap = CAShapeLayerLineCap.round return indicatorShapeLayer }() public var themeColor: UIColor = MagiRefreshDefaults.shared.themeColor { didSet { indicatorShapeLayer.strokeColor = themeColor.cgColor indicatorShapeLayer.backgroundColor = themeColor.cgColor } } public var animationStyle: MagiReplicatorLayerAnimationStyle = .woody { didSet { setNeedsLayout() } } override init(layer: Any) { super.init(layer: layer) } override init() { super.init() addSublayer(replicatorLayer) replicatorLayer.addSublayer(indicatorShapeLayer) indicatorShapeLayer.strokeColor = themeColor.cgColor indicatorShapeLayer.backgroundColor = themeColor.cgColor } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func layoutSublayers() { super.layoutSublayers() replicatorLayer.frame = bounds let padding: CGFloat = 10.0 switch animationStyle { case .woody: let h: CGFloat = magi_height / 3.0 let w: CGFloat = 3.0 let x: CGFloat = magi_width / 2.0 - (2.5 * w + padding * 2) let y: CGFloat = magi_height/2.0-h/2.0 indicatorShapeLayer.frame = CGRect(x: x, y: y, width: w, height: h) indicatorShapeLayer.cornerRadius = 1.0 indicatorShapeLayer.transform = CATransform3DMakeScale(0.8, 0.8, 0.8) replicatorLayer.instanceCount = 5 replicatorLayer.instanceDelay = 0.3/5 replicatorLayer.instanceTransform = CATransform3DMakeTranslation(padding, 0.0, 0.0) replicatorLayer.instanceBlueOffset = -0.01 replicatorLayer.instanceGreenOffset = -0.01 case .allen: let h: CGFloat = magi_height / 3.0 let w: CGFloat = 3.0 let x: CGFloat = magi_width / 2.0 - (2.5 * w + padding * 2) let y: CGFloat = magi_height/2.0-h/2.0 indicatorShapeLayer.frame = CGRect(x: x, y: y, width: w, height: h) indicatorShapeLayer.cornerRadius = 1.0 replicatorLayer.instanceCount = 5 replicatorLayer.instanceDelay = 0.3/5 replicatorLayer.instanceTransform = CATransform3DMakeTranslation(padding, 0.0, 0.0) replicatorLayer.instanceBlueOffset = -0.01 replicatorLayer.instanceGreenOffset = -0.01 case .circle: indicatorShapeLayer.frame = CGRect(x:magi_width/2.0 - 2.0, y: 10, width: 4.0, height: 4.0) indicatorShapeLayer.cornerRadius = 2.0 indicatorShapeLayer.transform = CATransform3DMakeScale(0.2, 0.2, 0.2) replicatorLayer.instanceCount = 12 replicatorLayer.instanceDelay = 0.8/12 let angle: CGFloat = CGFloat.pi*2/CGFloat(replicatorLayer.instanceCount) replicatorLayer.instanceTransform = CATransform3DMakeRotation(angle, 0, 0, 0.1) replicatorLayer.instanceBlueOffset = -0.01 replicatorLayer.instanceGreenOffset = -0.01 case .dot: let innerPadding: CGFloat = 30.0 let h: CGFloat = 8.0 let w: CGFloat = 8.0 let x: CGFloat = magi_width / 2.0 - (1.5 * w + innerPadding * 1) let y: CGFloat = magi_height/2.0 - h/2.0 indicatorShapeLayer.frame = CGRect(x: x, y: y, width: w, height: h) indicatorShapeLayer.cornerRadius = 4.0 replicatorLayer.instanceCount = 3 replicatorLayer.instanceDelay = 0.5/3 replicatorLayer.instanceTransform = CATransform3DMakeTranslation(innerPadding, 0.0, 0.0) case .arc: let h: CGFloat = magi_height - 10.0 let w: CGFloat = h let x: CGFloat = magi_width/2.0 - 0.5 * w let y: CGFloat = magi_height/2.0 - h/2.0 indicatorShapeLayer.frame = CGRect(x: x, y: y, width: w, height: h) indicatorShapeLayer.fillColor = UIColor.clear.cgColor indicatorShapeLayer.lineWidth = 3.0 indicatorShapeLayer.backgroundColor = UIColor.clear.cgColor let arcPath = UIBezierPath( arcCenter: CGPoint(x: w/2.0, y: h/2.0), radius: h/2.0, startAngle: CGFloat.pi/2.3, endAngle: -CGFloat.pi/2.3, clockwise: false) indicatorShapeLayer.path = arcPath.cgPath indicatorShapeLayer.strokeEnd = 0.1 replicatorLayer.instanceCount = 2 replicatorLayer.instanceTransform = CATransform3DMakeRotation(CGFloat.pi, 0, 0, 0.1) case .triangle: indicatorShapeLayer.frame = CGRect(x: replicatorLayer.magi_width/2.0, y:5.0, width: 8.0, height: 8.0) indicatorShapeLayer.cornerRadius = indicatorShapeLayer.magi_width/2.0 let topPoint: CGPoint = indicatorShapeLayer.position let leftPoint: CGPoint = CGPoint(x:topPoint.x-15, y:topPoint.y+23) let rightPoint: CGPoint = CGPoint(x:topPoint.x+15, y:topPoint.y+23) leftCircle.removeFromSuperlayer() rightCircle.removeFromSuperlayer() leftCircle.magi_size = indicatorShapeLayer.magi_size leftCircle.position = leftPoint leftCircle.cornerRadius = indicatorShapeLayer.cornerRadius replicatorLayer.addSublayer(leftCircle) rightCircle.magi_size = indicatorShapeLayer.magi_size rightCircle.position = rightPoint rightCircle.cornerRadius = indicatorShapeLayer.cornerRadius replicatorLayer.addSublayer(rightCircle) } } } extension MagiReplicatorLayer { fileprivate func animationKeyPath(keyPath: String, from fromValue: CGFloat, to toValue: CGFloat, duration: CFTimeInterval, repeatTime: Float)->CABasicAnimation { let animation: CABasicAnimation = CABasicAnimation(keyPath: keyPath) animation.fromValue = fromValue animation.toValue = toValue animation.duration = duration animation.repeatCount = repeatTime animation.isRemovedOnCompletion = false return animation } fileprivate func keyFrameAnimation(with path: UIBezierPath, duration: TimeInterval)->CAKeyframeAnimation { let animation: CAKeyframeAnimation = CAKeyframeAnimation() animation.keyPath = "position" animation.path = path.cgPath animation.duration = duration animation.repeatCount = Float.infinity animation.isRemovedOnCompletion = false return animation } fileprivate func trianglePath(with startPoint:CGPoint, vertexs: [CGPoint])->UIBezierPath { let topPoint: CGPoint = vertexs[0] let leftPoint: CGPoint = vertexs[1] let rightPoint: CGPoint = vertexs[2] let path = UIBezierPath() if startPoint.equalTo(topPoint) { path.move(to: startPoint) path.addLine(to: rightPoint) path.addLine(to: leftPoint) } else if startPoint.equalTo(leftPoint) { path.move(to: startPoint) path.addLine(to: topPoint) path.addLine(to: rightPoint) } else { path.move(to: startPoint) path.addLine(to: leftPoint) path.addLine(to: topPoint) } path.close() return path } } extension MagiReplicatorLayer: MagiAnimatableProtocol { public func startAnimating() { indicatorShapeLayer.removeAllAnimations() switch animationStyle { case .woody: let basicAnimation = animationKeyPath(keyPath: "transform.scale.y", from: 1.5, to: 0.0, duration: 0.3, repeatTime: Float.infinity) basicAnimation.autoreverses = true indicatorShapeLayer.add(basicAnimation, forKey: basicAnimation.keyPath) case .allen: let basicAnimation = animationKeyPath(keyPath: "position.y", from: indicatorShapeLayer.position.y+10, to: indicatorShapeLayer.position.y-10, duration: 0.3, repeatTime: Float.infinity) basicAnimation.autoreverses = true indicatorShapeLayer.add(basicAnimation, forKey: basicAnimation.keyPath) case .circle: let basicAnimation = animationKeyPath(keyPath: "transform.scale", from: 1.0, to: 0.2, duration: 0.8, repeatTime: Float.infinity) indicatorShapeLayer.add(basicAnimation, forKey: basicAnimation.keyPath) case .dot: let basicAnimation = animationKeyPath(keyPath: "transform.scale", from: 0.3, to: 2.5, duration: 0.5, repeatTime: Float.infinity) basicAnimation.autoreverses = true let opc = animationKeyPath(keyPath: "opacity", from: 0.1, to: 1.0, duration: 0.5, repeatTime: Float.infinity) opc.autoreverses = true let group = CAAnimationGroup() group.animations = [basicAnimation,opc] group.autoreverses = true group.repeatCount = Float.infinity group.duration = 0.5 indicatorShapeLayer.add(basicAnimation, forKey: basicAnimation.keyPath) case .arc: let basicAnimation = animationKeyPath(keyPath: "transform.rotation.z", from: CGFloat.pi*2, to: 0, duration:0.8, repeatTime: Float.infinity) indicatorShapeLayer.add(basicAnimation, forKey: basicAnimation.keyPath) case .triangle: let topPoint: CGPoint = indicatorShapeLayer.position let leftPoint: CGPoint = leftCircle.position let rightPoint: CGPoint = rightCircle.position let vertexs = [topPoint, leftPoint, rightPoint] let key0 = keyFrameAnimation(with: trianglePath(with: topPoint, vertexs: vertexs), duration: 1.5) indicatorShapeLayer.add(key0, forKey: key0.keyPath) let key1 = keyFrameAnimation(with: trianglePath(with: leftPoint, vertexs: vertexs), duration: 1.5) leftCircle.add(key1, forKey: key1.keyPath) let key2 = keyFrameAnimation(with: trianglePath(with: rightPoint, vertexs: vertexs), duration: 1.5) rightCircle.add(key2, forKey: key2.keyPath) } } public func stopAnimating() { indicatorShapeLayer.removeAllAnimations() switch animationStyle { case .woody: fallthrough case .allen: fallthrough case .circle: fallthrough case .dot: break case .arc: indicatorShapeLayer.strokeEnd = 0.1 case .triangle: leftCircle.removeAllAnimations() rightCircle.removeAllAnimations() } } }
mit
37e4b0af342cf27bd3040908f3f5af79
37.891688
113
0.537435
5.427065
false
false
false
false
tjw/swift
test/SILGen/objc_dictionary_bridging.swift
1
7122
// RUN: %empty-directory(%t) // RUN: %build-silgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -module-name objc_dictionary_bridging -emit-silgen -enable-sil-ownership %s | %FileCheck %s // REQUIRES: objc_interop import Foundation import gizmo @objc class Foo : NSObject { // Bridging dictionary parameters // CHECK-LABEL: sil hidden [thunk] @$S24objc_dictionary_bridging3FooC23bridge_Dictionary_param{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (NSDictionary, Foo) -> () func bridge_Dictionary_param(_ dict: Dictionary<Foo, Foo>) { // CHECK: bb0([[NSDICT:%[0-9]+]] : @unowned $NSDictionary, [[SELF:%[0-9]+]] : @unowned $Foo): // CHECK: [[NSDICT_COPY:%.*]] = copy_value [[NSDICT]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[CONVERTER:%[0-9]+]] = function_ref @$Ss10DictionaryV10FoundationE36_unconditionallyBridgeFromObjectiveCyAByxq_GSo12NSDictionaryCSgFZ // CHECK: [[OPT_NSDICT:%[0-9]+]] = enum $Optional<NSDictionary>, #Optional.some!enumelt.1, [[NSDICT_COPY]] : $NSDictionary // CHECK: [[DICT_META:%[0-9]+]] = metatype $@thin Dictionary<Foo, Foo>.Type // CHECK: [[DICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[OPT_NSDICT]], [[DICT_META]]) // CHECK: [[BORROWED_DICT:%.*]] = begin_borrow [[DICT]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @$S24objc_dictionary_bridging3FooC23bridge_Dictionary_param{{[_0-9a-zA-Z]*}}F // CHECK: [[RESULT:%[0-9]+]] = apply [[SWIFT_FN]]([[BORROWED_DICT]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@guaranteed Dictionary<Foo, Foo>, @guaranteed Foo) -> () // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: return [[RESULT]] : $() } // CHECK: } // end sil function '$S24objc_dictionary_bridging3FooC23bridge_Dictionary_param{{[_0-9a-zA-Z]*}}FTo' // Bridging dictionary results // CHECK-LABEL: sil hidden [thunk] @$S24objc_dictionary_bridging3FooC24bridge_Dictionary_result{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (Foo) -> @autoreleased NSDictionary func bridge_Dictionary_result() -> Dictionary<Foo, Foo> { // CHECK: bb0([[SELF:%[0-9]+]] : @unowned $Foo): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @$S24objc_dictionary_bridging3FooC24bridge_Dictionary_result{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo> // CHECK: [[DICT:%[0-9]+]] = apply [[SWIFT_FN]]([[BORROWED_SELF_COPY]]) : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo> // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: [[CONVERTER:%[0-9]+]] = function_ref @$Ss10DictionaryV10FoundationE19_bridgeToObjectiveCSo12NSDictionaryCyF // CHECK: [[BORROWED_DICT:%.*]] = begin_borrow [[DICT]] // CHECK: [[NSDICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[BORROWED_DICT]]) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary // CHECK: end_borrow [[BORROWED_DICT]] from [[DICT]] // CHECK: destroy_value [[DICT]] // CHECK: return [[NSDICT]] : $NSDictionary } // CHECK: } // end sil function '$S24objc_dictionary_bridging3FooC24bridge_Dictionary_result{{[_0-9a-zA-Z]*}}FTo' var property: Dictionary<Foo, Foo> = [:] // Property getter // CHECK-LABEL: sil hidden [thunk] @$S24objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CSo8NSObjectCs8Hashable10Foundationg_GvgTo : $@convention(objc_method) (Foo) -> @autoreleased NSDictionary // @$S24objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CSo8NSObjectCs8Hashable10Foundationg_Gvpfi // CHECK: bb0([[SELF:%[0-9]+]] : @unowned $Foo): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[GETTER:%[0-9]+]] = function_ref @$S24objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CSo8NSObjectCs8Hashable10Foundationg_Gvg : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo> // CHECK: [[DICT:%[0-9]+]] = apply [[GETTER]]([[BORROWED_SELF_COPY]]) : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo> // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: [[CONVERTER:%[0-9]+]] = function_ref @$Ss10DictionaryV10FoundationE19_bridgeToObjectiveCSo12NSDictionaryCyF // CHECK: [[BORROWED_DICT:%.*]] = begin_borrow [[DICT]] // CHECK: [[NSDICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[BORROWED_DICT]]) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary // CHECK: end_borrow [[BORROWED_DICT]] from [[DICT]] // CHECK: destroy_value [[DICT]] // CHECK: return [[NSDICT]] : $NSDictionary // CHECK: } // end sil function // Property setter // CHECK-LABEL: sil hidden [thunk] @$S24objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CSo8NSObjectCs8Hashable10Foundationg_GvsTo : $@convention(objc_method) (NSDictionary, Foo) -> () // CHECK: bb0([[NSDICT:%[0-9]+]] : @unowned $NSDictionary, [[SELF:%[0-9]+]] : @unowned $Foo): // CHECK: [[NSDICT_COPY:%.*]] = copy_value [[NSDICT]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[CONVERTER:%[0-9]+]] = function_ref @$Ss10DictionaryV10FoundationE36_unconditionallyBridgeFromObjectiveCyAByxq_GSo12NSDictionaryCSgFZ // CHECK: [[OPT_NSDICT:%[0-9]+]] = enum $Optional<NSDictionary>, #Optional.some!enumelt.1, [[NSDICT_COPY]] : $NSDictionary // CHECK: [[DICT_META:%[0-9]+]] = metatype $@thin Dictionary<Foo, Foo>.Type // CHECK: [[DICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[OPT_NSDICT]], [[DICT_META]]) // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[SETTER:%[0-9]+]] = function_ref @$S24objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CSo8NSObjectCs8Hashable10Foundationg_Gvs : $@convention(method) (@owned Dictionary<Foo, Foo>, @guaranteed Foo) -> () // CHECK: [[RESULT:%[0-9]+]] = apply [[SETTER]]([[DICT]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@owned Dictionary<Foo, Foo>, @guaranteed Foo) -> () // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: return [[RESULT]] : $() // CHECK-LABEL: sil hidden [thunk] @$S24objc_dictionary_bridging3FooC19nonVerbatimProperty{{[_0-9a-zA-Z]*}}vgTo : $@convention(objc_method) (Foo) -> @autoreleased NSDictionary // CHECK-LABEL: sil hidden [thunk] @$S24objc_dictionary_bridging3FooC19nonVerbatimProperty{{[_0-9a-zA-Z]*}}vsTo : $@convention(objc_method) (NSDictionary, Foo) -> () @objc var nonVerbatimProperty: Dictionary<String, Int> = [:] } func ==(x: Foo, y: Foo) -> Bool { }
apache-2.0
4d12c86212d93192e4431a01a6eac2c6
73.083333
224
0.646794
3.422522
false
false
false
false
aiwalle/LiveProject
LiveProject/Rank/Controller/LJDetailRankViewController.swift
1
2296
// // LJDetailRankViewController.swift // LiveProject // // Created by liang on 2017/10/26. // Copyright © 2017年 liang. All rights reserved. // import UIKit let kLJDetailRankViewCell = "LJDetailRankViewCell" class LJDetailRankViewController: LJSubrankViewController { var rankType : LJRankType lazy var tableView: UITableView = UITableView() fileprivate lazy var detailRankVM : LJDetailRankViewModel = LJDetailRankViewModel() init(rankType : LJRankType) { self.rankType = rankType super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupUI() loadData() } } extension LJDetailRankViewController { fileprivate func setupUI() { // 这里高度设定不够灵活 tableView.frame = CGRect(x: 0, y: 0, width: kDeviceWidth, height: kDeviceHeight-kNavigationBarHeight-kStatusBarHeight-kTabBarHeight-35) tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight] tableView.rowHeight = 50 view.addSubview(tableView) tableView.contentInset = UIEdgeInsets(top: 5, left: 0, bottom: 0, right: 0) tableView.backgroundColor = UIColor(r: 245, g: 245, b: 245) tableView.register(UINib(nibName: "LJDetailRankViewCell", bundle: nil), forCellReuseIdentifier: kLJDetailRankViewCell) tableView.dataSource = self tableView.delegate = self } func loadData() { detailRankVM.loadDetailRankData(rankType) { self.tableView.reloadData() } } } extension LJDetailRankViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return detailRankVM.rankModels.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: kLJDetailRankViewCell) as! LJDetailRankViewCell cell.rankNum = indexPath.row cell.rankModel = detailRankVM.rankModels[indexPath.row] return cell } }
mit
47024e5c8ba37f6e10c58dd39f89f447
31.471429
143
0.682798
4.55511
false
false
false
false
lorentey/swift
test/NameBinding/name_lookup.swift
2
29294
// RUN: %target-typecheck-verify-swift -typo-correction-limit 100 class ThisBase1 { init() { } var baseInstanceVar: Int var baseProp : Int { get { return 42 } set {} } func baseFunc0() {} func baseFunc1(_ a: Int) {} subscript(i: Int) -> Double { get { return Double(i) } set { baseInstanceVar = i } } class var baseStaticVar: Int = 42 // expected-error {{class stored properties not supported}} class var baseStaticProp: Int { get { return 42 } set {} } class func baseStaticFunc0() {} struct BaseNestedStruct {} // expected-note {{did you mean 'BaseNestedStruct'?}} class BaseNestedClass { init() { } } enum BaseNestedUnion { case BaseUnionX(Int) } typealias BaseNestedTypealias = Int // expected-note {{did you mean 'BaseNestedTypealias'?}} } class ThisDerived1 : ThisBase1 { override init() { super.init() } var derivedInstanceVar: Int var derivedProp : Int { get { return 42 } set {} } func derivedFunc0() {} func derivedFunc1(_ a: Int) {} subscript(i: Double) -> Int { get { return Int(i) } set { baseInstanceVar = Int(i) } } class var derivedStaticVar: Int = 42// expected-error {{class stored properties not supported}} class var derivedStaticProp: Int { get { return 42 } set {} } class func derivedStaticFunc0() {} struct DerivedNestedStruct {} class DerivedNestedClass { init() { } } enum DerivedNestedUnion { // expected-note {{did you mean 'DerivedNestedUnion'?}} case DerivedUnionX(Int) } typealias DerivedNestedTypealias = Int func testSelf1() { self.baseInstanceVar = 42 self.baseProp = 42 self.baseFunc0() self.baseFunc1(42) self[0] = 42.0 self.baseStaticVar = 42 // expected-error {{static member 'baseStaticVar' cannot be used on instance of type 'ThisDerived1'}} self.baseStaticProp = 42 // expected-error {{static member 'baseStaticProp' cannot be used on instance of type 'ThisDerived1'}} self.baseStaticFunc0() // expected-error {{static member 'baseStaticFunc0' cannot be used on instance of type 'ThisDerived1'}} self.baseExtProp = 42 self.baseExtFunc0() self.baseExtStaticVar = 42 self.baseExtStaticProp = 42 self.baseExtStaticFunc0() // expected-error {{static member 'baseExtStaticFunc0' cannot be used on instance of type 'ThisDerived1'}} var bs1 : BaseNestedStruct var bc1 : BaseNestedClass var bo1 : BaseNestedUnion = .BaseUnionX(42) var bt1 : BaseNestedTypealias var bs2 = self.BaseNestedStruct() // expected-error{{static member 'BaseNestedStruct' cannot be used on instance of type 'ThisDerived1'}} var bc2 = self.BaseNestedClass() // expected-error{{static member 'BaseNestedClass' cannot be used on instance of type 'ThisDerived1'}} var bo2 = self.BaseUnionX(24) // expected-error {{value of type 'ThisDerived1' has no member 'BaseUnionX'}} var bo3 = self.BaseNestedUnion.BaseUnionX(24) // expected-error{{static member 'BaseNestedUnion' cannot be used on instance of type 'ThisDerived1'}} var bt2 = self.BaseNestedTypealias(42) // expected-error{{static member 'BaseNestedTypealias' cannot be used on instance of type 'ThisDerived1'}} var bes1 : BaseExtNestedStruct var bec1 : BaseExtNestedClass var beo1 : BaseExtNestedUnion = .BaseExtUnionX(42) var bet1 : BaseExtNestedTypealias var bes2 = self.BaseExtNestedStruct() // expected-error{{static member 'BaseExtNestedStruct' cannot be used on instance of type 'ThisDerived1'}} var bec2 = self.BaseExtNestedClass() // expected-error{{static member 'BaseExtNestedClass' cannot be used on instance of type 'ThisDerived1'}} var beo2 = self.BaseExtUnionX(24) // expected-error {{value of type 'ThisDerived1' has no member 'BaseExtUnionX'}} var beo3 = self.BaseExtNestedUnion.BaseExtUnionX(24) // expected-error{{static member 'BaseExtNestedUnion' cannot be used on instance of type 'ThisDerived1'}} var bet2 = self.BaseExtNestedTypealias(42) // expected-error{{static member 'BaseExtNestedTypealias' cannot be used on instance of type 'ThisDerived1'}} self.derivedInstanceVar = 42 self.derivedProp = 42 self.derivedFunc0() self.derivedStaticVar = 42 // expected-error {{static member 'derivedStaticVar' cannot be used on instance of type 'ThisDerived1'}} self.derivedStaticProp = 42 // expected-error {{static member 'derivedStaticProp' cannot be used on instance of type 'ThisDerived1'}} self.derivedStaticFunc0() // expected-error {{static member 'derivedStaticFunc0' cannot be used on instance of type 'ThisDerived1'}} self.derivedExtProp = 42 self.derivedExtFunc0() self.derivedExtStaticVar = 42 self.derivedExtStaticProp = 42 self.derivedExtStaticFunc0() // expected-error {{static member 'derivedExtStaticFunc0' cannot be used on instance of type 'ThisDerived1'}} var ds1 : DerivedNestedStruct var dc1 : DerivedNestedClass var do1 : DerivedNestedUnion = .DerivedUnionX(42) var dt1 : DerivedNestedTypealias var ds2 = self.DerivedNestedStruct() // expected-error{{static member 'DerivedNestedStruct' cannot be used on instance of type 'ThisDerived1'}} var dc2 = self.DerivedNestedClass() // expected-error{{static member 'DerivedNestedClass' cannot be used on instance of type 'ThisDerived1'}} var do2 = self.DerivedUnionX(24) // expected-error {{value of type 'ThisDerived1' has no member 'DerivedUnionX'}} var do3 = self.DerivedNestedUnion.DerivedUnionX(24) // expected-error{{static member 'DerivedNestedUnion' cannot be used on instance of type 'ThisDerived1'}} var dt2 = self.DerivedNestedTypealias(42) // expected-error{{static member 'DerivedNestedTypealias' cannot be used on instance of type 'ThisDerived1'}} var des1 : DerivedExtNestedStruct var dec1 : DerivedExtNestedClass var deo1 : DerivedExtNestedUnion = .DerivedExtUnionX(42) var det1 : DerivedExtNestedTypealias var des2 = self.DerivedExtNestedStruct() // expected-error{{static member 'DerivedExtNestedStruct' cannot be used on instance of type 'ThisDerived1'}} var dec2 = self.DerivedExtNestedClass() // expected-error{{static member 'DerivedExtNestedClass' cannot be used on instance of type 'ThisDerived1'}} var deo2 = self.DerivedExtUnionX(24) // expected-error {{value of type 'ThisDerived1' has no member 'DerivedExtUnionX'}} var deo3 = self.DerivedExtNestedUnion.DerivedExtUnionX(24) // expected-error{{static member 'DerivedExtNestedUnion' cannot be used on instance of type 'ThisDerived1'}} var det2 = self.DerivedExtNestedTypealias(42) // expected-error{{static member 'DerivedExtNestedTypealias' cannot be used on instance of type 'ThisDerived1'}} self.Type // expected-error {{value of type 'ThisDerived1' has no member 'Type'}} } func testSuper1() { super.baseInstanceVar = 42 super.baseProp = 42 super.baseFunc0() super.baseFunc1(42) super[0] = 42.0 super.baseStaticVar = 42 // expected-error {{static member 'baseStaticVar' cannot be used on instance of type 'ThisBase1'}} super.baseStaticProp = 42 // expected-error {{static member 'baseStaticProp' cannot be used on instance of type 'ThisBase1'}} super.baseStaticFunc0() // expected-error {{static member 'baseStaticFunc0' cannot be used on instance of type 'ThisBase1'}} super.baseExtProp = 42 super.baseExtFunc0() super.baseExtStaticVar = 42 super.baseExtStaticProp = 42 super.baseExtStaticFunc0() // expected-error {{static member 'baseExtStaticFunc0' cannot be used on instance of type 'ThisBase1'}} var bs2 = super.BaseNestedStruct() // expected-error{{static member 'BaseNestedStruct' cannot be used on instance of type 'ThisBase1'}} var bc2 = super.BaseNestedClass() // expected-error{{static member 'BaseNestedClass' cannot be used on instance of type 'ThisBase1'}} var bo2 = super.BaseUnionX(24) // expected-error {{value of type 'ThisBase1' has no member 'BaseUnionX'}} var bo3 = super.BaseNestedUnion.BaseUnionX(24) // expected-error{{static member 'BaseNestedUnion' cannot be used on instance of type 'ThisBase1'}} var bt2 = super.BaseNestedTypealias(42) // expected-error{{static member 'BaseNestedTypealias' cannot be used on instance of type 'ThisBase1'}} var bes2 = super.BaseExtNestedStruct() // expected-error{{static member 'BaseExtNestedStruct' cannot be used on instance of type 'ThisBase1'}} var bec2 = super.BaseExtNestedClass() // expected-error{{static member 'BaseExtNestedClass' cannot be used on instance of type 'ThisBase1'}} var beo2 = super.BaseExtUnionX(24) // expected-error {{value of type 'ThisBase1' has no member 'BaseExtUnionX'}} var beo3 = super.BaseExtNestedUnion.BaseExtUnionX(24) // expected-error{{static member 'BaseExtNestedUnion' cannot be used on instance of type 'ThisBase1'}} var bet2 = super.BaseExtNestedTypealias(42) // expected-error{{static member 'BaseExtNestedTypealias' cannot be used on instance of type 'ThisBase1'}} super.derivedInstanceVar = 42 // expected-error {{value of type 'ThisBase1' has no member 'derivedInstanceVar'}} super.derivedProp = 42 // expected-error {{value of type 'ThisBase1' has no member 'derivedProp'}} super.derivedFunc0() // expected-error {{value of type 'ThisBase1' has no member 'derivedFunc0'}} super.derivedStaticVar = 42 // expected-error {{value of type 'ThisBase1' has no member 'derivedStaticVar'}} super.derivedStaticProp = 42 // expected-error {{value of type 'ThisBase1' has no member 'derivedStaticProp'}} super.derivedStaticFunc0() // expected-error {{value of type 'ThisBase1' has no member 'derivedStaticFunc0'}} super.derivedExtProp = 42 // expected-error {{value of type 'ThisBase1' has no member 'derivedExtProp'}} super.derivedExtFunc0() // expected-error {{value of type 'ThisBase1' has no member 'derivedExtFunc0'}} super.derivedExtStaticVar = 42 // expected-error {{value of type 'ThisBase1' has no member 'derivedExtStaticVar'; did you mean 'baseExtStaticVar'?}} super.derivedExtStaticProp = 42 // expected-error {{value of type 'ThisBase1' has no member 'derivedExtStaticProp'; did you mean 'baseExtStaticProp'?}} super.derivedExtStaticFunc0() // expected-error {{value of type 'ThisBase1' has no member 'derivedExtStaticFunc0'}} var ds2 = super.DerivedNestedStruct() // expected-error {{value of type 'ThisBase1' has no member 'DerivedNestedStruct'}} var dc2 = super.DerivedNestedClass() // expected-error {{value of type 'ThisBase1' has no member 'DerivedNestedClass'}} var do2 = super.DerivedUnionX(24) // expected-error {{value of type 'ThisBase1' has no member 'DerivedUnionX'}} var do3 = super.DerivedNestedUnion.DerivedUnionX(24) // expected-error {{value of type 'ThisBase1' has no member 'DerivedNestedUnion'}} var dt2 = super.DerivedNestedTypealias(42) // expected-error {{value of type 'ThisBase1' has no member 'DerivedNestedTypealias'}} var des2 = super.DerivedExtNestedStruct() // expected-error {{value of type 'ThisBase1' has no member 'DerivedExtNestedStruct'}} var dec2 = super.DerivedExtNestedClass() // expected-error {{value of type 'ThisBase1' has no member 'DerivedExtNestedClass'}} var deo2 = super.DerivedExtUnionX(24) // expected-error {{value of type 'ThisBase1' has no member 'DerivedExtUnionX'}} var deo3 = super.DerivedExtNestedUnion.DerivedExtUnionX(24) // expected-error {{value of type 'ThisBase1' has no member 'DerivedExtNestedUnion'}} var det2 = super.DerivedExtNestedTypealias(42) // expected-error {{value of type 'ThisBase1' has no member 'DerivedExtNestedTypealias'}} super.Type // expected-error {{value of type 'ThisBase1' has no member 'Type'}} } class func staticTestSelf1() { self.baseInstanceVar = 42 // expected-error {{member 'baseInstanceVar' cannot be used on type 'ThisDerived1'}} self.baseProp = 42 // expected-error {{member 'baseProp' cannot be used on type 'ThisDerived1'}} self.baseFunc0() // expected-error {{instance member 'baseFunc0' cannot be used on type 'ThisDerived1'}} self.baseFunc0(ThisBase1())() // expected-error {{cannot convert value of type 'ThisBase1' to expected argument type 'ThisDerived1'}} self.baseFunc0(ThisDerived1())() self.baseFunc1(42) // expected-error {{instance member 'baseFunc1' cannot be used on type 'ThisDerived1'}} self.baseFunc1(ThisBase1())(42) // expected-error {{cannot convert value of type 'ThisBase1' to expected argument type 'ThisDerived1'}} self.baseFunc1(ThisDerived1())(42) self[0] = 42.0 // expected-error {{instance member 'subscript' cannot be used on type 'ThisDerived1'}} self.baseStaticVar = 42 self.baseStaticProp = 42 self.baseStaticFunc0() self.baseExtProp = 42 // expected-error {{member 'baseExtProp' cannot be used on type 'ThisDerived1'}} self.baseExtFunc0() // expected-error {{instance member 'baseExtFunc0' cannot be used on type 'ThisDerived1'}} self.baseExtStaticVar = 42 // expected-error {{instance member 'baseExtStaticVar' cannot be used on type 'ThisDerived1'}} self.baseExtStaticProp = 42 // expected-error {{member 'baseExtStaticProp' cannot be used on type 'ThisDerived1'}} self.baseExtStaticFunc0() var bs1 : BaseNestedStruct var bc1 : BaseNestedClass var bo1 : BaseNestedUnion = .BaseUnionX(42) var bt1 : BaseNestedTypealias var bs2 = self.BaseNestedStruct() var bc2 = self.BaseNestedClass() var bo2 = self.BaseUnionX(24) // expected-error {{type 'ThisDerived1' has no member 'BaseUnionX'}} var bo3 = self.BaseNestedUnion.BaseUnionX(24) var bt2 = self.BaseNestedTypealias() self.derivedInstanceVar = 42 // expected-error {{member 'derivedInstanceVar' cannot be used on type 'ThisDerived1'}} self.derivedProp = 42 // expected-error {{member 'derivedProp' cannot be used on type 'ThisDerived1'}} self.derivedFunc0() // expected-error {{instance member 'derivedFunc0' cannot be used on type 'ThisDerived1'}} self.derivedFunc0(ThisBase1())() // expected-error {{cannot convert value of type 'ThisBase1' to expected argument type 'ThisDerived1'}} self.derivedFunc0(ThisDerived1())() self.derivedStaticVar = 42 self.derivedStaticProp = 42 self.derivedStaticFunc0() self.derivedExtProp = 42 // expected-error {{member 'derivedExtProp' cannot be used on type 'ThisDerived1'}} self.derivedExtFunc0() // expected-error {{instance member 'derivedExtFunc0' cannot be used on type 'ThisDerived1'}} self.derivedExtStaticVar = 42 // expected-error {{instance member 'derivedExtStaticVar' cannot be used on type 'ThisDerived1'}} self.derivedExtStaticProp = 42 // expected-error {{member 'derivedExtStaticProp' cannot be used on type 'ThisDerived1'}} self.derivedExtStaticFunc0() var ds1 : DerivedNestedStruct var dc1 : DerivedNestedClass var do1 : DerivedNestedUnion = .DerivedUnionX(42) var dt1 : DerivedNestedTypealias var ds2 = self.DerivedNestedStruct() var dc2 = self.DerivedNestedClass() var do2 = self.DerivedUnionX(24) // expected-error {{type 'ThisDerived1' has no member 'DerivedUnionX'}} var do3 = self.DerivedNestedUnion.DerivedUnionX(24) var dt2 = self.DerivedNestedTypealias() var des1 : DerivedExtNestedStruct var dec1 : DerivedExtNestedClass var deo1 : DerivedExtNestedUnion = .DerivedExtUnionX(42) var det1 : DerivedExtNestedTypealias var des2 = self.DerivedExtNestedStruct() var dec2 = self.DerivedExtNestedClass() var deo2 = self.DerivedExtUnionX(24) // expected-error {{type 'ThisDerived1' has no member 'DerivedExtUnionX'}} var deo3 = self.DerivedExtNestedUnion.DerivedExtUnionX(24) var det2 = self.DerivedExtNestedTypealias() self.Type // expected-error {{type 'ThisDerived1' has no member 'Type'}} } class func staticTestSuper1() { super.baseInstanceVar = 42 // expected-error {{member 'baseInstanceVar' cannot be used on type 'ThisBase1'}} super.baseProp = 42 // expected-error {{member 'baseProp' cannot be used on type 'ThisBase1'}} super.baseFunc0() // expected-error {{instance member 'baseFunc0' cannot be used on type 'ThisBase1'}} super.baseFunc0(ThisBase1())() super.baseFunc1(42) // expected-error {{instance member 'baseFunc1' cannot be used on type 'ThisBase1'}} super.baseFunc1(ThisBase1())(42) super[0] = 42.0 // expected-error {{instance member 'subscript' cannot be used on type 'ThisBase1'}} super.baseStaticVar = 42 super.baseStaticProp = 42 super.baseStaticFunc0() super.baseExtProp = 42 // expected-error {{member 'baseExtProp' cannot be used on type 'ThisBase1'}} super.baseExtFunc0() // expected-error {{instance member 'baseExtFunc0' cannot be used on type 'ThisBase1'}} super.baseExtStaticVar = 42 // expected-error {{instance member 'baseExtStaticVar' cannot be used on type 'ThisBase1'}} super.baseExtStaticProp = 42 // expected-error {{member 'baseExtStaticProp' cannot be used on type 'ThisBase1'}} super.baseExtStaticFunc0() var bs2 = super.BaseNestedStruct() var bc2 = super.BaseNestedClass() var bo2 = super.BaseUnionX(24) // expected-error {{type 'ThisBase1' has no member 'BaseUnionX'}} var bo3 = super.BaseNestedUnion.BaseUnionX(24) var bt2 = super.BaseNestedTypealias() super.derivedInstanceVar = 42 // expected-error {{type 'ThisBase1' has no member 'derivedInstanceVar'}} super.derivedProp = 42 // expected-error {{type 'ThisBase1' has no member 'derivedProp'}} super.derivedFunc0() // expected-error {{type 'ThisBase1' has no member 'derivedFunc0'}} super.derivedStaticVar = 42 // expected-error {{type 'ThisBase1' has no member 'derivedStaticVar'}} super.derivedStaticProp = 42 // expected-error {{type 'ThisBase1' has no member 'derivedStaticProp'}} super.derivedStaticFunc0() // expected-error {{type 'ThisBase1' has no member 'derivedStaticFunc0'}} super.derivedExtProp = 42 // expected-error {{type 'ThisBase1' has no member 'derivedExtProp'}} super.derivedExtFunc0() // expected-error {{type 'ThisBase1' has no member 'derivedExtFunc0'}} super.derivedExtStaticVar = 42 // expected-error {{type 'ThisBase1' has no member 'derivedExtStaticVar'; did you mean 'baseExtStaticVar'?}} super.derivedExtStaticProp = 42 // expected-error {{type 'ThisBase1' has no member 'derivedExtStaticProp'; did you mean 'baseExtStaticProp'?}} super.derivedExtStaticFunc0() // expected-error {{type 'ThisBase1' has no member 'derivedExtStaticFunc0'; did you mean 'baseExtStaticFunc0'?}} var ds2 = super.DerivedNestedStruct() // expected-error {{type 'ThisBase1' has no member 'DerivedNestedStruct'}} var dc2 = super.DerivedNestedClass() // expected-error {{type 'ThisBase1' has no member 'DerivedNestedClass'}} var do2 = super.DerivedUnionX(24) // expected-error {{type 'ThisBase1' has no member 'DerivedUnionX'}} var do3 = super.DerivedNestedUnion.DerivedUnionX(24) // expected-error {{type 'ThisBase1' has no member 'DerivedNestedUnion'}} var dt2 = super.DerivedNestedTypealias(42) // expected-error {{type 'ThisBase1' has no member 'DerivedNestedTypealias'}} var des2 = super.DerivedExtNestedStruct() // expected-error {{type 'ThisBase1' has no member 'DerivedExtNestedStruct'; did you mean 'BaseExtNestedStruct'?}} var dec2 = super.DerivedExtNestedClass() // expected-error {{type 'ThisBase1' has no member 'DerivedExtNestedClass'; did you mean 'BaseExtNestedClass'?}} var deo2 = super.DerivedExtUnionX(24) // expected-error {{type 'ThisBase1' has no member 'DerivedExtUnionX'}} var deo3 = super.DerivedExtNestedUnion.DerivedExtUnionX(24) // expected-error {{type 'ThisBase1' has no member 'DerivedExtNestedUnion'; did you mean 'BaseExtNestedUnion'?}} var det2 = super.DerivedExtNestedTypealias(42) // expected-error {{type 'ThisBase1' has no member 'DerivedExtNestedTypealias'; did you mean 'BaseExtNestedTypealias'?}} super.Type // expected-error {{type 'ThisBase1' has no member 'Type'}} } } extension ThisBase1 { var baseExtProp : Int { get { return 42 } set {} } func baseExtFunc0() {} var baseExtStaticVar: Int // expected-error {{extensions must not contain stored properties}} // expected-note 2 {{'baseExtStaticVar' declared here}} var baseExtStaticProp: Int { // expected-note 2 {{'baseExtStaticProp' declared here}} get { return 42 } set {} } class func baseExtStaticFunc0() {} // expected-note {{'baseExtStaticFunc0' declared here}} struct BaseExtNestedStruct {} // expected-note {{did you mean 'BaseExtNestedStruct'?}} // expected-note {{'BaseExtNestedStruct' declared here}} class BaseExtNestedClass { // expected-note {{'BaseExtNestedClass' declared here}} init() { } } enum BaseExtNestedUnion { // expected-note {{'BaseExtNestedUnion' declared here}} case BaseExtUnionX(Int) } typealias BaseExtNestedTypealias = Int // expected-note {{did you mean 'BaseExtNestedTypealias'?}} // expected-note {{'BaseExtNestedTypealias' declared here}} } extension ThisDerived1 { var derivedExtProp : Int { get { return 42 } set {} } func derivedExtFunc0() {} var derivedExtStaticVar: Int // expected-error {{extensions must not contain stored properties}} var derivedExtStaticProp: Int { get { return 42 } set {} } class func derivedExtStaticFunc0() {} struct DerivedExtNestedStruct {} class DerivedExtNestedClass { init() { } } enum DerivedExtNestedUnion { // expected-note {{did you mean 'DerivedExtNestedUnion'?}} case DerivedExtUnionX(Int) } typealias DerivedExtNestedTypealias = Int } // <rdar://problem/11554141> func shadowbug() { let Foo = 10 func g() { struct S { var x : Foo typealias Foo = Int } } _ = Foo } func scopebug() { let Foo = 10 struct S { typealias Foo = Int } _ = Foo } struct Ordering { var x : Foo typealias Foo = Int } // <rdar://problem/12202655> class Outer { class Inner {} class MoreInner : Inner {} } func makeGenericStruct<S>(_ x: S) -> GenericStruct<S> { return GenericStruct<S>() } struct GenericStruct<T> {} // <rdar://problem/13952064> extension Outer { class ExtInner {} } // <rdar://problem/14149537> func useProto<R : MyProto>(_ value: R) -> R.Element { return value.get() } protocol MyProto { associatedtype Element func get() -> Element } // <rdar://problem/14488311> struct DefaultArgumentFromExtension { func g(_ x: @escaping (DefaultArgumentFromExtension) -> () -> () = f) { let f = 42 var x2 = x x2 = f // expected-error{{cannot assign value of type 'Int' to type '(DefaultArgumentFromExtension) -> () -> ()'}} _ = x2 } var x : (DefaultArgumentFromExtension) -> () -> () = f } extension DefaultArgumentFromExtension { func f() {} } struct MyStruct { var state : Bool init() { state = true } mutating func mod() {state = false} // expected-note @+1 {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} func foo() { mod() } // expected-error {{cannot use mutating member on immutable value: 'self' is immutable}} } // <rdar://problem/19935319> QoI: poor diagnostic initializing a variable with a non-class func class Test19935319 { let i = getFoo() // expected-error {{cannot use instance member 'getFoo' within property initializer; property initializers run before 'self' is available}} func getFoo() -> Int {} } class Test19935319G<T> { let i = getFoo() // expected-error@-1 {{cannot use instance member 'getFoo' within property initializer; property initializers run before 'self' is available}} func getFoo() -> Int { return 42 } } // <rdar://problem/27013358> Crash using instance member as default parameter class rdar27013358 { let defaultValue = 1 func returnTwo() -> Int { return 2 } init(defaulted value: Int = defaultValue) {} // expected-error {{cannot use instance member 'defaultValue' as a default parameter}} init(another value: Int = returnTwo()) {} // expected-error {{cannot use instance member 'returnTwo' as a default parameter}} } class rdar27013358G<T> { let defaultValue = 1 func returnTwo() -> Int { return 2 } init(defaulted value: Int = defaultValue) {} // expected-error {{cannot use instance member 'defaultValue' as a default parameter}} init(another value: Int = returnTwo()) {} // expected-error {{cannot use instance member 'returnTwo' as a default parameter}} } // <rdar://problem/23904262> QoI: ivar default initializer cannot reference other default initialized ivars? class r23904262 { let x = 1 let y = x // expected-error {{cannot use instance member 'x' within property initializer; property initializers run before 'self' is available}} } // <rdar://problem/21677702> Static method reference in static var doesn't work class r21677702 { static func method(value: Int) -> Int { return value } static let x = method(value: 123) static let y = method(123) // expected-error {{missing argument label 'value:' in call}} } // <rdar://problem/31762378> lazy properties don't have to use "self." in their initializers. class r16954496 { func bar() {} lazy var x: Array<() -> Void> = [bar] } // <rdar://problem/27413116> [Swift] Using static constant defined in enum when in switch statement doesn't compile enum MyEnum { case one case two case oneTwoThree static let kMyConstant = "myConstant" } switch "someString" { case MyEnum.kMyConstant: // this causes a compiler error print("yay") case MyEnum.self.kMyConstant: // this works fine print("hmm") default: break } func foo() { _ = MyEnum.One // expected-error {{enum type 'MyEnum' has no case 'One'; did you mean 'one'?}}{{14-17=one}} _ = MyEnum.Two // expected-error {{enum type 'MyEnum' has no case 'Two'; did you mean 'two'?}}{{14-17=two}} _ = MyEnum.OneTwoThree // expected-error {{enum type 'MyEnum' has no case 'OneTwoThree'; did you mean 'oneTwoThree'?}}{{14-25=oneTwoThree}} } enum MyGenericEnum<T> { case one(T) case oneTwo(T) } func foo1() { _ = MyGenericEnum<Int>.One // expected-error {{enum type 'MyGenericEnum<Int>' has no case 'One'; did you mean 'one'?}}{{26-29=one}} _ = MyGenericEnum<Int>.OneTwo // expected-error {{enum type 'MyGenericEnum<Int>' has no case 'OneTwo'; did you mean 'oneTwo'?}}{{26-32=oneTwo}} } // SR-4082 func foo2() { let x = 5 if x < 0, let x = Optional(1) { } // expected-warning {{immutable value 'x' was never used; consider replacing with '_' or removing it}} } struct Person { let name: String? } struct Company { // expected-note 2{{'Company' declared here}} let owner: Person? } func test1() { let example: Company? = Company(owner: Person(name: "Owner")) if let person = aCompany.owner, // expected-error {{use of unresolved identifier 'aCompany'; did you mean 'Company'?}} let aCompany = example { _ = person } } func test2() { let example: Company? = Company(owner: Person(name: "Owner")) guard let person = aCompany.owner, // expected-error {{use of unresolved identifier 'aCompany'; did you mean 'Company'?}} let aCompany = example else { return } } func test3() { var c: String? = "c" // expected-note {{'c' declared here}} if let a = b = c, let b = c { // expected-error {{use of unresolved identifier 'b'; did you mean 'c'?}} _ = b } } // rdar://problem/22587551 class ShadowingGenericParameter<T> { typealias T = Int func foo (t : T) {} } _ = ShadowingGenericParameter<String>().foo(t: "hi") // rdar://problem/51266778 struct PatternBindingWithTwoVars1 { var x = 3, y = x } // expected-error@-1 {{cannot use instance member 'x' within property initializer; property initializers run before 'self' is available}} struct PatternBindingWithTwoVars2 { var x = y, y = 3 } // expected-error@-1 {{cannot use instance member 'y' within property initializer; property initializers run before 'self' is available}} struct PatternBindingWithTwoVars3 { var x = y, y = x } // expected-error@-1 {{cannot use instance member 'x' within property initializer; property initializers run before 'self' is available}} // expected-error@-2 {{cannot use instance member 'y' within property initializer; property initializers run before 'self' is available}} // expected-error@-3 {{circular reference}} // expected-note@-4 {{through reference here}} // expected-note@-5 {{through reference here}} // expected-note@-6 {{through reference here}} // expected-note@-7 {{through reference here}} // expected-note@-8 {{through reference here}} // expected-error@-9 {{circular reference}} // expected-note@-10 {{through reference here}} // expected-note@-11 {{through reference here}} // expected-note@-12 {{through reference here}} // expected-note@-13 {{through reference here}} // expected-note@-14 {{through reference here}} // https://bugs.swift.org/browse/SR-9015 func sr9015() { let closure1 = { closure2() } // expected-error {{circular reference}} expected-note {{through reference here}} expected-note {{through reference here}} let closure2 = { closure1() } // expected-note {{through reference here}} expected-note {{through reference here}} expected-note {{through reference here}} }
apache-2.0
d357abf05cb0aa369b2bde1f32d4fb06
44.700468
176
0.712569
3.905346
false
false
false
false
Brightify/Reactant
Tests/Validation/Rule.swift
2
2502
// // Rule.swift // Reactant // // Created by Matyáš Kříž on 26/10/2017. // Copyright © 2017 Brightify. All rights reserved. // import Quick import Nimble import Reactant class RuleTest: QuickSpec { override func spec() { describe("Rule Validation Tests") { let permissiveRule = Rule<String?, ValidationError> { _ in nil } let restrictiveRule = Rule<String?, ValidationError> { _ in .invalid } let divBy2StringLengthRule = Rule<String, ValidationError> { string in return string.count % 2 == 0 ? nil : .invalid } describe("anything should pass permissive rule") { expect(permissiveRule.test("value")).to(beTrue()) expect(permissiveRule.test("")).to(beTrue()) expect(permissiveRule.test(nil)).to(beTrue()) if case .failure = permissiveRule.run("value") { fail() } if case .failure = permissiveRule.run(nil) { fail() } } describe("nothing should pass restrictive rule") { expect(restrictiveRule.test("value")).to(beFalse()) expect(restrictiveRule.test("")).to(beFalse()) expect(restrictiveRule.test(nil)).to(beFalse()) if case .success = restrictiveRule.run("value") { fail() } if case .success = restrictiveRule.run(nil) { fail() } } describe("strings appropriate should pass \"div by 2 string length rule\" and others should not") { expect(divBy2StringLengthRule.test("")).to(beTrue()) expect(divBy2StringLengthRule.test("nilu")).to(beTrue()) expect(divBy2StringLengthRule.test("value")).to(beFalse()) expect(divBy2StringLengthRule.test("valueueueueueueue")).to(beFalse()) if case .failure = divBy2StringLengthRule.run("") { fail() } if case .failure = divBy2StringLengthRule.run("valu") { fail() } if case .success = divBy2StringLengthRule.run("value") { fail() } if case .success = divBy2StringLengthRule.run("valueueueueueueue") { fail() } } } } }
mit
7a792c6a61c9d360b1ec14d28902bbcf
36.818182
111
0.51242
4.718336
false
true
false
false
Kawoou/FlexibleImage
Sources/Filter/SoftLightFilter.swift
1
2433
// // SoftLightFilter.swift // FlexibleImage // // Created by Kawoou on 2017. 5. 12.. // Copyright © 2017년 test. All rights reserved. // #if !os(OSX) import UIKit #else import AppKit #endif #if !os(watchOS) import Metal #endif internal class SoftLightFilter: ImageFilter { // MARK: - Property internal override var metalName: String { get { return "SoftLightFilter" } } internal var color: FIColorType = (1.0, 1.0, 1.0, 1.0) // MARK: - Internal #if !os(watchOS) @available(OSX 10.11, iOS 8, tvOS 9, *) internal override func processMetal(_ device: ImageMetalDevice, _ commandBuffer: MTLCommandBuffer, _ commandEncoder: MTLComputeCommandEncoder) -> Bool { let factors: [Float] = [color.r, color.g, color.b, color.a] for i in 0..<factors.count { var factor = factors[i] let size = max(MemoryLayout<Float>.size, 16) let options: MTLResourceOptions if #available(iOS 9.0, *) { options = [.storageModeShared] } else { options = [.cpuCacheModeWriteCombined] } let buffer = device.device.makeBuffer( bytes: &factor, length: size, options: options ) #if swift(>=4.0) commandEncoder.setBuffer(buffer, offset: 0, index: i) #else commandEncoder.setBuffer(buffer, offset: 0, at: i) #endif } return super.processMetal(device, commandBuffer, commandEncoder) } #endif override func processNone(_ device: ImageNoneDevice) -> Bool { guard let context = device.context else { return false } let color = FIColor( red: CGFloat(self.color.r), green: CGFloat(self.color.g), blue: CGFloat(self.color.b), alpha: CGFloat(self.color.a) ) context.saveGState() context.setBlendMode(.softLight) context.setFillColor(color.cgColor) context.fill(device.drawRect!) context.restoreGState() return super.processNone(device) } }
mit
755882fa58208c42f4bab2009ab2f292
26.931034
160
0.515638
4.664107
false
false
false
false
amosavian/FileProvider
Sources/FPSStreamTask.swift
2
39683
// // FPSStreamTask.swift // FileProvider // // Created by Amir Abbas Mousavian. // Copyright © 2016 Mousavian. Distributed under MIT license. // import Foundation private var _lasttaskIdAssociated = 1_000_000_000 let _lasttaskIdAssociated_lock: NSLock = NSLock() var lasttaskIdAssociated: Int { get { _lasttaskIdAssociated_lock.lock() defer { _lasttaskIdAssociated_lock.unlock() } return _lasttaskIdAssociated } set { _lasttaskIdAssociated_lock.lock() defer { _lasttaskIdAssociated_lock.unlock() } _lasttaskIdAssociated = newValue } } // codebeat:disable[TOTAL_LOC,TOO_MANY_IVARS] /// This class is a replica of NSURLSessionStreamTask with same api for iOS 7/8 /// while it can actually fallback to NSURLSessionStreamTask in iOS 9. public class FileProviderStreamTask: URLSessionTask, StreamDelegate { fileprivate var inputStream: InputStream? fileprivate var outputStream: OutputStream? fileprivate let dataToBeSentLock = NSLock() fileprivate var dataToBeSent: Data = Data() fileprivate let dataReceivedLock = NSLock() fileprivate var dataReceived: Data = Data() fileprivate var _error: Error? = nil fileprivate var isSecure = false public var securityLevel: StreamSocketSecurityLevel = .negotiatedSSL fileprivate var dispatch_queue: DispatchQueue! internal var _underlyingSession: URLSession fileprivate var host: (hostname: String, port: Int)? fileprivate var service: NetService? fileprivate var streamDelegate: FPSStreamDelegate? { return (_underlyingSession.delegate as? FPSStreamDelegate) } internal static let defaultUseURLSession = false fileprivate var _taskIdentifier: Int fileprivate var _taskDescription: String? var observers: [(keyPath: String, observer: NSObject, context: UnsafeMutableRawPointer?)] = [] /// Force using `URLSessionStreamTask` for iOS 9 and later public let useURLSession: Bool @available(iOS 9.0, macOS 10.11, *) fileprivate static var streamTasks = [Int: URLSessionStreamTask]() @available(iOS 9.0, macOS 10.11, *) internal var _underlyingTask: URLSessionStreamTask? { return FileProviderStreamTask.streamTasks[_taskIdentifier] } /// The end of the stream has been reached. private var endEncountered: Bool = false /// Trust all certificates if `disableEvaluation`, Otherwise validate certificate chain. public var serverTrustPolicy: ServerTrustPolicy = .performDefaultEvaluation(validateHost: true) /// A pointer to a buffer containing the peer ID data to set. var peerID: UnsafeRawPointer? = nil /// The length of the peer ID data buffer. var peerIDLen: Int = 0 /** * An identifier uniquely identifies the task within a given session. * * This value is unique only within the context of a single session; * tasks in other sessions may have the same `taskIdentifier` value. */ open override var taskIdentifier: Int { if #available(iOS 9.0, macOS 10.11, *) { if self.useURLSession { return _underlyingTask!.taskIdentifier } } return _taskIdentifier } /// An app-provided description of the current task. /// /// This value may be nil. It is intended to contain human-readable strings that you can /// then display to the user as part of your app’s user interface. open override var taskDescription: String? { get { if #available(iOS 9.0, macOS 10.11, *) { if self.useURLSession { return _underlyingTask!.taskDescription } } return _taskDescription } @objc(setTaskDescription:) set { if #available(iOS 9.0, macOS 10.11, *) { if self.useURLSession { _underlyingTask!.taskDescription = newValue return } } _taskDescription = newValue } } fileprivate var _state: URLSessionTask.State = .suspended /** * The current state of the task—active, suspended, in the process * of being canceled, or completed. */ override open var state: URLSessionTask.State { if #available(iOS 9.0, macOS 10.11, *) { if self.useURLSession { return _underlyingTask!.state } } return _state } /** * The original request object passed when the task was created. * This value is typically the same as the currently active request (`currentRequest`) * except when the server has responded to the initial request with a redirect to a different URL. */ override open var originalRequest: URLRequest? { if #available(iOS 9.0, macOS 10.11, *) { if self.useURLSession { return _underlyingTask!.originalRequest } } return nil } /** * The URL request object currently being handled by the task. * This value is typically the same as the initial request (`originalRequest`) * except when the server has responded to the initial request with a redirect to a different URL. */ override open var currentRequest: URLRequest? { if #available(iOS 9.0, macOS 10.11, *) { return _underlyingTask!.currentRequest } else { return nil } } fileprivate var _countOfBytesSent: Int64 = 0 { willSet { for observer in observers where observer.keyPath == "countOfBytesSent" { observer.observer.observeValue(forKeyPath: observer.keyPath, of: self, change: [.oldKey: _countOfBytesSent, .oldKey: newValue], context: observer.context) } } didSet { for observer in observers where observer.keyPath == "countOfBytesSent" { observer.observer.observeValue(forKeyPath: observer.keyPath, of: self, change: [.oldKey: oldValue, .oldKey: _countOfBytesSent], context: observer.context) } } } fileprivate var _countOfBytesRecieved: Int64 = 0 { willSet { for observer in observers where observer.keyPath == "countOfBytesRecieved" { observer.observer.observeValue(forKeyPath: observer.keyPath, of: self, change: [.oldKey: _countOfBytesRecieved, .oldKey: newValue], context: observer.context) } } didSet { for observer in observers where observer.keyPath == "countOfBytesRecieved" { observer.observer.observeValue(forKeyPath: observer.keyPath, of: self, change: [.oldKey: oldValue, .oldKey: _countOfBytesRecieved], context: observer.context) } } } /** * The number of bytes that the task has sent to the server in the request body. * * This byte count includes only the length of the request body itself, not the request headers. * * To be notified when this value changes, implement the * `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` delegate method. */ override open var countOfBytesSent: Int64 { if #available(iOS 9.0, macOS 10.11, *) { if self.useURLSession { return _underlyingTask!.countOfBytesSent } } self.dataToBeSentLock.lock() defer { self.dataToBeSentLock.unlock() } return _countOfBytesSent } /** * The number of bytes that the task has received from the server in the response body. * * To be notified when this value changes, implement the `urlSession(_:dataTask:didReceive:)` delegate method (for data and upload tasks) * or the `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)` method (for download tasks). */ override open var countOfBytesReceived: Int64 { if #available(iOS 9.0, macOS 10.11, *) { if self.useURLSession { return _underlyingTask!.countOfBytesReceived } } dataReceivedLock.lock() defer { dataReceivedLock.unlock() } return _countOfBytesRecieved } /** * The number of bytes that the task expects to send in the request body. * * The `URL` loading system can determine the length of the upload data in three ways: * - From the length of the `NSData` object provided as the upload body. * - From the length of the file on disk provided as the upload body of an upload task (not a download task). * - From the `Content-Length` in the request object, if you explicitly set it. * * Otherwise, the value is `NSURLSessionTransferSizeUnknown` (`-1`) if you provided a stream or body data object, or zero (`0`) if you did not. */ override open var countOfBytesExpectedToSend: Int64 { if #available(iOS 9.0, macOS 10.11, *) { if self.useURLSession { return _underlyingTask!.countOfBytesExpectedToSend } } self.dataToBeSentLock.lock() defer { self.dataToBeSentLock.unlock() } return Int64(dataToBeSent.count) + _countOfBytesSent } /** * The number of bytes that the task expects to receive in the response body. * * This value is determined based on the `Content-Length` header received from the server. * If that header is absent, the value is `NSURLSessionTransferSizeUnknown`. */ override open var countOfBytesExpectedToReceive: Int64 { if #available(iOS 9.0, macOS 10.11, *) { if self.useURLSession { return _underlyingTask!.countOfBytesExpectedToReceive } } dataReceivedLock.lock() defer { dataReceivedLock.unlock() } return Int64(dataReceived.count) } override public init() { fatalError("Use NSURLSession.fpstreamTask() method") } internal init(session: URLSession, host: String, port: Int, useURLSession: Bool = defaultUseURLSession) { self._underlyingSession = session self.useURLSession = useURLSession if #available(iOS 9.0, macOS 10.11, *) { if useURLSession { let task = session.streamTask(withHostName: host, port: port) self._taskIdentifier = task.taskIdentifier FileProviderStreamTask.streamTasks[_taskIdentifier] = task return } } lasttaskIdAssociated += 1 self._taskIdentifier = lasttaskIdAssociated self.host = (host, port) self.dispatch_queue = DispatchQueue(label: "FileProviderStreamTask") self.dispatch_queue.suspend() } internal init(session: URLSession, netService: NetService, useURLSession: Bool = defaultUseURLSession) { self._underlyingSession = session self.useURLSession = useURLSession if #available(iOS 9.0, macOS 10.11, *) { if useURLSession { let task = session.streamTask(with: netService) self._taskIdentifier = task.taskIdentifier FileProviderStreamTask.streamTasks[_taskIdentifier] = task return } } lasttaskIdAssociated += 1 self._taskIdentifier = lasttaskIdAssociated self.service = netService self.dispatch_queue = DispatchQueue(label: "FileProviderStreamTask") self.dispatch_queue.suspend() } deinit { if !self.useURLSession { finish() } } /** * An error object that indicates why the task failed. * * This value is `NULL` if the task is still active or if the transfer completed successfully. */ override open var error: Error? { if #available(iOS 9.0, macOS 10.11, *) { if useURLSession { return _underlyingTask!.error } } return _error } /** * Cancels the task. * * This method returns immediately, marking the task as being canceled. Once a task is marked as being canceled, * `urlSession(_:task:didCompleteWithError:)` will be sent to the task delegate, passing an error * in the domain NSURLErrorDomain with the code `NSURLErrorCancelled`. A task may, under some circumstances, * send messages to its delegate before the cancelation is acknowledged. * * This method may be called on a task that is suspended. */ override open func cancel() { if #available(iOS 9.0, macOS 10.11, *) { if self.useURLSession { _underlyingTask!.cancel() return } } self._state = .canceling dispatch_queue.async { self.finish() self._state = .completed self._countOfBytesSent = 0 self._countOfBytesRecieved = 0 } } /** * Temporarily suspends a task. * * A task, while suspended, produces no network traffic and is not subject to timeouts. * A download task can continue transferring data at a later time. * All other tasks must start over when resumed. */ override open func suspend() { if #available(iOS 9.0, macOS 10.11, *) { if self.useURLSession { _underlyingTask!.suspend() return } } if self._state == .running { self._state = .suspended self.dispatch_queue.suspend() } } // Resumes the task, if it is suspended. override open func resume() { if #available(iOS 9.0, macOS 10.11, *) { if self.useURLSession { _underlyingTask!.resume() return } } if inputStream == nil || outputStream == nil { if let host = host { Stream.getStreamsToHost(withName: host.hostname, port: host.port, inputStream: &self.inputStream, outputStream: &self.outputStream) } else if let service = service { var readStream : Unmanaged<CFReadStream>? var writeStream : Unmanaged<CFWriteStream>? let cfnetService = CFNetServiceCreate(kCFAllocatorDefault, service.domain as CFString, service.type as CFString, service.name as CFString, Int32(service.port)) CFStreamCreatePairWithSocketToNetService(kCFAllocatorDefault, cfnetService.takeRetainedValue(), &readStream, &writeStream) inputStream = readStream?.takeRetainedValue() outputStream = writeStream?.takeRetainedValue() } guard let inputStream = inputStream, let outputStream = outputStream else { return } streamDelegate?.urlSession?(self._underlyingSession, streamTask: self, didBecome: inputStream, outputStream: outputStream) } guard let inputStream = inputStream, let outputStream = outputStream else { return } if isSecure { inputStream.setProperty(securityLevel.rawValue, forKey: .socketSecurityLevelKey) outputStream.setProperty(securityLevel.rawValue, forKey: .socketSecurityLevelKey) if serverTrustPolicy.evaluate() { // ※ Called, After setProperty securityLevel addTrustAllCertificatesSettings() } inputStream.setSSLPeerID(peerID: peerID, peerIDLen: peerIDLen) } else { inputStream.setProperty(StreamSocketSecurityLevel.none.rawValue, forKey: .socketSecurityLevelKey) outputStream.setProperty(StreamSocketSecurityLevel.none.rawValue, forKey: .socketSecurityLevelKey) } inputStream.delegate = self outputStream.delegate = self #if swift(>=4.2) inputStream.schedule(in: RunLoop.main, forMode: .common) #else inputStream.schedule(in: RunLoop.main, forMode: .commonModes) #endif //outputStream.schedule(in: RunLoop.main, forMode: .init("kCFRunLoopDefaultMode")) inputStream.open() outputStream.open() if self._state == .suspended { dispatch_queue.resume() _state = .running } } /** * Asynchronously reads a number of bytes from the stream, and calls a handler upon completion. * * - Parameter minBytes: The minimum number of bytes to read. * - ParametermaxBytes: The maximum number of bytes to read. * - Parameter timeout: A timeout for reading bytes. If the read is not completed within the specified interval, * the read is canceled and the completionHandler is called with an error. Pass `0` to prevent a read from timing out. * - Parameter completionHandler: The completion handler to call when all bytes are read, or an error occurs. * This handler is executed on the delegate queue. This completion handler takes the following parameters: * - Parameter data: The data read from the stream. * - Parameter atEOF: Whether or not the stream reached end-of-file (`EOF`), such that no more data can be read. * - Parameter error: An error object that indicates why the read failed, or `nil` if the read was successful. */ open func readData(ofMinLength minBytes: Int, maxLength maxBytes: Int, timeout: TimeInterval, completionHandler: @escaping (_ data: Data?, _ atEOF: Bool, _ error :Error?) -> Void) { if #available(iOS 9.0, macOS 10.11, *) { if self.useURLSession { _underlyingTask!.readData(ofMinLength: minBytes, maxLength: maxBytes, timeout: timeout, completionHandler: completionHandler) return } } guard let inputStream = inputStream else { return } let expireDate = Date(timeIntervalSinceNow: timeout) dispatch_queue.async { var timedOut: Bool = false self.dataReceivedLock.lock() while (self.dataReceived.count == 0 || self.dataReceived.count < minBytes) && !timedOut && !self.endEncountered { self.dataReceivedLock.unlock() Thread.sleep(forTimeInterval: 0.1) if let error = inputStream.streamError { completionHandler(nil, inputStream.streamStatus == .atEnd, error) return } timedOut = expireDate < Date() self.dataReceivedLock.lock() } self.endEncountered = false var dR: Data? if self.dataReceived.count > maxBytes { let range: Range = 0..<maxBytes dR = self.dataReceived.subdata(in: range) self.dataReceived.removeFirst(maxBytes) } else { if self.dataReceived.count > 0 { dR = self.dataReceived self.dataReceived.removeAll(keepingCapacity: false) } } let isEOF = inputStream.streamStatus == .atEnd && self.dataReceived.count == 0 self.dataReceivedLock.unlock() completionHandler(dR, isEOF, dR == nil ? (timedOut ? URLError(.timedOut) : inputStream.streamError) : nil) } } /** * Asynchronously writes the specified data to the stream, and calls a handler upon completion. * * There is no guarantee that the remote side of the stream has received all of the written bytes * at the time that `completionHandler` is called, only that all of the data has been written to the kernel. * * - Parameter data: The data to be written. * - Parameter timeout: A timeout for writing bytes. If the write is not completed within the specified interval, * the write is canceled and the `completionHandler` is called with an error. * Pass `0` to prevent a write from timing out. * - Parameter completionHandler: The completion handler to call when all bytes are written, or an error occurs. * This handler is executed on the delegate queue. * This completion handler takes the following parameter: * - Parameter error: An error object that indicates why the write failed, or `nil` if the write was successful. */ open func write(_ data: Data, timeout: TimeInterval, completionHandler: @escaping (_ error: Error?) -> Void) { if #available(iOS 9.0, macOS 10.11, *) { if self.useURLSession { _underlyingTask!.write(data, timeout: timeout, completionHandler: completionHandler) return } } guard outputStream != nil else { if self.state == .canceling || self.state == .completed { completionHandler(URLError(.cancelled)) } return } self.dataToBeSentLock.lock() self.dataToBeSent.append(data) self.dataToBeSentLock.unlock() dispatch_queue.async { let result = self.write(timeout: timeout, close: false) if result < 0 { let error = self.outputStream?.streamError ?? URLError((self.state == .canceling || self.state == .completed) ? .cancelled : .cannotWriteToFile) completionHandler(error) } else { completionHandler(nil) } } } /** * Completes any already enqueued reads and writes, and then invokes the * `urlSession(_:streamTask:didBecome:outputStream:)` delegate message. */ open func captureStreams() { if #available(iOS 9.0, macOS 10.11, *) { if self.useURLSession { _underlyingTask!.captureStreams() return } } guard let outputStream = outputStream, let inputStream = inputStream else { return } dispatch_queue.async { _=self.write(close: false) while outputStream.streamStatus == .writing { Thread.sleep(forTimeInterval: 0.1) } self.streamDelegate?.urlSession?(self._underlyingSession, streamTask: self, didBecome: inputStream, outputStream: outputStream) } } /** * Completes any enqueued reads and writes, and then closes the write side of the underlying socket. * * You may continue to read data using the `readData(ofMinLength:maxLength:timeout:completionHandler:)` * method after calling this method. Any calls to `write(_:timeout:completionHandler:)` after calling * this method will result in an error. * * Because the server may continue to write bytes to the client, it is recommended that * you continue reading until the stream reaches end-of-file (EOF). */ open func closeWrite() { if #available(iOS 9.0, macOS 10.11, *) { if self.useURLSession { _underlyingTask!.closeWrite() return } } dispatch_queue.async { _ = self.write(close: true) } } fileprivate var shouldCloseWrite = false /** * Completes any enqueued reads and writes, and then closes the read side of the underlying socket. * * You may continue to write data using the `write(_:timeout:completionHandler:)` method after * calling this method. Any calls to `readData(ofMinLength:maxLength:timeout:completionHandler:)` * after calling this method will result in an error. */ open func closeRead() { closeRead(immediate: false) } /** * Completes any enqueued reads and writes, and then closes the read side of the underlying socket. * * You may continue to write data using the `write(_:timeout:completionHandler:)` method after * calling this method. Any calls to `readData(ofMinLength:maxLength:timeout:completionHandler:)` * after calling this method will result in an error. * * - Parameter immediate: close immediatly if true. */ open func closeRead(immediate: Bool) { if #available(iOS 9.0, macOS 10.11, *) { if self.useURLSession { _underlyingTask!.closeRead() return } } guard let inputStream = inputStream else { return } dispatch_queue.async { if !immediate { while inputStream.streamStatus != .atEnd { Thread.sleep(forTimeInterval: 0.1) } } inputStream.close() self.streamDelegate?.urlSession?(self._underlyingSession, readClosedFor: self) } } /** * Completes any enqueued reads and writes, and establishes a secure connection. * * Authentication callbacks are sent to the session's delegate using the * `urlSession(_:task:didReceive:completionHandler:)` method. */ open func startSecureConnection() { if #available(iOS 9.0, macOS 10.11, *) { if self.useURLSession { _underlyingTask!.startSecureConnection() return } } isSecure = true if let inputStream = self.inputStream, let outputStream = self.outputStream, inputStream.property(forKey: .socketSecurityLevelKey) as? String == StreamSocketSecurityLevel.none.rawValue { if serverTrustPolicy.evaluate() { // ※ Called, Before setProperty securityLevel self.addTrustAllCertificatesSettings() } inputStream.setSSLPeerID(peerID: peerID, peerIDLen: peerIDLen) dispatch_queue.async { inputStream.setProperty(self.securityLevel.rawValue, forKey: .socketSecurityLevelKey) outputStream.setProperty(self.securityLevel.rawValue, forKey: .socketSecurityLevelKey) } var sslSessionState: SSLSessionState = .idle if let sslContext = inputStream.property(forKey: kCFStreamPropertySSLContext as Stream.PropertyKey) { while SSLGetSessionState(sslContext as! SSLContext, UnsafeMutablePointer(&sslSessionState)) == errSSLWouldBlock || sslSessionState == .idle || sslSessionState == .handshake { guard inputStream.streamError == nil, outputStream.streamError == nil else { break } Thread.sleep(forTimeInterval: 0.1) } } } } /** * Completes any enqueued reads and writes, and closes the secure connection. */ open func stopSecureConnection() { if #available(iOS 9.0, macOS 10.11, *) { if self.useURLSession { _underlyingTask!.stopSecureConnection() return } } isSecure = false dispatch_queue.async { if let inputStream = self.inputStream, let outputStream = self.outputStream, inputStream.property(forKey: .socketSecurityLevelKey) as? String != StreamSocketSecurityLevel.none.rawValue { inputStream.setProperty(StreamSocketSecurityLevel.none.rawValue, forKey: .socketSecurityLevelKey) outputStream.setProperty(StreamSocketSecurityLevel.none.rawValue, forKey: .socketSecurityLevelKey) if let sslContext = inputStream.property(forKey: kCFStreamPropertySSLContext as Stream.PropertyKey) { while SSLClose(sslContext as! SSLContext) == errSSLWouldBlock { guard inputStream.streamError == nil || inputStream.streamError?._code == Int(errSSLClosedGraceful), outputStream.streamError == nil || outputStream.streamError?._code == Int(errSSLClosedGraceful) else { break } Thread.sleep(forTimeInterval: 0.1) } } } } } /** * Add TrustAllCertificates SSLSettings to Input/OutputStream. * * - note: Connects to a remote socket server using a self-signed certificate */ func addTrustAllCertificatesSettings() { // Define custom SSL/TLS settings #if swift(>=5.0) let sslSettings: [NSString: Any] = [ NSString(format: kCFStreamSSLValidatesCertificateChain): kCFBooleanFalse!, NSString(format: kCFStreamSSLPeerName): kCFNull! ] #else let sslSettings: [NSString: Any] = [ NSString(format: kCFStreamSSLValidatesCertificateChain): kCFBooleanFalse, NSString(format: kCFStreamSSLPeerName): kCFNull ] #endif // Set custom SSL/TLS settings inputStream?.setProperty(sslSettings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey) outputStream?.setProperty(sslSettings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey) } /** * Reuse SSL/TLS session used for the SSL/TLS session cache. * * - Parameter task: The task authenticated connection FTP over SSL/TLS. */ func reuseSSLSession(task: FileProviderStreamTask) { let sslPeerID = task.inputStream?.getSSLPeerID() peerID = sslPeerID?.peerID peerIDLen = sslPeerID?.peerIDLen ?? 0 } } extension Stream { /** * Retrieves the current peer ID data. * * - Returns: * - peerID: On return, points to a buffer containing the peer ID data. * - peerIDLen: On return, the length of the peer ID data buffer. */ public func getSSLPeerID() -> (peerID: UnsafeRawPointer?, peerIDLen: Int) { var peerID: UnsafeRawPointer? = nil var peerIDLen: Int = 0 if let sslContext = self.property(forKey: kCFStreamPropertySSLContext as Stream.PropertyKey) { let _ = SSLGetPeerID(sslContext as! SSLContext, UnsafeMutablePointer(&peerID), UnsafeMutablePointer(&peerIDLen)) } return (peerID, peerIDLen) } /** * Specifies data that is sufficient to uniquely identify the peer of the current session. * This peerID is used for the TLS session cache. * * - Parameter peerID: A pointer to a buffer containing the peer ID data to set. * - Parameter peerIDLen: The length of the peer ID data buffer. */ fileprivate func setSSLPeerID(peerID: UnsafeRawPointer?, peerIDLen: Int) { guard peerID != nil, peerIDLen > 0 else { return } if let sslContext = self.property(forKey: kCFStreamPropertySSLContext as Stream.PropertyKey) { let _ = SSLSetPeerID(sslContext as! SSLContext, peerID, peerIDLen) } } } extension FileProviderStreamTask { open func stream(_ aStream: Stream, handle eventCode: Stream.Event) { if eventCode.contains(.errorOccurred) { self._error = aStream.streamError streamDelegate?.urlSession?(_underlyingSession, task: self, didCompleteWithError: error) } if aStream == inputStream && eventCode.contains(.endEncountered) { self.endEncountered = true } if aStream == inputStream && eventCode.contains(.hasBytesAvailable) { while (inputStream!.hasBytesAvailable) { var buffer = [UInt8](repeating: 0, count: 2048) let len = inputStream!.read(&buffer, maxLength: buffer.count) if len > 0 { dataReceivedLock.lock() dataReceived.append(&buffer, count: len) dataReceivedLock.unlock() self._countOfBytesRecieved += Int64(len) } } } } fileprivate func write(timeout: TimeInterval = 0, close: Bool) -> Int { guard let outputStream = outputStream else { return -1 } var byteSent: Int = 0 let expireDate = Date(timeIntervalSinceNow: timeout) self.dataToBeSentLock.lock() defer { self.dataToBeSentLock.unlock() } while self.dataToBeSent.count > 0 && (timeout == 0 || expireDate > Date()) { if let _ = outputStream.streamError { return byteSent == 0 ? -1 : byteSent } let bytesWritten: Int = (try? outputStream.write(data: self.dataToBeSent)) ?? -1 if bytesWritten > 0 { self.dataToBeSent.removeFirst(bytesWritten) byteSent += bytesWritten self._countOfBytesSent += Int64(bytesWritten) } else if bytesWritten < 0 { self._error = outputStream.streamError return bytesWritten } if self.dataToBeSent.count == 0 { break } } if close { DispatchQueue.main.sync { outputStream.close() shouldCloseWrite = true } self.streamDelegate?.urlSession?(self._underlyingSession, writeClosedFor: self) } return byteSent } fileprivate func finish() { peerID = nil inputStream?.delegate = nil outputStream?.delegate = nil inputStream?.close() #if swift(>=4.2) inputStream?.remove(from: RunLoop.main, forMode: .common) #else inputStream?.remove(from: RunLoop.main, forMode: .commonModes) #endif inputStream = nil outputStream?.close() #if swift(>=4.2) outputStream?.remove(from: RunLoop.main, forMode: .common) #else outputStream?.remove(from: RunLoop.main, forMode: .commonModes) #endif outputStream = nil } } extension FileProviderStreamTask { public override func addObserver(_ observer: NSObject, forKeyPath keyPath: String, options: NSKeyValueObservingOptions = [], context: UnsafeMutableRawPointer?) { if #available(iOS 9.0, macOS 10.11, *) { if self.useURLSession { self._underlyingTask?.addObserver(observer, forKeyPath: keyPath, options: options, context: context) return } } switch keyPath { case #keyPath(countOfBytesSent): fallthrough case #keyPath(countOfBytesReceived): fallthrough case #keyPath(countOfBytesExpectedToSend): fallthrough case #keyPath(countOfBytesExpectedToReceive): observers.append((keyPath: keyPath, observer: observer, context: context)) default: break } super.addObserver(observer, forKeyPath: keyPath, options: options, context: context) } public override func removeObserver(_ observer: NSObject, forKeyPath keyPath: String) { var newObservers: [(keyPath: String, observer: NSObject, context: UnsafeMutableRawPointer?)] = [] for observer in observers where observer.keyPath != keyPath { newObservers.append(observer) } self.observers = newObservers super.removeObserver(observer, forKeyPath: keyPath) } public override func removeObserver(_ observer: NSObject, forKeyPath keyPath: String, context: UnsafeMutableRawPointer?) { var newObservers: [(keyPath: String, observer: NSObject, context: UnsafeMutableRawPointer?)] = [] for observer in observers where observer.keyPath != keyPath || observer.context != context { newObservers.append(observer) } self.observers = newObservers super.removeObserver(observer, forKeyPath: keyPath, context: context) } } public extension URLSession { /// Creates a bidirectional stream task to a given host and port. func fpstreamTask(withHostName hostname: String, port: Int) -> FileProviderStreamTask { return FileProviderStreamTask(session: self, host: hostname, port: port) } /** * Creates a bidirectional stream task with an NSNetService to identify the endpoint. * The NSNetService will be resolved before any IO completes. */ func fpstreamTask(withNetService service: NetService) -> FileProviderStreamTask { return FileProviderStreamTask(session: self, netService: service) } } @objc internal protocol FPSStreamDelegate : URLSessionTaskDelegate { /** * Indiciates that the read side of a connection has been closed. Any * outstanding reads complete, but future reads will immediately fail. * This may be sent even when no reads are in progress. However, when * this delegate message is received, there may still be bytes * available. You only know that no more bytes are available when you * are able to read until EOF. */ @objc optional func urlSession(_ session: URLSession, readClosedFor streamTask: FileProviderStreamTask) /** * Indiciates that the write side of a connection has been closed. * Any outstanding writes complete, but future writes will immediately * fail. */ @objc optional func urlSession(_ session: URLSession, writeClosedFor streamTask: FileProviderStreamTask) /** * A notification that the system has determined that a better route * to the host has been detected (eg, a wi-fi interface becoming * available.) This is a hint to the delegate that it may be * desirable to create a new task for subsequent work. Note that * there is no guarantee that the future task will be able to connect * to the host, so callers should should be prepared for failure of * reads and writes over any new interface. */ @objc optional func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: FileProviderStreamTask) /** * The given task has been completed, and unopened NSInputStream and * NSOutputStream objects are created from the underlying network * connection. This will only be invoked after all enqueued IO has * completed (including any necessary handshakes.) The streamTask * will not receive any further delegate messages. */ @objc optional func urlSession(_ session: URLSession, streamTask: FileProviderStreamTask, didBecome inputStream: InputStream, outputStream: OutputStream) } // codebeat:enable[TOTAL_LOC,TOO_MANY_IVARS] private let ports: [String: Int] = ["http": 80, "https": 443, "smb": 445,"ftp": 21, "telnet": 23, "pop": 110, "smtp": 25, "imap": 143] private let securePorts: [String: Int] = ["ssh": 22, "https": 443, "smb": 445, "smtp": 465, "ftps": 990,"telnet": 992, "imap": 993, "pop": 995]
mit
eecf7d912047ddeebfb08dcd543fc637
38.873367
185
0.609618
5.17532
false
false
false
false
djwbrown/swift
test/decl/class/override.swift
6
19081
// RUN: %target-typecheck-verify-swift -parse-as-library class A { func ret_sametype() -> Int { return 0 } func ret_subclass() -> A { return self } func ret_subclass_rev() -> B { return B() } func ret_nonclass_optional() -> Int? { return .none } func ret_nonclass_optional_rev() -> Int { return 0 } func ret_class_optional() -> B? { return .none } func ret_class_optional_rev() -> A { return self } func ret_class_uoptional() -> B! { return B() } func ret_class_uoptional_rev() -> A { return self } func ret_class_optional_uoptional() -> B? { return .none } func ret_class_optional_uoptional_rev() -> A! { return self } func param_sametype(_ x : Int) {} func param_subclass(_ x : B) {} func param_subclass_rev(_ x : A) {} func param_nonclass_optional(_ x : Int) {} func param_nonclass_optional_rev(_ x : Int?) {} func param_class_optional(_ x : B) {} func param_class_optional_rev(_ x : B?) {} func param_class_uoptional(_ x : B) {} func param_class_uoptional_rev(_ x : B!) {} func param_class_optional_uoptional(_ x : B!) {} func param_class_optional_uoptional_rev(_ x : B?) {} } class B : A { override func ret_sametype() -> Int { return 1 } override func ret_subclass() -> B { return self } func ret_subclass_rev() -> A { return self } override func ret_nonclass_optional() -> Int { return 0 } func ret_nonclass_optional_rev() -> Int? { return 0 } override func ret_class_optional() -> B { return self } func ret_class_optional_rev() -> A? { return self } override func ret_class_uoptional() -> B { return self } func ret_class_uoptional_rev() -> A! { return self } override func ret_class_optional_uoptional() -> B! { return self } override func ret_class_optional_uoptional_rev() -> A? { return self } override func param_sametype(_ x : Int) {} override func param_subclass(_ x : A) {} func param_subclass_rev(_ x : B) {} override func param_nonclass_optional(_ x : Int?) {} func param_nonclass_optional_rev(_ x : Int) {} override func param_class_optional(_ x : B?) {} func param_class_optional_rev(_ x : B) {} override func param_class_uoptional(_ x : B!) {} func param_class_uoptional_rev(_ x : B) {} override func param_class_optional_uoptional(_ x : B?) {} override func param_class_optional_uoptional_rev(_ x : B!) {} } class C<T> { func ret_T() -> T {} } class D<T> : C<[T]> { override func ret_T() -> [T] {} } class E { var var_sametype: Int { get { return 0 } set {} } var var_subclass: E { get { return self } set {} } // expected-note{{attempt to override property here}} var var_subclass_rev: F { get { return F() } set {} } // expected-note{{attempt to override property here}} var var_nonclass_optional: Int? { get { return .none } set {} } // expected-note{{attempt to override property here}} var var_nonclass_optional_rev: Int { get { return 0 } set {} } // expected-note{{attempt to override property here}} var var_class_optional: F? { get { return .none } set {} } // expected-note{{attempt to override property here}} var var_class_optional_rev: E { get { return self } set {} } // expected-note{{attempt to override property here}} var var_class_uoptional: F! { get { return F() } set {} } // expected-note{{attempt to override property here}} var var_class_uoptional_rev: E { get { return self } set {} } // expected-note{{attempt to override property here}} var var_class_optional_uoptional: F? { get { return .none } set {} } var var_class_optional_uoptional_rev: E! { get { return self } set {} } var ro_sametype: Int { return 0 } var ro_subclass: E { return self } var ro_subclass_rev: F { return F() } var ro_nonclass_optional: Int? { return 0 } var ro_nonclass_optional_rev: Int { return 0 } // expected-note{{attempt to override property here}} var ro_class_optional: F? { return .none } var ro_class_optional_rev: E { return self } // expected-note{{attempt to override property here}} var ro_class_uoptional: F! { return F() } var ro_class_uoptional_rev: E { return self } // expected-note{{attempt to override property here}} var ro_class_optional_uoptional: F? { return .none } var ro_class_optional_uoptional_rev: E! { return self } } class F : E { override var var_sametype: Int { get { return 0 } set {} } override var var_subclass: F { get { return self } set {} } // expected-error{{cannot override mutable property 'var_subclass' of type 'E' with covariant type 'F'}} override var var_subclass_rev: E { get { return F() } set {} } // expected-error{{property 'var_subclass_rev' with type 'E' cannot override a property with type 'F}} override var var_nonclass_optional: Int { get { return 0 } set {} } // expected-error{{cannot override mutable property 'var_nonclass_optional' of type 'Int?' with covariant type 'Int'}} override var var_nonclass_optional_rev: Int? { get { return 0 } set {} } // expected-error{{property 'var_nonclass_optional_rev' with type 'Int?' cannot override a property with type 'Int'}} override var var_class_optional: F { get { return self } set {} } // expected-error{{cannot override mutable property 'var_class_optional' of type 'F?' with covariant type 'F'}} override var var_class_optional_rev: E? { get { return self } set {} } // expected-error{{property 'var_class_optional_rev' with type 'E?' cannot override a property with type 'E'}} override var var_class_uoptional: F { get { return F() } set {} } // expected-error{{cannot override mutable property 'var_class_uoptional' of type 'F!' with covariant type 'F'}} override var var_class_uoptional_rev: E! { get { return self } set {} } // expected-error{{property 'var_class_uoptional_rev' with type 'E!' cannot override a property with type 'E'}} override var var_class_optional_uoptional: F! { get { return .none } set {} } override var var_class_optional_uoptional_rev: E? { get { return self } set {} } override var ro_sametype: Int { return 0 } override var ro_subclass: E { return self } override var ro_subclass_rev: F { return F() } override var ro_nonclass_optional: Int { return 0 } override var ro_nonclass_optional_rev: Int? { return 0 } // expected-error{{property 'ro_nonclass_optional_rev' with type 'Int?' cannot override a property with type 'Int'}} override var ro_class_optional: F { return self } override var ro_class_optional_rev: E? { return self } // expected-error{{property 'ro_class_optional_rev' with type 'E?' cannot override a property with type 'E'}} override var ro_class_uoptional: F { return F() } override var ro_class_uoptional_rev: E! { return self } // expected-error{{property 'ro_class_uoptional_rev' with type 'E!' cannot override a property with type 'E'}} override var ro_class_optional_uoptional: F! { return .none } override var ro_class_optional_uoptional_rev: E? { return self } } class G { func f1(_: Int, int: Int) { } func f2(_: Int, int: Int) { } func f3(_: Int, int: Int) { } func f4(_: Int, int: Int) { } func f5(_: Int, int: Int) { } func f6(_: Int, int: Int) { } func f7(_: Int, int: Int) { } func g1(_: Int, string: String) { } // expected-note{{potential overridden instance method 'g1(_:string:)' here}} {{28-28=string }} func g1(_: Int, path: String) { } // expected-note{{potential overridden instance method 'g1(_:path:)' here}} {{28-28=path }} func g2(_: Int, string: String) { } // expected-note{{potential overridden instance method 'g2(_:string:)' here}} {{none}} func g2(_: Int, path: String) { } func g3(_: Int, _ another: Int) { } func g3(_: Int, path: String) { } // expected-note{{potential overridden instance method 'g3(_:path:)' here}} {{none}} func g4(_: Int, _ another: Int) { } func g4(_: Int, path: String) { } init(a: Int) {} // expected-note {{potential overridden initializer 'init(a:)' here}} {{none}} init(a: String) {} // expected-note {{potential overridden initializer 'init(a:)' here}} {{17-17=a }} expected-note {{potential overridden initializer 'init(a:)' here}} {{none}} init(b: String) {} // expected-note {{potential overridden initializer 'init(b:)' here}} {{17-17=b }} expected-note {{potential overridden initializer 'init(b:)' here}} {{none}} } class H : G { override func f1(_: Int, _: Int) { } // expected-error{{argument names for method 'f1' do not match those of overridden method 'f1(_:int:)'}}{{28-28=int }} override func f2(_: Int, value: Int) { } // expected-error{{argument names for method 'f2(_:value:)' do not match those of overridden method 'f2(_:int:)'}}{{28-28=int }} override func f3(_: Int, value int: Int) { } // expected-error{{argument names for method 'f3(_:value:)' do not match those of overridden method 'f3(_:int:)'}}{{28-34=}} override func f4(_: Int, _ int: Int) { } // expected-error{{argument names for method 'f4' do not match those of overridden method 'f4(_:int:)'}}{{28-30=}} override func f5(_: Int, value inValue: Int) { } // expected-error{{argument names for method 'f5(_:value:)' do not match those of overridden method 'f5(_:int:)'}}{{28-33=int}} override func f6(_: Int, _ inValue: Int) { } // expected-error{{argument names for method 'f6' do not match those of overridden method 'f6(_:int:)'}}{{28-29=int}} override func f7(_: Int, int value: Int) { } // okay override func g1(_: Int, s: String) { } // expected-error{{declaration 'g1(_:s:)' has different argument names from any potential overrides}}{{none}} override func g2(_: Int, string: Int) { } // expected-error{{method does not override any method from its superclass}} {{none}} override func g3(_: Int, path: Int) { } // expected-error{{method does not override any method from its superclass}} {{none}} override func g4(_: Int, string: Int) { } // expected-error{{argument names for method 'g4(_:string:)' do not match those of overridden method 'g4'}} {{28-28=_ }} override init(x: Int) {} // expected-error{{argument names for initializer 'init(x:)' do not match those of overridden initializer 'init(a:)'}} {{17-17=a }} override init(x: String) {} // expected-error{{declaration 'init(x:)' has different argument names from any potential overrides}} {{none}} override init(a: Double) {} // expected-error{{initializer does not override a designated initializer from its superclass}} {{none}} override init(b: Double) {} // expected-error{{initializer does not override a designated initializer from its superclass}} {{none}} } @objc class IUOTestBaseClass { func none() {} func oneA(_: AnyObject) {} func oneB(x: AnyObject) {} func oneC(_ x: AnyObject) {} func manyA(_: AnyObject, _: AnyObject) {} func manyB(_ a: AnyObject, b: AnyObject) {} func manyC(var a: AnyObject, // expected-error {{'var' as a parameter attribute is not allowed}} var b: AnyObject) {} // expected-error {{'var' as a parameter attribute is not allowed}} func result() -> AnyObject? { return nil } func both(_ x: AnyObject) -> AnyObject? { return x } init(_: AnyObject) {} init(one: AnyObject) {} init(a: AnyObject, b: AnyObject) {} } class IUOTestSubclass : IUOTestBaseClass { override func oneA(_: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}} // expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}} override func oneB(x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}} // expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}} override func oneC(_ x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{36-37=}} // expected-note@-2 {{add parentheses to silence this warning}} {{27-27=(}} {{37-37=)}} override func manyA(_: AnyObject!, _: AnyObject!) {} // expected-warning 2 {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 2 {{remove '!' to make the parameter required}} // expected-note@-2 2 {{add parentheses to silence this warning}} override func manyB(_ a: AnyObject!, b: AnyObject!) {} // expected-warning 2 {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 2 {{remove '!' to make the parameter required}} // expected-note@-2 2 {{add parentheses to silence this warning}} override func result() -> AnyObject! { return nil } // expected-warning {{overriding instance method optional result type 'AnyObject?' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 {{use '?' to make the result optional}} {{38-39=?}} // expected-note@-2 {{add parentheses to silence this warning}} {{29-29=(}} {{39-39=)}} override func both(_ x: AnyObject!) -> AnyObject! { return x } // expected-warning {{overriding instance method optional result type 'AnyObject?' with implicitly unwrapped optional type 'AnyObject!'}} expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 {{use '?' to make the result optional}} {{51-52=?}} expected-note@-1 {{remove '!' to make the parameter required}} {{36-37=}} // expected-note@-2 2 {{add parentheses to silence this warning}} override init(_: AnyObject!) {} // expected-warning {{overriding initializer parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{29-30=}} // expected-note@-2 {{add parentheses to silence this warning}} {{20-20=(}} {{30-30=)}} override init(one: AnyObject!) {} // expected-warning {{overriding initializer parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{31-32=}} // expected-note@-2 {{add parentheses to silence this warning}} {{22-22=(}} {{32-32=)}} override init(a: AnyObject!, b: AnyObject!) {} // expected-warning 2 {{overriding initializer parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 2 {{remove '!' to make the parameter required}} // expected-note@-2 2 {{add parentheses to silence this warning}} } class IUOTestSubclass2 : IUOTestBaseClass { override func oneA(_ x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{36-37=}} // expected-note@-2 {{add parentheses to silence this warning}} {{27-27=(}} {{37-37=)}} override func oneB(x: ImplicitlyUnwrappedOptional<AnyObject>) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'ImplicitlyUnwrappedOptional<AnyObject>'}} // expected-note@-1 {{add parentheses to silence this warning}} {{25-25=(}} {{63-63=)}} override func oneC(_: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}} // expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}} } class IUOTestSubclassOkay : IUOTestBaseClass { override func oneA(_: AnyObject?) {} override func oneB(x: (AnyObject!)) {} override func oneC(_ x: AnyObject) {} override func result() -> (AnyObject!) { return nil } } class GenericBase<T> {} class ConcreteDerived: GenericBase<Int> {} class OverriddenWithConcreteDerived<T> { func foo() -> GenericBase<T> {} // expected-note{{potential overridden instance method 'foo()' here}} } class OverridesWithMismatchedConcreteDerived<T>: OverriddenWithConcreteDerived<T> { override func foo() -> ConcreteDerived {} //expected-error{{does not override}} } class OverridesWithConcreteDerived: OverriddenWithConcreteDerived<Int> { override func foo() -> ConcreteDerived {} } // <rdar://problem/24646184> class Ty {} class SubTy : Ty {} class Base24646184 { init(_: SubTy) { } func foo(_: SubTy) { } init(ok: Ty) { } init(ok: SubTy) { } func foo(ok: Ty) { } func foo(ok: SubTy) { } } class Derived24646184 : Base24646184 { override init(_: Ty) { } // expected-note {{'init' previously overridden here}} override init(_: SubTy) { } // expected-error {{'init' has already been overridden}} override func foo(_: Ty) { } // expected-note {{'foo' previously overridden here}} override func foo(_: SubTy) { } // expected-error {{'foo' has already been overridden}} override init(ok: Ty) { } override init(ok: SubTy) { } override func foo(ok: Ty) { } override func foo(ok: SubTy) { } } // Generic subscripts class GenericSubscriptBase { var dict: [AnyHashable : Any] = [:] subscript<T : Hashable, U>(t: T) -> U { get { return dict[t] as! U } set { dict[t] = newValue } } } class GenericSubscriptDerived : GenericSubscriptBase { override subscript<K : Hashable, V>(t: K) -> V { get { return super[t] } set { super[t] = newValue } } } // @escaping class CallbackBase { func perform(handler: @escaping () -> Void) {} // expected-note * {{here}} func perform(optHandler: (() -> Void)?) {} // expected-note * {{here}} func perform(nonescapingHandler: () -> Void) {} // expected-note * {{here}} } class CallbackSubA: CallbackBase { override func perform(handler: () -> Void) {} // expected-error {{method does not override any method from its superclass}} // expected-note@-1 {{type does not match superclass instance method with type '(@escaping () -> Void) -> ()'}} override func perform(optHandler: () -> Void) {} // expected-error {{method does not override any method from its superclass}} override func perform(nonescapingHandler: () -> Void) {} } class CallbackSubB : CallbackBase { override func perform(handler: (() -> Void)?) {} override func perform(optHandler: (() -> Void)?) {} override func perform(nonescapingHandler: (() -> Void)?) {} // expected-error {{method does not override any method from its superclass}} } class CallbackSubC : CallbackBase { override func perform(handler: @escaping () -> Void) {} override func perform(optHandler: @escaping () -> Void) {} // expected-error {{cannot override instance method parameter of type '(() -> Void)?' with non-optional type '() -> Void'}} override func perform(nonescapingHandler: @escaping () -> Void) {} // expected-error {{method does not override any method from its superclass}} }
apache-2.0
a4c8aa9e38e69ab007df5deb218605e7
56.472892
333
0.670877
3.856306
false
false
false
false
blinksh/blink
Settings/ViewControllers/BKPubKey/ImportKeyView.swift
1
3926
////////////////////////////////////////////////////////////////////////////////// // // 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 SwiftUI import SSH struct ImportKeyView: View { @ObservedObject var state: ImportKeyObservable let onCancel: () -> Void let onSuccess: () -> Void var body: some View { List { Section( header: Text("NAME"), footer: Text("Default key must be named `id_\(state.keyType.lowercased())`") ) { FixedTextField( "Enter a name for the key", text: $state.keyName, id: "keyName", nextId: "keyComment", autocorrectionType: .no, autocapitalizationType: .none ) } Section(header: Text("COMMENT (OPTIONAL)")) { FixedTextField( "Comment for your key", text: $state.keyComment, id: "keyComment", returnKeyType: .continue, onReturn: { if state.saveKey() { onSuccess() } }, autocorrectionType: .no, autocapitalizationType: .none ) } Section( header: Text("INFORMATION"), footer: Text("Blink creates PKCS#8 public and private keys, with AES 256 bit encryption. Use \"ssh-copy-id [name]\" to copy the public key to the server.") ) { } } .listStyle(GroupedListStyle()) .navigationBarItems( leading: Button("Cancel", action: onCancel), trailing: Button("Import") { if state.saveKey() { onSuccess() } } .disabled(!state.isValid) ) .navigationBarTitle("Import \(state.keyType) Key") .alert(errorMessage: $state.errorMessage) } } class ImportKeyObservable: ObservableObject { let key: SSHKey; let keyType: String @Published var keyName: String @Published var keyComment: String @Published var errorMessage = "" var isValid: Bool { !keyName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } init(key: SSHKey, keyName: String, keyComment: String) { self.key = key self.keyType = key.sshKeyType.shortName self.keyName = keyName self.keyComment = keyComment } func saveKey() -> Bool { errorMessage = "" let keyID = keyName.trimmingCharacters(in: .whitespacesAndNewlines) let comment = keyComment.trimmingCharacters(in: .whitespacesAndNewlines) do { if keyID.isEmpty { throw KeyUIError.emptyName } if BKPubKey.withID(keyID) != nil { throw KeyUIError.duplicateName(name: keyID) } try BKPubKey.addKeychainKey(id: keyID, key: key, comment: comment) } catch { errorMessage = error.localizedDescription return false } return true } }
gpl-3.0
3e75b7c10b6eab25fae34db50593d58e
28.081481
163
0.607234
4.591813
false
false
false
false
mohsenShakiba/ListView
Example/ListView/LabelCell.swift
1
1688
// // LabelCell.swift // Entekhabat // // Created by mohsen shakiba on 12/19/1395 AP. // Copyright © 1395 mohsen shakiba. All rights reserved. // import UIKit import ListView class LabelCell: ListViewCell { @IBOutlet weak var label: UILabel! @IBOutlet weak var bottomConstraint: NSLayoutConstraint! @IBOutlet weak var rightConstraint: NSLayoutConstraint! @IBOutlet weak var leftConstraint: NSLayoutConstraint! @IBOutlet weak var topConstraint: NSLayoutConstraint! override func awakeFromNib() { super.awakeFromNib() label.numberOfLines = 99 label.textAlignment = .center self.backgroundColor = .clear label.textColor = .gray setBorder(.bottom) } func size(_ top: CGFloat, _ right: CGFloat, _ bottom: CGFloat, _ left: CGFloat) { topConstraint.constant = top rightConstraint.constant = right leftConstraint.constant = left bottomConstraint.constant = bottom } override func height() -> CGFloat { var size = self.bounds.size size.height = .infinity let labelSize = label.sizeThatFits(self.label.bounds.size) let height = labelSize.height + topConstraint.constant + bottomConstraint.constant return height // return LabelCell.size(forStr: self.label.text ?? "") } static func size(forStr: String) -> CGFloat { let label = UILabel() let size = CGSize(width: UIScreen.main.bounds.width - 40, height: .infinity) label.numberOfLines = 99 label.text = forStr let height = label.sizeThatFits(size).height return height + 16 } }
mit
29101d300351deb9df8fcc403c90576a
29.125
90
0.648488
4.621918
false
false
false
false
SanctionCo/pilot-ios
pilot/RegisterValidationForm.swift
1
1238
// // RegisterValidationForm.swift // pilot // // Created by Nick Eckert on 12/13/17. // Copyright © 2017 sanction. All rights reserved. // import Foundation struct RegisterValidationForm: ValidationForm { var email: String? var password: String? var confirmPassword: String? init(email: String?, password: String?, confirmPassword: String?) { self.email = email self.password = password self.confirmPassword = confirmPassword } func validate() -> ValidationError? { var validationError: ValidationError? = nil if let emailValidationError = validateEmail(email: email) { validationError = emailValidationError } if let passwordValidationError = validatePassword(password: password) { validationError = passwordValidationError } if let confirmPasswordValidationError = validatePassword(password: confirmPassword) { validationError = confirmPasswordValidationError } if let passwordMissMatchValidationError = validateEqualPasswords(passwordOne: password, passwordTwo: confirmPassword) { validationError = passwordMissMatchValidationError } return validationError } }
mit
a1b60bdac37a4f94b592017651c5edb1
27.113636
100
0.697656
5.354978
false
false
false
false
morgz/SwiftGoal
SwiftGoalTests/Models/ChangesetSpec.swift
3
2307
// // SwiftGoalTests.swift // SwiftGoalTests // // Created by Martin Richter on 10/05/15. // Copyright (c) 2015 Martin Richter. All rights reserved. // import Quick import Nimble @testable import SwiftGoal private struct Item: Equatable { let identifier: String let value: String } private func ==(lhs: Item, rhs: Item) -> Bool { return lhs.identifier == rhs.identifier } class ChangesetSpec: QuickSpec { override func spec() { let oldItems = [ Item(identifier: "cat", value: "Cat"), Item(identifier: "dog", value: "Dog"), Item(identifier: "fox", value: "Fox"), Item(identifier: "rat", value: "Rat"), Item(identifier: "yak", value: "Yak") ] describe("A Changeset") { it("should have the correct insertions, deletions and modifications") { let newItems = [ Item(identifier: "bat", value: "Bat"), Item(identifier: "cow", value: "Cow"), Item(identifier: "dog", value: "A different dog"), Item(identifier: "fox", value: "Fox"), Item(identifier: "pig", value: "Pig"), Item(identifier: "yak", value: "A different yak") ] let changeset = Changeset( oldItems: oldItems, newItems: newItems, contentMatches: { item1, item2 in item1.value == item2.value } ) let deletion1 = NSIndexPath(forRow: 0, inSection: 0) let deletion2 = NSIndexPath(forRow: 3, inSection: 0) let modification1 = NSIndexPath(forRow: 1, inSection: 0) let modification2 = NSIndexPath(forRow: 4, inSection: 0) let insertion1 = NSIndexPath(forRow: 0, inSection: 0) let insertion2 = NSIndexPath(forRow: 1, inSection: 0) let insertion3 = NSIndexPath(forRow: 4, inSection: 0) expect(changeset.deletions).to(equal([deletion1, deletion2])) expect(changeset.modifications).to(equal([modification1, modification2])) expect(changeset.insertions).to(equal([insertion1, insertion2, insertion3])) } } } }
mit
6a8a359e6bf40f7f7e8d911cc1ebad35
32.926471
92
0.550498
4.445087
false
false
false
false
findM/PasswordView
SetPassWordView/SetPassWordView.swift
1
4262
// // SetPassWordView.swift // SampleDemo // // Created by 陈光临 on 15/11/30. // Copyright © 2015年 cn.chenguanglin. All rights reserved. // import UIKit // MARK: - UIView的扩展 extension UIView{ func removeAllSubviews(){ for view:UIView in self.subviews{ view.removeFromSuperview() } } func removeSubViewWithTag(tag:Int){ for view:UIView in self.subviews{ if(view.tag == tag){ view.removeFromSuperview() } } } } /// 输密码完成的回调 typealias doneActionBlock = (String) -> () internal class SetPassWordView: UIView ,UITextFieldDelegate{ //MARK: public /// 密码数量 var count = 6 /// 线条颜色 var lineColor: UIColor = UIColor.grayColor() /// 点点颜色 var dotColor: UIColor = UIColor.grayColor() /// 点点大小 var dotRadius: CGFloat = 10 /// 完成输入的回调 var doneAction: doneActionBlock? override func layoutSubviews() { super.layoutSubviews() self.layer.borderColor = lineColor.CGColor inputeTextField.frame = CGRect(x: 0, y: 0, width: 100, height: 40) renderLine(self) } //MARK: private private let dotTag = 1 private lazy var inputeTextField: UITextField = { let inputeTextField = UITextField() inputeTextField.keyboardType = .NumberPad inputeTextField.delegate = self inputeTextField.hidden = true return inputeTextField }() private func renderLine(bgView:UIView){ let w:CGFloat = self.width / CGFloat(count) let h:CGFloat = self.height var x: CGFloat = 0 for index in 1...count - 1{ x = CGFloat(index) * w let line = UIImageView() line.frame = CGRect(x: x, y: 0.0, width: 0.5, height: h) line.backgroundColor = lineColor bgView.addSubview(line) } } private func renderDot(fieldView:UITextField,bgView:UIView){ let w:CGFloat = self.width / CGFloat(self.count) let h:CGFloat = self.height var x:CGFloat = (w - dotRadius) / 2 let y:CGFloat = (h - dotRadius) / 2 let count = fieldView.text?.characters.count < 7 ? fieldView.text?.characters.count: 6 for var index = 0; index < count; ++index { let dot = UIView() dot.tag = dotTag dot.backgroundColor = dotColor dot.frame = CGRect(x: x, y: y, width: dotRadius, height: dotRadius) x = x + w dot.layer.cornerRadius = dot.width / 2 dot.clipsToBounds = true bgView.addSubview(dot) } } func fieldViewDidChange(){ self.removeSubViewWithTag(dotTag) renderDot(inputeTextField, bgView: self) if(inputeTextField.text?.characters.count == count && self.doneAction != nil){ self.doneAction!(inputeTextField.text!) } } func tapAction(){ self.inputeTextField.becomeFirstResponder() } //MARK: init override init(frame: CGRect) { super.init(frame: frame) setUpSubViews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setUpSubViews() } private func setUpSubViews(){ self.layer.borderWidth = 0.5 self.layer.borderColor = lineColor.CGColor let tap = UITapGestureRecognizer(target: self, action: "tapAction") self.addGestureRecognizer(tap) self.addSubview(inputeTextField) NSNotificationCenter.defaultCenter().addObserver(self, selector: "fieldViewDidChange", name: UITextFieldTextDidChangeNotification, object: inputeTextField) } //MARK: UITextFieldDelegate func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let str = textField.text! + string if(str.characters.count > count){ return false }else{ return true } } }
mit
41adf59456c8bb75e4ece91619ca6101
25.656051
163
0.580167
4.519438
false
false
false
false
uber/rides-ios-sdk
source/UberRides/EndpointsManager.swift
1
12051
// // EndpointsManager.swift // UberRides // // Copyright © 2015 Uber Technologies, Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import CoreLocation import UberCore /// Convenience enum for managing versions of resources. private enum Resources: String { case estimates = "estimates" case history = "history" case me = "me" case paymentMethod = "payment-methods" case places = "places" case products = "products" case request = "requests" private var version: String { switch self { case .estimates: return "v1.2" case .history: return "v1.2" case .me: return "v1.2" case .paymentMethod: return "v1.2" case .places: return "v1.2" case .products: return "v1.2" case .request: return "v1.2" } } fileprivate var basePath: String { return "/\(version)/\(rawValue)" } } /** Endpoints related to components. - RideRequestWidget: Ride Request Widget endpoint. - Warning: The Ride Request Widget is deprecated, and will no longer work for new apps. Existing apps have until 05/31/2018 to migrate. See the Uber API Changelog for more details. */ enum Components: APIEndpoint { case rideRequestWidget(rideParameters: RideParameters?) var method: UberHTTPMethod { switch self { case .rideRequestWidget: return .get } } var host: String { return "https://components.uber.com" } var path: String { switch self { case .rideRequestWidget: return "/rides/" } } var query: [URLQueryItem] { switch self { case .rideRequestWidget(let rideParameters): let environment = Configuration.shared.isSandbox ? "sandbox" : "production" var queryItems = queryBuilder( ("env", "\(environment)") ) if let rideParameters = rideParameters { queryItems.append(contentsOf: RequestURLUtil.buildRequestQueryParameters(rideParameters)) } return queryItems } } } /** API endpoints for the Products resource. - GetAll: Returns information about the Uber products offered at a given location (lat, long). - GetProduct: Returns information about the Uber product specified by product ID. */ enum Products: APIEndpoint { case getAll(location: CLLocation) case getProduct(productID: String) var method: UberHTTPMethod { switch self { case .getAll: fallthrough case .getProduct: return .get } } var path: String { switch self { case .getAll: return Resources.products.basePath case .getProduct(let productID): return "\(Resources.products.basePath)/\(productID)" } } var query: [URLQueryItem] { switch self { case .getAll(let location): return queryBuilder( ("latitude", "\(location.coordinate.latitude)"), ("longitude", "\(location.coordinate.longitude)")) case .getProduct: return queryBuilder() } } } /** API Endpoints for the Estimates resource. - Price: Returns an estimated range for each product offered between two locations (lat, long). - Time: Returns ETAs for all products offered at a given location (lat, long). */ enum Estimates: APIEndpoint { case price(startLocation: CLLocation, endLocation: CLLocation) case time(location: CLLocation, productID: String?) var method: UberHTTPMethod { switch self { case .price: fallthrough case .time: return .get } } var path: String { switch self { case .price: return "\(Resources.estimates.basePath)/price" case .time: return "\(Resources.estimates.basePath)/time" } } var query: [URLQueryItem] { switch self { case .price(let startLocation, let endLocation): return queryBuilder( ("start_latitude", "\(startLocation.coordinate.latitude)"), ("start_longitude", "\(startLocation.coordinate.longitude)"), ("end_latitude", "\(endLocation.coordinate.latitude)"), ("end_longitude", "\(endLocation.coordinate.longitude)")) case .time(let location, let productID): return queryBuilder( ("start_latitude", "\(location.coordinate.latitude)"), ("start_longitude", "\(location.coordinate.longitude)"), ("product_id", productID == nil ? "" : "\(productID!)")) } } } /** API Endpoints for the History v1.2 resource. - Get: Returns limited data about a user's lifetime activity with Uber. */ enum History: APIEndpoint { case get(offset: Int?, limit: Int?) var method: UberHTTPMethod { switch self { case .get: return .get } } var path: String { switch self { case .get: return Resources.history.basePath } } var query: [URLQueryItem] { switch self { case .get(let offset, let limit): return queryBuilder( ("offset", offset == nil ? "" : "\(offset!)"), ("limit", limit == nil ? "" : "\(limit!)")) } } } /** API Endpoints for the Me resource. - UserProfile: Returns information about the Uber user that has authorized the application. */ enum Me: APIEndpoint { case userProfile var method: UberHTTPMethod { switch self { case .userProfile: return .get } } var path: String { switch self { case .userProfile: return Resources.me.basePath } } var query: [URLQueryItem] { switch self { case .userProfile: return queryBuilder() } } } /** API endpoints for the Requests resource. - Make: Request a ride on behalf of Uber user. - GetCurrent: Returns real-time details for an ongoing trip. - GetRequest: Get the status of an ongoing or completed trip that was created using the Ride Request endpoint. - Estimate: Gets an estimate for a ride given the desired product, start, and end locations. */ enum Requests: APIEndpoint { case deleteCurrent case deleteRequest(requestID: String) case estimate(rideParameters: RideParameters) case getCurrent case getRequest(requestID: String) case make(rideParameters: RideParameters) case patchCurrent(rideParameters: RideParameters) case patchRequest(requestID: String, rideParameters: RideParameters) case rideMap(requestID: String) case rideReceipt(requestID: String) var body: Data? { switch self { case .deleteCurrent: fallthrough case .deleteRequest: return nil case .estimate(let rideParameters): return RideRequestDataBuilder(rideParameters: rideParameters).build() case .getCurrent: fallthrough case .getRequest: return nil case .make(let rideParameters): return RideRequestDataBuilder(rideParameters: rideParameters).build() case .patchCurrent(let rideParameters): return RideRequestDataBuilder(rideParameters: rideParameters).build() case .patchRequest(_, let rideParameters): return RideRequestDataBuilder(rideParameters: rideParameters).build() case .rideMap: return nil case .rideReceipt: return nil } } var headers: [String : String]? { return ["Content-Type": "application/json"] } var method: UberHTTPMethod { switch self { case .deleteCurrent: fallthrough case .deleteRequest: return .delete case .estimate: return .post case .getCurrent: fallthrough case .getRequest: return .get case .make: return .post case .patchCurrent: fallthrough case .patchRequest: return .patch case .rideMap: return .get case .rideReceipt: return .get } } var path: String { switch self { case .deleteCurrent: return "\(Resources.request.basePath)/current" case .deleteRequest(let requestID): return "\(Resources.request.basePath)/\(requestID)" case .estimate: return "\(Resources.request.basePath)/estimate" case .getCurrent: return "\(Resources.request.basePath)/current" case .getRequest(let requestID): return "\(Resources.request.basePath)/\(requestID)" case .make: return Resources.request.basePath case .patchCurrent: return "\(Resources.request.basePath)/current" case .patchRequest(let requestID, _): return "\(Resources.request.basePath)/\(requestID)" case .rideMap(let requestID): return "\(Resources.request.basePath)/\(requestID)/map" case .rideReceipt(let requestID): return "\(Resources.request.basePath)/\(requestID)/receipt" } } var query: [URLQueryItem] { return [] } } enum Payment: APIEndpoint { case getMethods var body: Data? { return nil } var method: UberHTTPMethod { return .get } var path: String { return Resources.paymentMethod.basePath } var query: [URLQueryItem] { return [] } } enum Places: APIEndpoint { case getPlace(placeID: String) case putPlace(placeID: String, address: String) var body: Data? { switch self { case .getPlace: return nil case .putPlace(_, let address): do { let data = try JSONSerialization.data(withJSONObject: ["address": address], options: []) return data } catch { } return nil } } var headers: [String : String]? { switch self { case .getPlace: return nil case .putPlace: return ["Content-Type": "application/json"] } } var method: UberHTTPMethod { switch self { case .getPlace: return .get case .putPlace: return .put } } var path: String { switch self { case .getPlace(let placeID): return "\(Resources.places.basePath)/\(placeID)" case .putPlace(let placeID, _): return "\(Resources.places.basePath)/\(placeID)" } } var query: [URLQueryItem] { return [] } }
mit
1e9657fe3905a643d9cb30909bb45503
28.036145
111
0.594772
4.880518
false
false
false
false
DanielAsher/SwiftParse
SwiftParse/Playgrounds/PrettyPrinter.playground/Pages/OperatorAssociativity.xcplaygroundpage/Sources/Array+Ext.swift
1
581
public enum ArrayMatcher<A> { case Nil case Cons(A, [A]) } extension Array { /// Destructures a list into its constituent parts. /// /// If the given list is empty, this function returns .Nil. If the list is non-empty, this /// function returns .Cons(head, tail) public var match : ArrayMatcher<Element> { if self.count == 0 { return .Nil } else if self.count == 1 { return .Cons(self[0], []) } let hd = self[0] let tl = Array(self[1..<self.count]) return .Cons(hd, tl) } }
mit
5e63e78e5485ff9640864a0de08ff56e
25.409091
95
0.550775
3.724359
false
false
false
false
AlexZd/SRT
Pod/Utils/UIViewController+Helpers.swift
1
598
// // UIViewController+Helpers.swift // // Created by Alex Zdorovets on 6/18/15. // Copyright (c) 2015 Alex Zdorovets. All rights reserved. // import UIKit extension UIViewController { public func fixIOS9PopOverAnchor(segue:UIStoryboardSegue?) { guard #available(iOS 9.0, *) else { return } if let popOver = segue?.destinationViewController.popoverPresentationController, let anchor = popOver.sourceView where popOver.sourceRect == CGRect() && segue!.sourceViewController === self { popOver.sourceRect = anchor.bounds } } }
mit
45e402b24089135daf6d9c4c98d0aa47
28.95
200
0.670569
4.333333
false
false
false
false
mattdonnelly/Swifter
Sources/SwifterCredential.swift
1
2717
// // Credential.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation #if os(macOS) || os(iOS) import Accounts #endif public class Credential { public struct OAuthAccessToken { public internal(set) var key: String public internal(set) var secret: String public internal(set) var verifier: String? public internal(set) var screenName: String? public internal(set) var userID: String? public init(key: String, secret: String) { self.key = key self.secret = secret self.userID = key.components(separatedBy: "-").first } public init(queryString: String) { let attributes = queryString.queryStringParameters self.key = attributes["oauth_token"]! self.secret = attributes["oauth_token_secret"]! self.screenName = attributes["screen_name"] self.userID = attributes["user_id"] } } public internal(set) var accessToken: OAuthAccessToken? #if os(macOS) || os(iOS) @available(iOS, deprecated: 11.0, message: "Using ACAccount for Twitter is no longer supported as of iOS 11.") public internal(set) var account: ACAccount? @available(iOS, deprecated: 11.0, message: "Using ACAccount for Twitter is no longer supported as of iOS 11.") public init(account: ACAccount) { self.account = account } #endif public init(accessToken: OAuthAccessToken) { self.accessToken = accessToken } }
mit
266ee35c36057a7876619688e8b5e3b9
34.285714
114
0.6636
4.566387
false
false
false
false
Sivintech/code-samples
swift/chained_XML_response_rendering.swift
1
5930
import UIKit // XMLResponseRepresentation represents the root element of an XML response // (the root tag). As it adopts GenericXMLItem, MappedXMLItem and // RootXMLItem, it's able to parse XML data, map XML values onto it's // properties and pass the control of the XML parser down to its child // objects representation. class XMLResponseRepresentation : GenericXMLItem, MappedXMLItem, RootXMLItem { var responseHash: Int { get { return _responseHash } } private var _responseHash: Int = 0 var version: String? var childNodes: Array<GenericXMLItem> = Array<GenericXMLItem>() private var callback: ((responseRepresentation: XMLResponseRepresentation, error: NSError?) -> Void)? var error: ServerError? private var parser: NSXMLParser? private var dataToParse: NSData? override init() { super.init(attributes: nil) } // MARK: - RootXMLItem required convenience init(asRootElementWithXMLData XMLData: NSData, id: Int = 0) { self.init(attributes: nil) setUpForParsingData(XMLData) root = self _responseHash = id } required init(attributes: Dictionary<NSObject, AnyObject>!) { super.init(attributes: attributes) } func renderWithAdUnwrappingEndCallback(responseParsingEndCallBack: ((responseRepresentation: XMLResponseRepresentation, error: NSError?) -> Void)?) -> Void { callback = responseParsingEndCallBack if let value = value { if let wrappedResponseURL = NSURL(string: value) { visitURL(wrappedResponseURL, completionHandler: { [weak self] (success, data) -> Void in if (success) { if (data.length > 0) { self?.setUpForParsingData(data) self?.parser?.parse() } } }) } } var status = false if let parsingStatus = parser?.parse() { status = parsingStatus && (dataToParse?.length > 0) } if (status == false) { let error = NSError(domain: "XMLResponseRepresentation.NSXMLParser", code: 123, userInfo: ["Error description" : "The data to parse is empty"]) callback?(responseRepresentation: self, error:error) } } // MARK: - MappedXMLItem override func classForTagNamed() -> () -> Dictionary<String, GenericXMLItem.Type> { let classMap: Dictionary<String, GenericXMLItem.Type> = ["ChildNode" : VASTchildNode.self, "Error" : ServerError.self] // Here's what is called the Module design pattern. It just mimics the static variable for classMap. func module() -> Dictionary<String, GenericXMLItem.Type> { return classMap } return module } override func keyPathForTagNamed() -> () -> Dictionary<String, String> { let keyPathMap: Dictionary<String, String> = ["ChildNode" : "childNodes", "Error" : "error"] // Here's what is called the Module design pattern. func module() -> Dictionary<String, String> { return keyPathMap } return module } override func actionForKeyPath() -> () -> Dictionary<String, KVCBinder> { let actionMap: Dictionary<String, KVCBinder> = ["childNodes" : inserter, "error" : assignor] func module() -> Dictionary<String, KVCBinder> { return actionMap } return module } // MARK: - internal (for future overriding) internal func setUpForParsingData(XMLData: NSData) { self.dataToParse = XMLData parser = NSXMLParser(data: XMLData) //as the standard SAX parser from UIKit doesn't allow reentrant parsing parser?.delegate = self } // MARK: - NSXMLParserDelegate override func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) -> Void { if let callback = callback { callback(responseRepresentation: self, error: parseError) } } override func parser(parser: NSXMLParser, validationErrorOccurred validationError: NSError) -> Void { if let callback = callback { callback(responseRepresentation: self, error: validationError) } } override func parserDidEndDocument(parser: NSXMLParser) -> Void { let childNodes = self.childNodes if (childNodes.count > 0) { for childNode in childNodes { if let wrappedResponse = childNode.wrappedResponse { if let type = childNode.type { if (type == XMLResponseType.Chained) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {[unowned self]() -> Void in wrappedResponse.renderWithAdUnwrappingEndCallback(self.callback) } } } } else if let callback = self.callback { callback(responseRepresentation: self, error: nil) self.callback = nil } } } else { if let callback = self.callback { callback(responseRepresentation: self, error: nil) self.callback = nil } } parser.delegate = nil } }
mit
34f963093364edced4b1502690fb5478
30.215789
159
0.548735
5.183566
false
false
false
false
collegboi/iOS-Sprite-Game
Part1/AnalogControl.swift
2
3028
// // AnalogControl.swift // Minnion Maze // // Created by Timothy Barnard on 13/12/2014. // Copyright (c) 2014 Timothy Barnard. All rights reserved. // import UIKit protocol AnalogControlPositionChange { func analogControlPositionChanged( analogControl: AnalogControl, position: CGPoint) } class AnalogControl: UIView { let baseCenter: CGPoint let knobImageView: UIImageView var relativePostion: CGPoint! var delegate: AnalogControlPositionChange? required init(coder aDecoder: NSCoder) { fatalError("NSCoding not supported") } override init(frame viewFrame: CGRect) { baseCenter = CGPoint(x: viewFrame.size.width / 2, y: viewFrame.size.height / 2) knobImageView = UIImageView(image: UIImage(named: "knob")) knobImageView.frame.size.width /= 2 knobImageView.frame.size.height /= 2 knobImageView.center = baseCenter super.init(frame: viewFrame) userInteractionEnabled = false let baseImageView = UIImageView(frame: bounds) baseImageView.image = UIImage(named: "base") addSubview(baseImageView) addSubview(knobImageView) assert(CGRectContainsRect(bounds, knobImageView.bounds), "Analog contol should be larger than the knob in size") } func updateKnobWithPosition(postion: CGPoint) { var postionToCenter = postion - baseCenter var direction : CGPoint if postionToCenter == CGPointZero { direction = CGPointZero } else { direction = postionToCenter.normalized() } let radius = frame.size.width / 2 var length = postionToCenter.length() if length > radius { length = radius postionToCenter = direction * radius } let relPosition = CGPoint(x: direction.x * (length/radius), y: direction.y * (length/radius)) knobImageView.center = baseCenter + postionToCenter relativePostion = relPosition delegate?.analogControlPositionChanged(self, position: relativePostion) } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { let touchLocation = touches.anyObject()!.locationInView(self) updateKnobWithPosition(touchLocation) } override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { let touchLocation = touches.anyObject()!.locationInView(self) updateKnobWithPosition(touchLocation) } override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { updateKnobWithPosition(baseCenter) } override func touchesCancelled(touches: NSSet, withEvent event: UIEvent) { updateKnobWithPosition(baseCenter) } }
mit
e190bd6ef0430472974fd8803e30b365
27.037037
101
0.613937
5.229706
false
false
false
false
sammyd/Concurrency-VideoSeries
projects/003_AsyncOperations/003_DemoComplete/AsyncOperations.playground/Contents.swift
1
2280
import UIKit import XCPlayground //: # Concurrent NSOperations //: So far, you've discovered how to create an `NSOperation` subclass by overriding the `main()` method, but that will only work for synchronous tasks. //: Need long running playground XCPlaygroundPage.currentPage.needsIndefiniteExecution = true //: A abstract class for wrapping asynchronous functionality class ConcurrentOperation: NSOperation { enum State: String { case Ready, Executing, Finished private var keyPath: String { return "is" + rawValue } } var state = State.Ready { willSet { willChangeValueForKey(newValue.keyPath) willChangeValueForKey(state.keyPath) } didSet { didChangeValueForKey(oldValue.keyPath) didChangeValueForKey(state.keyPath) } } } extension ConcurrentOperation { //: NSOperation Overrides override var ready: Bool { return super.ready && state == .Ready } override var executing: Bool { return state == .Executing } override var finished: Bool { return state == .Finished } override var asynchronous: Bool { return true } override func start() { if cancelled { state = .Finished return } main() state = .Executing } override func cancel() { state = .Finished } } //: Concrete subclass of `ConcurrentOperation` to load data from a URL. //: This uses the async method on the network simulator to load it class DataLoadOperation: ConcurrentOperation { private let url: NSURL var loadedData: NSData? init(url: NSURL) { self.url = url super.init() } override func main() { NetworkSimulator.asyncLoadDataAtURL(url) { data in self.loadedData = data self.state = .Finished } } } //: Create imageURL and queue let imageURL = NSBundle.mainBundle().URLForResource("desert", withExtension: "jpg")! let queue = NSOperationQueue() //: Create the load operation and add it to the queue let loadOperation = DataLoadOperation(url: imageURL) queue.addOperation(loadOperation) //: Wait for the queue to complete queue.waitUntilAllOperationsAreFinished() //: Take a look at the resultant image if let readData = loadOperation.loadedData { UIImage(data: readData) }
mit
dce50ad526dd6ba8b086f9d76a683aa8
20.509434
151
0.689035
4.624746
false
false
false
false
jwfriese/Fleet
FleetTests/CoreExtensions/TableView/UITableViewRowAction+FleetSpec.swift
1
618
import XCTest import Nimble @testable import Fleet class UITableViewRowAction_FleetSpec: XCTestCase { override func setUp() { super.setUp() continueAfterFailure = false } func test_handler_returnsTheHandlerUsedToInitializeAction() { var didFireHandler = false let rowAction = UITableViewRowAction(style: .default, title: "turtle") { action, indexPath in didFireHandler = true } if let handler = rowAction.handler { handler(rowAction, IndexPath(row: 7, section: 14)) } expect(didFireHandler).to(beTrue()) } }
apache-2.0
53c6ff6d0778b6d0cc1725471c983d47
23.72
101
0.645631
4.681818
false
true
false
false
mthistle/BandPersonalizationSwift
BandPersonalizationSwift/ViewController.swift
1
2837
// // ViewController.swift // BandPersonalizationSwift // // Created by Mark Thistle on 4/9/15. // Copyright (c) 2015 New Thistle LLC. All rights reserved. // import UIKit class ViewController: UIViewController, MSBClientManagerDelegate { @IBOutlet weak var txtOutput: UITextView! @IBOutlet weak var accelLabel: UILabel! weak var client: MSBClient? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. MSBClientManager.sharedManager().delegate = self if let client = MSBClientManager.sharedManager().attachedClients().first as? MSBClient { self.client = client MSBClientManager.sharedManager().connectClient(self.client) self.output("Please wait. Connecting to Band...") } else { self.output("Failed! No Bands attached.") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func runExampleCode(sender: AnyObject) { if let client = self.client { if client.isDeviceConnected == false { self.output("Band is not connected. Please wait....") return } self.output("Updating MeTile image...") var image = MSBImage(UIImage:UIImage(named: "SampleMeTileImage.jpg")) client.personalizationManager.updateMeTileImage(image, completionHandler: { (error: NSError!) in if error == nil { self.output("Successfully Finished!!!") } else { self.output(error.localizedDescription) } }) } else { self.output("Band is not connected. Please wait....") } } func output(message: String) { self.txtOutput.text = NSString(format: "%@\n%@", self.txtOutput.text, message) as String let p = self.txtOutput.contentOffset self.txtOutput.setContentOffset(p, animated: false) self.txtOutput.scrollRangeToVisible(NSMakeRange(self.txtOutput.text.lengthOfBytesUsingEncoding(NSASCIIStringEncoding), 0)) } // Mark - Client Manager Delegates func clientManager(clientManager: MSBClientManager!, clientDidConnect client: MSBClient!) { self.output("Band connected.") } func clientManager(clientManager: MSBClientManager!, clientDidDisconnect client: MSBClient!) { self.output(")Band disconnected.") } func clientManager(clientManager: MSBClientManager!, client: MSBClient!, didFailToConnectWithError error: NSError!) { self.output("Failed to connect to Band.") self.output(error.description) } }
mit
413e733feb986b021c9eb4294dd9f9ac
35.844156
130
0.633416
4.82483
false
false
false
false
m-alani/contests
hackerrank/Staircase.swift
1
610
// // Staircase.swift // // Practice solution - Marwan Alani - 2017 // // Check the problem (and run the code) on HackerRank @ https://www.hackerrank.com/challenges/staircase // Note: make sure that you select "Swift" from the top-right language menu of the code editor when testing this code // import Foundation // read the integer n let n = Int(readLine()!)! // print the staircase for steps in 1...n { var outputLine = "" var spaces = n - steps while (spaces > 0) { outputLine += " " spaces -= 1 } for _ in 1...steps { outputLine += "#" } print(outputLine) }
mit
441e1006463b86ab7a28275e44febb42
23.4
118
0.629508
3.546512
false
false
false
false
IvanVorobei/Sparrow
sparrow/ui/views/views/SPGradeWithBlurView.swift
2
2680
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit class SPGradeWithBlurView: UIView { internal var gradeView: UIView = UIView() internal var blurView: UIView = UIView() init(gradeColor: UIColor = UIColor.black, gradeAlphaFactor: CGFloat = 0.1, blurRadius: CGFloat = 3) { super.init(frame: CGRect.zero) self.setGradeColor(gradeColor) self.setGradeAlpha(gradeAlphaFactor, blurRaius: blurRadius) self.commonInit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func commonInit() { if #available(iOS 9, *) { self.blurView = SPBlurView() } self.layer.masksToBounds = true self.addSubview(gradeView) self.addSubview(blurView) } func setGradeColor(_ color: UIColor) { self.gradeView.backgroundColor = UIColor.black } func setGradeAlpha(_ alpha: CGFloat) { self.gradeView.alpha = alpha } func setBlurRadius(_ radius: CGFloat) { if #available(iOS 9, *) { if let blurView = self.blurView as? SPBlurView { blurView.setBlurRadius(radius) } } } func setGradeAlpha(_ alpha: CGFloat, blurRaius: CGFloat) { self.setGradeAlpha(alpha) self.setBlurRadius(blurRaius) } override func layoutSubviews() { super.layoutSubviews() self.gradeView.frame = self.bounds self.blurView.frame = self.bounds } }
mit
3c22f9266ad9bf171fd7218bb01b069a
34.72
105
0.673759
4.43543
false
false
false
false
siemensikkema/Fairness
FairnessTests/ParticipantCellTests.swift
1
3292
import XCTest import UIKit class ParticipantCellTests: XCTestCase { class TextEditControllerForTesting: NSObject, TextEditControllerInterface { var textField: UITextField! var textChangeCallback: TextChangeCallback! func configureWithTextField(textField: UITextField, textChangeCallback: TextChangeCallback) { self.textField = textField self.textChangeCallback = textChangeCallback } } class ParticipantTransactionViewModelForTesting: ParticipantTransactionViewModelInterface { var amountString: String { return "amount" } var isPayee: Bool = false var isPayer: Bool = false var nameOrNil: String? { return "name" } } var amountLabel: UILabel! var nameTextField: ParticipantNameTextField! var sut: ParticipantCell! let participantTransactionViewModel = ParticipantTransactionViewModelForTesting() let window = UIWindow() var textEditController: TextEditControllerForTesting! override func setUp() { amountLabel = UILabel() nameTextField = ParticipantNameTextField() textEditController = TextEditControllerForTesting() sut = ParticipantCell(style: .Default, reuseIdentifier: ParticipantCell.reuseIdentifier(), textEditController: textEditController) sut.amountLabel = amountLabel sut.nameTextField = nameTextField window.addSubview(nameTextField) sut.configureWithParticipantTransactionViewModel(participantTransactionViewModel, textChangeCallback: { _ in }) } func testReuseIdentifier() { XCTAssertEqual(ParticipantCell.reuseIdentifier(), "Participant") } func testAmountLabelTextGetsSet() { XCTAssertEqual(amountLabel.text!, participantTransactionViewModel.amountString) } func testNameTextFieldTextGetsSet() { XCTAssertEqual(nameTextField.text!, participantTransactionViewModel.nameOrNil!) } func testTextEditControllerGetsSet() { XCTAssertNotNil(sut.textEditController) } func testTextEditorGetsConfiguredWithTextFieldAndCallback() { XCTAssertEqual(textEditController.textField, nameTextField) XCTAssertFalse(textEditController.textChangeCallback == nil) } func testBackgroundColorIsWhiteForNonPayees() { XCTAssertEqual(sut.backgroundColor!, UIColor.whiteColor()) } func testBackgroundColorIsGreenForPayees() { participantTransactionViewModel.isPayee = true sut.configureWithParticipantTransactionViewModel(participantTransactionViewModel, textChangeCallback: { _ in }) XCTAssertEqual(sut.backgroundColor!, UIColor.greenColor()) } func testBorderIsAbsentForNonPayers() { XCTAssertEqual(sut.layer.borderWidth, 0 as CGFloat) } func testBorderIsPresentForPayers() { participantTransactionViewModel.isPayer = true sut.configureWithParticipantTransactionViewModel(participantTransactionViewModel, textChangeCallback: { _ in }) XCTAssertEqual(sut.layer.borderWidth, 1 as CGFloat) } func testTextFieldEditingIsEndedWhenSettingEditingToFalse() { nameTextField.becomeFirstResponder() sut.setEditing(false, animated: false) XCTAssertFalse(nameTextField.editing) } }
mit
f6ab9713f1060c99d2894ef4c755e411
36
138
0.738153
5.560811
false
true
false
false
GraphQLSwift/GraphQL
Sources/GraphQL/Subscription/EventStream.swift
1
3065
/// Abstract event stream class - Should be overridden for actual implementations open class EventStream<Element> { public init() {} /// Template method for mapping an event stream to a new generic type - MUST be overridden by implementing types. open func map<To>(_: @escaping (Element) throws -> To) -> EventStream<To> { fatalError("This function should be overridden by implementing classes") } } #if compiler(>=5.5) && canImport(_Concurrency) @available(macOS 12, iOS 15, watchOS 8, tvOS 15, *) /// Event stream that wraps an `AsyncThrowingStream` from Swift's standard concurrency system. public class ConcurrentEventStream<Element>: EventStream<Element> { public let stream: AsyncThrowingStream<Element, Error> public init(_ stream: AsyncThrowingStream<Element, Error>) { self.stream = stream } /// Performs the closure on each event in the current stream and returns a stream of the results. /// - Parameter closure: The closure to apply to each event in the stream /// - Returns: A stream of the results override open func map<To>(_ closure: @escaping (Element) throws -> To) -> ConcurrentEventStream<To> { let newStream = stream.mapStream(closure) return ConcurrentEventStream<To>.init(newStream) } } @available(macOS 12, iOS 15, watchOS 8, tvOS 15, *) extension AsyncThrowingStream { func mapStream<To>(_ closure: @escaping (Element) throws -> To) -> AsyncThrowingStream<To, Error> { return AsyncThrowingStream<To, Error> { continuation in let task = Task { do { for try await event in self { let newEvent = try closure(event) continuation.yield(newEvent) } continuation.finish() } catch { continuation.finish(throwing: error) } } continuation.onTermination = { @Sendable reason in task.cancel() } } } func filterStream(_ isIncluded: @escaping (Element) throws -> Bool) -> AsyncThrowingStream<Element, Error> { return AsyncThrowingStream<Element, Error> { continuation in let task = Task { do { for try await event in self { if try isIncluded(event) { continuation.yield(event) } } continuation.finish() } catch { continuation.finish(throwing: error) } } continuation.onTermination = { @Sendable _ in task.cancel() } } } } #endif
mit
4b060c7be6430c6d8c032d5e9e94119e
37.3125
117
0.523002
5.623853
false
false
false
false
Zewo/Reflection
Sources/Reflection/Set.swift
2
916
/// Set value for key of an instance public func set(_ value: Any, key: String, for instance: inout Any) throws { let type = Swift.type(of: instance) try property(type: type, key: key).write(value, to: mutableStorage(instance: &instance, type: type)) } /// Set value for key of an instance public func set(_ value: Any, key: String, for instance: AnyObject) throws { var copy: Any = instance try set(value, key: key, for: &copy) } /// Set value for key of an instance public func set<T>(_ value: Any, key: String, for instance: inout T) throws { try property(type: T.self, key: key).write(value, to: mutableStorage(instance: &instance)) } private func property(type: Any.Type, key: String) throws -> Property.Description { guard let property = try properties(type).first(where: { $0.key == key }) else { throw ReflectionError.instanceHasNoKey(type: type, key: key) } return property }
mit
042937c931e85087c4bdc422f9439b52
42.619048
147
0.694323
3.53668
false
false
false
false
alexbasson/swift-experiment
SwiftExperimentTests/Models/PostersSpec.swift
1
3242
import Quick import Nimble import SwiftExperiment class PostersSpec: QuickSpec { override func spec() { let thumbnailURL = NSURL(string: "thumbnailURL")! let profileURL = NSURL(string: "profileURL")! let detailedURL = NSURL(string: "detailedURL")! let originalURL = NSURL(string: "originalURL")! let unequalURL = NSURL(string: "unequalURL")! describe("==") { var subject: Posters! var equalToSubject: Posters! var unequalToSubject: Posters! beforeEach { subject = Posters(thumbnailURL: thumbnailURL, profileURL: profileURL, detailedURL: detailedURL, originalURL: originalURL) } it("equates posters with the same urls") { equalToSubject = Posters(thumbnailURL: thumbnailURL, profileURL: profileURL, detailedURL: detailedURL, originalURL: originalURL); expect(subject).to(equal(equalToSubject)) } it("unequates posters with different thumbnail urls") { unequalToSubject = Posters(thumbnailURL: unequalURL, profileURL: profileURL, detailedURL: detailedURL, originalURL: originalURL) expect(subject).notTo(equal(unequalToSubject)) } it("unequates posters with different profile urls") { unequalToSubject = Posters(thumbnailURL: thumbnailURL, profileURL: unequalURL, detailedURL: detailedURL, originalURL: originalURL) expect(subject).notTo(equal(unequalToSubject)) } it("unequates posters with different detailed urls") { unequalToSubject = Posters(thumbnailURL: thumbnailURL, profileURL: profileURL, detailedURL: unequalURL, originalURL: originalURL) expect(subject).notTo(equal(unequalToSubject)) } it("unequates posters with different original urls") { unequalToSubject = Posters(thumbnailURL: thumbnailURL, profileURL: profileURL, detailedURL: detailedURL, originalURL: unequalURL) expect(subject).notTo(equal(unequalToSubject)) } } describe("serializable") { var subject: Posters! var dictionary: Dictionary<String, AnyObject>! describe("serialize") { beforeEach { subject = Posters() } it("serializes the posters") { let dict = subject.serialize() expect(dict["thumbnail"] as? String).to(equal("example.com/posters/thumbnail")) expect(dict["profile"] as? String).to(equal("example.com/posters/profile")) expect(dict["detailed"] as? String).to(equal("example.com/posters/detailed")) expect(dict["original"] as? String).to(equal("example.com/posters/original")) } } describe("init(dict:))") { beforeEach { subject = Posters() dictionary = [ "thumbnail": "example.com/posters/thumbnail", "profile": "example.com/posters/profile", "detailed": "example.com/posters/detailed", "original": "example.com/posters/original" ] } it("deserialized the dictionary into Posters") { expect(Posters(dict: dictionary)).to(equal(subject)) } } } } }
mit
c686037b61229d8f74d28cd703c66e2d
37.595238
140
0.631092
4.86057
false
false
false
false
leo-lp/LPIM
LPIM/Classes/Card/LPNormalTeamListViewController.swift
1
3135
// // LPNormalTeamListViewController.swift // LPIM // // Created by lipeng on 2017/6/28. // Copyright © 2017年 lipeng. All rights reserved. // import UIKit class LPNormalTeamListViewController: 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 numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false 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, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .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, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
cf4459bd90194632f7f9d05ae1b459bd
31.968421
136
0.671456
5.272727
false
false
false
false
wtrumler/FluentSwiftAssertions
FluentSwiftAssertions/DictionaryExtension.swift
1
1498
// // DictionaryExtension.swift // FluentSwiftAssertions // // Created by Wolfgang Trumler on 23.03.17. // Copyright © 2017 Wolfgang Trumler. All rights reserved. // import Foundation import XCTest extension Dictionary where Value: Equatable { public var should : Dictionary { return self } public func beEqualTo( _ expression2: @autoclosure () throws -> [Key : Value], _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line, assertionFunction : @escaping (_ exp1: @autoclosure () throws -> [Key : Value], _ exp2: @autoclosure () throws -> [Key : Value], _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertEqual) { assertionFunction(self, expression2, message, file, line) } public func notBeEqualTo( _ expression2: @autoclosure () throws -> [Key : Value], _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line, assertionFunction : @escaping (_ exp1: @autoclosure () throws -> [Key : Value], _ exp2: @autoclosure () throws -> [Key : Value], _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertNotEqual) { assertionFunction(self, expression2, message, file, line) } }
mit
e7fb0089a0e40eecfc0fe3b702cdbb2a
41.771429
260
0.563126
4.678125
false
false
false
false
vauxhall/worldcities
worldcities/Model/ModelList.swift
1
606
import Foundation class ModelList { private(set) var itemsMap:[String:[ModelListItem]] private(set) var items:[ModelListItem] private(set) var displayItems:[ModelListItem] init() { itemsMap = [:] items = [] displayItems = [] } //MARK: internal func itemsLoaded( items:[ModelListItem], itemsMap:[String:[ModelListItem]]) { self.items = items self.itemsMap = itemsMap } func updateDisplayItems(searchString:String) { displayItems = searchItems(forInput:searchString) } }
mit
c12658aee7494d1528e8db5bf27337dc
19.2
57
0.589109
4.423358
false
false
false
false
andrew8712/DCKit
DCKit/UITextFields/DCMandatoryNumberTextField.swift
2
1388
// // MandatoryNumberTextField.swift // DCKit // // Created by Andrey Gordeev on 11/03/15. // Copyright (c) 2015 Andrey Gordeev ([email protected]). All rights reserved. // import UIKit /// Allows to set a max possible value. @IBDesignable open class DCMandatoryNumberTextField: DCMandatoryTextField { // MARK: - Initializers // IBDesignables require both of these inits, otherwise we'll get an error: IBDesignable View Rendering times out. // http://stackoverflow.com/questions/26772729/ibdesignable-view-rendering-times-out override public init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /// The field's value will be compared against this property. /// - seealso: `isValid()` @IBInspectable open var maxValue: Float = 999 // MARK: - Build control override open func customInit() { super.customInit() keyboardType = UIKeyboardType.decimalPad } // MARK: - Validation override open func isValid() -> Bool { var valid = true if let value = Float(text ?? "") { valid = value < maxValue } else { // If the field is Mandatory and empty - it's invalid valid = !isMandatory } isSelected = !valid return valid } }
mit
0288c39c972b05ef884027a44a98eb3c
24.703704
118
0.636167
4.257669
false
false
false
false
ryuichis/swift-ast
Sources/Lexer/Lexer+Operator.swift
2
2937
/* Copyright 2015-2017, 2019 Ryuichi Intellectual Property and the Yanagiba project contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ extension Lexer /* operator */ { func lexReservedOperator(prev: Role) -> Token.Kind { let opString = char.string let operatorRole = char.role _consume(operatorRole) let operatorKind = opString.toOperator(following: prev, followed: char.role) switch (operatorRole, operatorKind) { case (.lessThan, .prefixOperator): return .leftChevron case (.greaterThan, .postfixOperator): return .rightChevron case (.amp, .prefixOperator): return .prefixAmp case (.question, .prefixOperator): return .prefixQuestion case (.question, .binaryOperator): return .binaryQuestion case (.question, .postfixOperator): return .postfixQuestion case (.exclaim, .postfixOperator): return .postfixExclaim default: return operatorKind } } func lexOperator(prev: Role, enableDotOperator: Bool = false) -> Token.Kind { var opString = "" repeat { opString.append(char.string) _consume(char.role) } while char.shouldContinue(enableDotOperator: enableDotOperator) return opString.toOperator(following: prev, followed: char.role) } } fileprivate extension Char { func shouldContinue(enableDotOperator: Bool) -> Bool { if self == .eof { return false } switch self.role { case .operatorHead, .operatorBody, .lessThan, .greaterThan, .amp, .question, .exclaim, .equal, .arrow, .minus, .singleLineCommentHead, .multipleLineCommentHead, .multipleLineCommentTail, .dotOperatorHead where enableDotOperator, .period where enableDotOperator: return true default: return false } } } fileprivate extension String { func toOperator(following head: Role, followed tail: Role) -> Token.Kind { let headSeparated = head.isHeadSeparator let tailSeparated = tail.isTailSeparator if tail == .eof && !headSeparated { return .postfixOperator(self) } else if headSeparated && !tailSeparated { return .prefixOperator(self) } else if !headSeparated && tailSeparated { return .postfixOperator(self) } else if !headSeparated && (self == "?" || self == "!") { return .postfixOperator(self) } else { return .binaryOperator(self) } } }
apache-2.0
b1e119f1c52d71711e17b541d8e7c685
31.633333
81
0.684031
4.357567
false
false
false
false
inacioferrarini/York
Classes/Extensions/UIViewExtensions.swift
1
1932
// The MIT License (MIT) // // Copyright (c) 2016 Inácio Ferrarini // // 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 public extension UIView { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } @IBInspectable var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } @IBInspectable var borderColor: UIColor? { get { if let color = layer.borderColor { return UIColor(cgColor: color) } return nil } set { layer.borderColor = newValue?.cgColor } } }
mit
d60e1d1d3972144f78a6275bdd89958b
31.728814
84
0.640083
4.815461
false
false
false
false
kean/Nuke
Sources/Nuke/Decoding/ImageDecoders+Video.swift
1
1717
// The MIT License (MIT) // // Copyright (c) 2015-2022 Alexander Grebenyuk (github.com/kean). #if !os(watchOS) import Foundation import AVKit extension ImageDecoders { public final class Video: ImageDecoding, @unchecked Sendable { private var didProducePreview = false private let type: AssetType public var isAsynchronous: Bool { true } private let lock = NSLock() public init?(context: ImageDecodingContext) { guard let type = AssetType(context.data), type.isVideo else { return nil } self.type = type } public func decode(_ data: Data) throws -> ImageContainer { ImageContainer(image: PlatformImage(), type: type, data: data) } public func decodePartiallyDownloadedData(_ data: Data) -> ImageContainer? { lock.lock() defer { lock.unlock() } guard let type = AssetType(data), type.isVideo else { return nil } guard !didProducePreview else { return nil // We only need one preview } guard let preview = makePreview(for: data, type: type) else { return nil } didProducePreview = true return ImageContainer(image: preview, type: type, isPreview: true, data: data) } } } private func makePreview(for data: Data, type: AssetType) -> PlatformImage? { let asset = AVDataAsset(data: data, type: type) let generator = AVAssetImageGenerator(asset: asset) guard let cgImage = try? generator.copyCGImage(at: CMTime(value: 0, timescale: 1), actualTime: nil) else { return nil } return PlatformImage(cgImage: cgImage) } #endif
mit
bcdd44e521e41ee3fdec5e0568ae5dee
31.396226
110
0.62085
4.542328
false
false
false
false
delba/SwiftyUserDefaults
SwiftyUserDefaults/SwiftyUserDefaults.swift
1
15869
// // SwiftyUserDefaults // // Copyright (c) 2015 Radosław Pietruszewski // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation public extension NSUserDefaults { class Proxy { private let defaults: NSUserDefaults private let key: String private init(_ defaults: NSUserDefaults, _ key: String) { self.defaults = defaults self.key = key } // MARK: Getters public var object: NSObject? { return defaults.objectForKey(key) as? NSObject } public var string: String? { return defaults.stringForKey(key) } public var array: NSArray? { return defaults.arrayForKey(key) } public var dictionary: NSDictionary? { return defaults.dictionaryForKey(key) } public var data: NSData? { return defaults.dataForKey(key) } public var date: NSDate? { return object as? NSDate } public var number: NSNumber? { return defaults.numberForKey(key) } public var int: Int? { return number?.integerValue } public var double: Double? { return number?.doubleValue } public var bool: Bool? { return number?.boolValue } // MARK: Non-Optional Getters public var stringValue: String { return string ?? "" } public var arrayValue: NSArray { return array ?? [] } public var dictionaryValue: NSDictionary { return dictionary ?? NSDictionary() } public var dataValue: NSData { return data ?? NSData() } public var numberValue: NSNumber { return number ?? 0 } public var intValue: Int { return int ?? 0 } public var doubleValue: Double { return double ?? 0 } public var boolValue: Bool { return bool ?? false } } /// `NSNumber` representation of a user default func numberForKey(key: String) -> NSNumber? { return objectForKey(key) as? NSNumber } /// Returns getter proxy for `key` public subscript(key: String) -> Proxy { return Proxy(self, key) } /// Sets value for `key` public subscript(key: String) -> Any? { get { return self[key] } set { switch newValue { case let v as Int: setInteger(v, forKey: key) case let v as Double: setDouble(v, forKey: key) case let v as Bool: setBool(v, forKey: key) case let v as NSURL: setURL(v, forKey: key) case let v as NSObject: setObject(v, forKey: key) case nil: removeObjectForKey(key) default: assertionFailure("Invalid value type") } } } /// Returns `true` if `key` exists public func hasKey(key: String) -> Bool { return objectForKey(key) != nil } /// Removes value for `key` public func remove(key: String) { removeObjectForKey(key) } } /// Global shortcut for NSUserDefaults.standardUserDefaults() public let Defaults = NSUserDefaults.standardUserDefaults() // MARK: - Static keys /// Extend this class and add your user defaults keys as static constants /// so you can use the shortcut dot notation (e.g. `Defaults[.yourKey]`) public class DefaultsKeys { private init() {} } /// Base class for static user defaults keys. Specialize with value type type /// and pass key name to the initializer to create a key. private protocol OptionalType {} extension Optional: OptionalType {} public class DefaultsKey<ValueType>: DefaultsKeys { // TODO: Can we use protocols to ensure ValueType is a compatible type? public let _key: String public let _default: ValueType? public convenience init(_ key: String) { self.init(key: key, defaultValue: nil) } public convenience init(_ key: String, _ defaultValue: ValueType) { precondition(!(defaultValue is OptionalType), "A default cannot be specified for an optional value type.") self.init(key: key, defaultValue: defaultValue) } private init(key: String, defaultValue: ValueType?) { self._key = key self._default = defaultValue } } extension NSUserDefaults { func set<T>(key: DefaultsKey<T>, _ value: Any?) { self[key._key] = value } } extension NSUserDefaults { /// Returns `true` if `key` exists public func hasKey<T>(key: DefaultsKey<T>) -> Bool { return objectForKey(key._key) != nil } /// Removes value for `key` public func remove<T>(key: DefaultsKey<T>) { removeObjectForKey(key._key) } } // MARK: Static subscripts for standard types // TODO: Use generic subscripts when they become available extension NSUserDefaults { public subscript(key: DefaultsKey<String?>) -> String? { get { return stringForKey(key._key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<String>) -> String { get { return stringForKey(key._key) ?? key._default ?? "" } set { set(key, newValue) } } public subscript(key: DefaultsKey<NSString?>) -> NSString? { get { return stringForKey(key._key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<NSString>) -> NSString { get { return stringForKey(key._key) ?? key._default ?? "" } set { set(key, newValue) } } public subscript(key: DefaultsKey<Int?>) -> Int? { get { return numberForKey(key._key)?.integerValue } set { set(key, newValue) } } public subscript(key: DefaultsKey<Int>) -> Int { get { return numberForKey(key._key)?.integerValue ?? key._default ?? 0 } set { set(key, newValue) } } public subscript(key: DefaultsKey<Double?>) -> Double? { get { return numberForKey(key._key)?.doubleValue } set { set(key, newValue) } } public subscript(key: DefaultsKey<Double>) -> Double { get { return numberForKey(key._key)?.doubleValue ?? key._default ?? 0.0 } set { set(key, newValue) } } public subscript(key: DefaultsKey<Bool?>) -> Bool? { get { return numberForKey(key._key)?.boolValue } set { set(key, newValue) } } public subscript(key: DefaultsKey<Bool>) -> Bool { get { return numberForKey(key._key)?.boolValue ?? key._default ?? false } set { set(key, newValue) } } public subscript(key: DefaultsKey<AnyObject?>) -> AnyObject? { get { return objectForKey(key._key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<NSObject?>) -> NSObject? { get { return objectForKey(key._key) as? NSObject } set { set(key, newValue) } } public subscript(key: DefaultsKey<NSData?>) -> NSData? { get { return dataForKey(key._key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<NSData>) -> NSData { get { return dataForKey(key._key) ?? key._default ?? NSData() } set { set(key, newValue) } } public subscript(key: DefaultsKey<NSDate?>) -> NSDate? { get { return objectForKey(key._key) as? NSDate } set { set(key, newValue) } } public subscript(key: DefaultsKey<NSURL?>) -> NSURL? { get { return URLForKey(key._key) } set { set(key, newValue) } } // TODO: It would probably make sense to have support for statically typed dictionaries (e.g. [String: String]) public subscript(key: DefaultsKey<[String: AnyObject]?>) -> [String: AnyObject]? { get { return dictionaryForKey(key._key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[String: AnyObject]>) -> [String: AnyObject] { get { return dictionaryForKey(key._key) ?? key._default ?? [:] } set { set(key, newValue) } } public subscript(key: DefaultsKey<NSDictionary?>) -> NSDictionary? { get { return dictionaryForKey(key._key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<NSDictionary>) -> NSDictionary { get { return dictionaryForKey(key._key) ?? key._default ?? [:] } set { set(key, newValue) } } } // MARK: Static subscripts for array types extension NSUserDefaults { public subscript(key: DefaultsKey<NSArray?>) -> NSArray? { get { return arrayForKey(key._key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<NSArray>) -> NSArray { get { return arrayForKey(key._key) ?? key._default ?? [] } set { set(key, newValue) } } public subscript(key: DefaultsKey<[AnyObject]?>) -> [AnyObject]? { get { return arrayForKey(key._key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[AnyObject]>) -> [AnyObject] { get { return arrayForKey(key._key) ?? key._default ?? [] } set { set(key, newValue) } } } // We need the <T: AnyObject> and <T: _ObjectiveCBridgeable> variants to // suppress compiler warnings about NSArray not being convertible to [T] // AnyObject is for NSData and NSDate, _ObjectiveCBridgeable is for value // types bridge-able to Foundation types (String, Int, ...) extension NSUserDefaults { public func getArray<T: _ObjectiveCBridgeable>(key: DefaultsKey<[T]>) -> [T] { return arrayForKey(key._key) as NSArray? as? [T] ?? key._default ?? [] } public func getArray<T: _ObjectiveCBridgeable>(key: DefaultsKey<[T]?>) -> [T]? { return arrayForKey(key._key) as NSArray? as? [T] } public func getArray<T: AnyObject>(key: DefaultsKey<[T]>) -> [T] { return arrayForKey(key._key) as NSArray? as? [T] ?? key._default ?? [] } public func getArray<T: AnyObject>(key: DefaultsKey<[T]?>) -> [T]? { return arrayForKey(key._key) as NSArray? as? [T] } } extension NSUserDefaults { public subscript(key: DefaultsKey<[String]?>) -> [String]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[String]>) -> [String] { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Int]?>) -> [Int]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Int]>) -> [Int] { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Double]?>) -> [Double]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Double]>) -> [Double] { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Bool]?>) -> [Bool]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Bool]>) -> [Bool] { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[NSData]?>) -> [NSData]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[NSData]>) -> [NSData] { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[NSDate]?>) -> [NSDate]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[NSDate]>) -> [NSDate] { get { return getArray(key) } set { set(key, newValue) } } } // MARK: Archiving complex types extension NSUserDefaults { // TODO: Can we simplify this and ensure that T is NSCoding compliant? public func archive<T>(key: DefaultsKey<T>, _ value: T) { if let value: AnyObject = value as? AnyObject { set(key, NSKeyedArchiver.archivedDataWithRootObject(value)) } else { assertionFailure("Invalid value type") } } public func archive<T>(key: DefaultsKey<T?>, _ value: T?) { if let value: AnyObject = value as? AnyObject { set(key, NSKeyedArchiver.archivedDataWithRootObject(value)) } else if value == nil { remove(key) } else { assertionFailure("Invalid value type") } } public func unarchive<T>(key: DefaultsKey<T?>) -> T? { return dataForKey(key._key).flatMap { NSKeyedUnarchiver.unarchiveObjectWithData($0) } as? T } public func unarchive<T>(key: DefaultsKey<T>) -> T? { return dataForKey(key._key).flatMap { NSKeyedUnarchiver.unarchiveObjectWithData($0) } as? T } } // MARK: - Deprecations infix operator ?= { associativity right precedence 90 } /// If key doesn't exist, sets its value to `expr` /// Note: This isn't the same as `Defaults.registerDefaults`. This method saves the new value to disk, whereas `registerDefaults` only modifies the defaults in memory. /// Note: If key already exists, the expression after ?= isn't evaluated @available(*, deprecated=1, message="Please migrate to static keys and use this gist: https://gist.github.com/radex/68de9340b0da61d43e60") public func ?= (proxy: NSUserDefaults.Proxy, @autoclosure expr: () -> Any) { if !proxy.defaults.hasKey(proxy.key) { proxy.defaults[proxy.key] = expr() } } /// Adds `b` to the key (and saves it as an integer) /// If key doesn't exist or isn't a number, sets value to `b` @available(*, deprecated=1, message="Please migrate to static keys to use this.") public func += (proxy: NSUserDefaults.Proxy, b: Int) { let a = proxy.defaults[proxy.key].intValue proxy.defaults[proxy.key] = a + b } @available(*, deprecated=1, message="Please migrate to static keys to use this.") public func += (proxy: NSUserDefaults.Proxy, b: Double) { let a = proxy.defaults[proxy.key].doubleValue proxy.defaults[proxy.key] = a + b } /// Icrements key by one (and saves it as an integer) /// If key doesn't exist or isn't a number, sets value to 1 @available(*, deprecated=1, message="Please migrate to static keys to use this.") public postfix func ++ (proxy: NSUserDefaults.Proxy) { proxy += 1 }
mit
e093c03096a22f2f145cc9f25bf9c719
30.423762
167
0.596294
4.396786
false
false
false
false
LeonClover/DouYu
DouYuZB/DouYuZB/Classes/Main/View/PageContentView.swift
1
4840
// // PageContentView.swift // DouYuZB // // Created by Leon on 2017/6/7. // Copyright © 2017年 pingan. All rights reserved. // import UIKit protocol PageContentViewDelegate: class { func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) } private let contentCellID = "contentCellID" class PageContentView: UIView { //定义属性 fileprivate var childVcs: [UIViewController] fileprivate weak var parentVC: UIViewController? fileprivate var startOffsetX: CGFloat = 0.0 fileprivate var isForbidScrollDelegate: Bool = false weak var delegate: PageContentViewDelegate? //懒加载属性 fileprivate lazy var collectionView: UICollectionView = {[weak self] in let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal let collectionView = UICollectionView(frame: CGRect(), collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.dataSource = self collectionView.delegate = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: contentCellID) return collectionView }() init(frame: CGRect, childVcs: [UIViewController], parentVC: UIViewController?) { self.childVcs = childVcs self.parentVC = parentVC super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //设置UI界面 extension PageContentView { fileprivate func setupUI() { for childVC in childVcs { parentVC?.addChildViewController(childVC) } collectionView.frame = bounds addSubview(collectionView) } } //实现协议 extension PageContentView: UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: contentCellID, for: indexPath) for view in cell.contentView.subviews { view.removeFromSuperview() } let childVC = childVcs[indexPath.item] childVC.view.frame = cell.contentView.bounds cell.contentView.addSubview(childVC.view) return cell } } // extension PageContentView: UICollectionViewDelegate{ func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isForbidScrollDelegate = false; startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { if isForbidScrollDelegate { return } //1.定义获取需要的数据 var progress: CGFloat = 0.0 var sourceIndex = 0 var targetIndex = 0 //2.判断左滑还是右滑 let currentOffsetX = scrollView.contentOffset.x let scrollViewW = scrollView.bounds.width if currentOffsetX > startOffsetX { //左滑 //1.计算progress progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW) //2.计算sourceIndex sourceIndex = Int(currentOffsetX / scrollViewW) //3.计算targetIndex targetIndex = sourceIndex + 1 if targetIndex >= childVcs.count { targetIndex = childVcs.count - 1 } }else{ //1.计算progress progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)) //2.计算targetIndex targetIndex = Int(currentOffsetX / scrollViewW) //3.计算sourceIndex sourceIndex = targetIndex + 1 if sourceIndex >= childVcs.count { sourceIndex = childVcs.count - 1 } } //3.将progress,sourceIndex,targetIndex,传给titleView delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } } //对外暴露的方法 extension PageContentView{ func setCurrentIndex(currentIndex: Int) { isForbidScrollDelegate = true; let offsetX = CGFloat(currentIndex) * collectionView.frame.width collectionView.setContentOffset(CGPoint(x: offsetX, y: 0.0), animated: false) } }
mit
c18720ff056fb10ebaa668249094bbb6
32.439716
124
0.656416
5.70133
false
false
false
false
rudkx/swift
SwiftCompilerSources/Sources/SIL/Instruction.swift
1
19491
//===--- Instruction.swift - Defines the Instruction classes --------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Basic import SILBridging //===----------------------------------------------------------------------===// // Instruction base classes //===----------------------------------------------------------------------===// public class Instruction : ListNode, CustomStringConvertible, Hashable { final public var next: Instruction? { SILInstruction_next(bridged).instruction } final public var previous: Instruction? { SILInstruction_previous(bridged).instruction } // Needed for ReverseList<Instruction>.reversed(). Never use directly. public var _firstInList: Instruction { SILBasicBlock_firstInst(block.bridged).instruction! } // Needed for List<Instruction>.reversed(). Never use directly. public var _lastInList: Instruction { SILBasicBlock_lastInst(block.bridged).instruction! } final public var block: BasicBlock { SILInstruction_getParent(bridged).block } final public var function: Function { block.function } final public var description: String { SILNode_debugDescription(bridgedNode).takeString() } final public var operands: OperandArray { return OperandArray(opArray: SILInstruction_getOperands(bridged)) } fileprivate var resultCount: Int { 0 } fileprivate func getResult(index: Int) -> Value { fatalError() } public struct Results : RandomAccessCollection { fileprivate let inst: Instruction fileprivate let numResults: Int public var startIndex: Int { 0 } public var endIndex: Int { numResults } public subscript(_ index: Int) -> Value { inst.getResult(index: index) } } final public var results: Results { Results(inst: self, numResults: resultCount) } final public var location: Location { return Location(bridgedLocation: SILInstruction_getLocation(bridged)) } public var mayTrap: Bool { false } final public var mayHaveSideEffects: Bool { return mayTrap || mayWriteToMemory } final public var mayReadFromMemory: Bool { switch SILInstruction_getMemBehavior(bridged) { case MayReadBehavior, MayReadWriteBehavior, MayHaveSideEffectsBehavior: return true default: return false } } final public var mayWriteToMemory: Bool { switch SILInstruction_getMemBehavior(bridged) { case MayWriteBehavior, MayReadWriteBehavior, MayHaveSideEffectsBehavior: return true default: return false } } final public var mayReadOrWriteMemory: Bool { switch SILInstruction_getMemBehavior(bridged) { case MayReadBehavior, MayWriteBehavior, MayReadWriteBehavior, MayHaveSideEffectsBehavior: return true default: return false } } public final var mayRelease: Bool { return SILInstruction_mayRelease(bridged) } public static func ==(lhs: Instruction, rhs: Instruction) -> Bool { lhs === rhs } public func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) } public var bridged: BridgedInstruction { BridgedInstruction(obj: SwiftObject(self)) } var bridgedNode: BridgedNode { BridgedNode(obj: SwiftObject(self)) } } extension BridgedInstruction { public var instruction: Instruction { obj.getAs(Instruction.self) } public func getAs<T: Instruction>(_ instType: T.Type) -> T { obj.getAs(T.self) } } extension OptionalBridgedInstruction { var instruction: Instruction? { obj.getAs(Instruction.self) } } public class SingleValueInstruction : Instruction, Value { final public var definingInstruction: Instruction? { self } fileprivate final override var resultCount: Int { 1 } fileprivate final override func getResult(index: Int) -> Value { self } } public final class MultipleValueInstructionResult : Value { final public var description: String { SILNode_debugDescription(bridgedNode).takeString() } public var instruction: Instruction { MultiValueInstResult_getParent(bridged).instruction } public var definingInstruction: Instruction? { instruction } var bridged: BridgedMultiValueResult { BridgedMultiValueResult(obj: SwiftObject(self)) } var bridgedNode: BridgedNode { BridgedNode(obj: SwiftObject(self)) } } extension BridgedMultiValueResult { var result: MultipleValueInstructionResult { obj.getAs(MultipleValueInstructionResult.self) } } public class MultipleValueInstruction : Instruction { fileprivate final override var resultCount: Int { return MultipleValueInstruction_getNumResults(bridged) } fileprivate final override func getResult(index: Int) -> Value { MultipleValueInstruction_getResult(bridged, index).result } } /// Instructions, which have a single operand. public protocol UnaryInstruction : AnyObject { var operands: OperandArray { get } var operand: Value { get } } extension UnaryInstruction { public var operand: Value { operands[0].value } } //===----------------------------------------------------------------------===// // no-value instructions //===----------------------------------------------------------------------===// /// Used for all non-value instructions which are not implemented here, yet. /// See registerBridgedClass() in SILBridgingUtils.cpp. final public class UnimplementedInstruction : Instruction { } final public class StoreInst : Instruction { public var sourceOperand: Operand { return operands[0] } public var destinationOperand: Operand { return operands[1] } public var source: Value { return sourceOperand.value } public var destination: Value { return destinationOperand.value } // must match with enum class StoreOwnershipQualifier public enum StoreOwnership: Int { case unqualified = 0, initialize = 1, assign = 2, trivial = 3 } public var destinationOwnership: StoreOwnership { StoreOwnership(rawValue: StoreInst_getStoreOwnership(bridged))! } } final public class CopyAddrInst : Instruction { public var sourceOperand: Operand { return operands[0] } public var destinationOperand: Operand { return operands[1] } public var source: Value { return sourceOperand.value } public var destination: Value { return destinationOperand.value } } final public class EndAccessInst : Instruction, UnaryInstruction { public var beginAccess: BeginAccessInst { return operand as! BeginAccessInst } } final public class EndBorrowInst : Instruction, UnaryInstruction {} final public class DeallocStackInst : Instruction, UnaryInstruction { public var allocstack: AllocStackInst { return operand as! AllocStackInst } } final public class DeallocStackRefInst : Instruction, UnaryInstruction { public var allocRef: AllocRefInstBase { operand as! AllocRefInstBase } } final public class CondFailInst : Instruction, UnaryInstruction { public override var mayTrap: Bool { true } public var message: String { CondFailInst_getMessage(bridged).string } } final public class FixLifetimeInst : Instruction, UnaryInstruction {} final public class DebugValueInst : Instruction, UnaryInstruction {} final public class UnconditionalCheckedCastAddrInst : Instruction { public override var mayTrap: Bool { true } } final public class SetDeallocatingInst : Instruction, UnaryInstruction {} final public class DeallocRefInst : Instruction, UnaryInstruction {} public class RefCountingInst : Instruction, UnaryInstruction { public var isAtomic: Bool { RefCountingInst_getIsAtomic(bridged) } } final public class StrongRetainInst : RefCountingInst { } final public class RetainValueInst : RefCountingInst { } final public class StrongReleaseInst : RefCountingInst { } final public class ReleaseValueInst : RefCountingInst { } final public class DestroyValueInst : Instruction, UnaryInstruction {} final public class DestroyAddrInst : Instruction, UnaryInstruction {} final public class UnimplementedRefCountingInst : RefCountingInst {} //===----------------------------------------------------------------------===// // single-value instructions //===----------------------------------------------------------------------===// /// Used for all SingleValueInstructions which are not implemented here, yet. /// See registerBridgedClass() in SILBridgingUtils.cpp. final public class UnimplementedSingleValueInst : SingleValueInstruction { } final public class LoadInst : SingleValueInstruction, UnaryInstruction {} final public class LoadBorrowInst : SingleValueInstruction, UnaryInstruction {} final public class BuiltinInst : SingleValueInstruction { // TODO: find a way to directly reuse the BuiltinValueKind enum public enum ID { case None case DestroyArray } public var id: ID? { switch BuiltinInst_getID(bridged) { case DestroyArrayBuiltin: return .DestroyArray default: return .None } } } final public class UpcastInst : SingleValueInstruction, UnaryInstruction {} final public class UncheckedRefCastInst : SingleValueInstruction, UnaryInstruction {} final public class RawPointerToRefInst : SingleValueInstruction, UnaryInstruction {} final public class AddressToPointerInst : SingleValueInstruction, UnaryInstruction {} final public class PointerToAddressInst : SingleValueInstruction, UnaryInstruction {} final public class IndexAddrInst : SingleValueInstruction {} final public class InitExistentialRefInst : SingleValueInstruction, UnaryInstruction {} final public class OpenExistentialRefInst : SingleValueInstruction, UnaryInstruction {} final public class InitExistentialValueInst : SingleValueInstruction, UnaryInstruction {} final public class OpenExistentialValueInst : SingleValueInstruction, UnaryInstruction {} final public class InitExistentialAddrInst : SingleValueInstruction, UnaryInstruction {} final public class OpenExistentialAddrInst : SingleValueInstruction, UnaryInstruction {} final public class OpenExistentialBoxInst : SingleValueInstruction, UnaryInstruction {} final public class OpenExistentialBoxValueInst : SingleValueInstruction, UnaryInstruction {} final public class InitExistentialMetatypeInst : SingleValueInstruction, UnaryInstruction {} final public class OpenExistentialMetatypeInst : SingleValueInstruction, UnaryInstruction {} final public class ValueMetatypeInst : SingleValueInstruction, UnaryInstruction {} final public class ExistentialMetatypeInst : SingleValueInstruction, UnaryInstruction {} public class GlobalAccessInst : SingleValueInstruction { final public var global: GlobalVariable { GlobalAccessInst_getGlobal(bridged).globalVar } } final public class FunctionRefInst : GlobalAccessInst { public var referencedFunction: Function { FunctionRefInst_getReferencedFunction(bridged).function } } final public class GlobalAddrInst : GlobalAccessInst {} final public class GlobalValueInst : GlobalAccessInst {} final public class IntegerLiteralInst : SingleValueInstruction {} final public class TupleInst : SingleValueInstruction { } final public class TupleExtractInst : SingleValueInstruction, UnaryInstruction { public var fieldIndex: Int { TupleExtractInst_fieldIndex(bridged) } } final public class TupleElementAddrInst : SingleValueInstruction, UnaryInstruction { public var fieldIndex: Int { TupleElementAddrInst_fieldIndex(bridged) } } final public class StructInst : SingleValueInstruction { } final public class StructExtractInst : SingleValueInstruction, UnaryInstruction { public var fieldIndex: Int { StructExtractInst_fieldIndex(bridged) } } final public class StructElementAddrInst : SingleValueInstruction, UnaryInstruction { public var fieldIndex: Int { StructElementAddrInst_fieldIndex(bridged) } } final public class EnumInst : SingleValueInstruction { public var caseIndex: Int { EnumInst_caseIndex(bridged) } public var operand: Value? { operands.first?.value } } final public class UncheckedEnumDataInst : SingleValueInstruction, UnaryInstruction { public var caseIndex: Int { UncheckedEnumDataInst_caseIndex(bridged) } } final public class RefElementAddrInst : SingleValueInstruction, UnaryInstruction { public var fieldIndex: Int { RefElementAddrInst_fieldIndex(bridged) } } final public class RefTailAddrInst : SingleValueInstruction, UnaryInstruction {} final public class UnconditionalCheckedCastInst : SingleValueInstruction, UnaryInstruction { public override var mayTrap: Bool { true } } final public class ConvertFunctionInst : SingleValueInstruction, UnaryInstruction {} final public class ThinToThickFunctionInst : SingleValueInstruction, UnaryInstruction {} final public class ObjCExistentialMetatypeToObjectInst : SingleValueInstruction, UnaryInstruction {} final public class ObjCMetatypeToObjectInst : SingleValueInstruction, UnaryInstruction {} final public class ValueToBridgeObjectInst : SingleValueInstruction, UnaryInstruction {} final public class MarkDependenceInst : SingleValueInstruction { public var value: Value { return operands[0].value } public var base: Value { return operands[1].value } } final public class BridgeObjectToRefInst : SingleValueInstruction, UnaryInstruction {} final public class BeginAccessInst : SingleValueInstruction, UnaryInstruction {} final public class BeginBorrowInst : SingleValueInstruction, UnaryInstruction {} final public class CopyValueInst : SingleValueInstruction, UnaryInstruction {} final public class EndCOWMutationInst : SingleValueInstruction, UnaryInstruction {} final public class ClassifyBridgeObjectInst : SingleValueInstruction, UnaryInstruction {} final public class PartialApplyInst : SingleValueInstruction, ApplySite { public var numArguments: Int { PartialApplyInst_numArguments(bridged) } } final public class ApplyInst : SingleValueInstruction, FullApplySite { public var numArguments: Int { ApplyInst_numArguments(bridged) } public var singleDirectResult: Value? { self } } final public class ClassMethodInst : SingleValueInstruction, UnaryInstruction {} final public class SuperMethodInst : SingleValueInstruction, UnaryInstruction {} final public class ObjCMethodInst : SingleValueInstruction, UnaryInstruction {} final public class ObjCSuperMethodInst : SingleValueInstruction, UnaryInstruction {} final public class WitnessMethodInst : SingleValueInstruction {} final public class IsUniqueInst : SingleValueInstruction, UnaryInstruction {} final public class IsEscapingClosureInst : SingleValueInstruction, UnaryInstruction {} //===----------------------------------------------------------------------===// // single-value allocation instructions //===----------------------------------------------------------------------===// public protocol Allocation : AnyObject { } final public class AllocStackInst : SingleValueInstruction, Allocation { } public class AllocRefInstBase : SingleValueInstruction, Allocation { final public var isObjC: Bool { AllocRefInstBase_isObjc(bridged) != 0 } final public var canAllocOnStack: Bool { AllocRefInstBase_canAllocOnStack(bridged) != 0 } } final public class AllocRefInst : AllocRefInstBase { } final public class AllocRefDynamicInst : AllocRefInstBase { } final public class AllocBoxInst : SingleValueInstruction, Allocation { } final public class AllocExistentialBoxInst : SingleValueInstruction, Allocation { } //===----------------------------------------------------------------------===// // multi-value instructions //===----------------------------------------------------------------------===// final public class BeginCOWMutationInst : MultipleValueInstruction, UnaryInstruction { public var uniquenessResult: Value { return getResult(index: 0) } public var bufferResult: Value { return getResult(index: 1) } } final public class DestructureStructInst : MultipleValueInstruction { } final public class DestructureTupleInst : MultipleValueInstruction { } final public class BeginApplyInst : MultipleValueInstruction, FullApplySite { public var numArguments: Int { BeginApplyInst_numArguments(bridged) } public var singleDirectResult: Value? { nil } } public final class RefToBridgeObjectInst: MultipleValueInstruction {} //===----------------------------------------------------------------------===// // terminator instructions //===----------------------------------------------------------------------===// public class TermInst : Instruction { final public var successors: SuccessorArray { SuccessorArray(succArray: TermInst_getSuccessors(bridged)) } } final public class UnreachableInst : TermInst { } final public class ReturnInst : TermInst, UnaryInstruction { } final public class ThrowInst : TermInst, UnaryInstruction { } final public class YieldInst : TermInst { } final public class UnwindInst : TermInst { } final public class TryApplyInst : TermInst, FullApplySite { public var numArguments: Int { TryApplyInst_numArguments(bridged) } public var normalBlock: BasicBlock { successors[0] } public var errorBlock: BasicBlock { successors[1] } public var singleDirectResult: Value? { normalBlock.arguments[0] } } final public class BranchInst : TermInst { public var targetBlock: BasicBlock { BranchInst_getTargetBlock(bridged).block } public func getArgument(for operand: Operand) -> Argument { return targetBlock.arguments[operand.index] } } final public class CondBranchInst : TermInst { } final public class SwitchValueInst : TermInst { } final public class SwitchEnumInst : TermInst { public var enumOp: Value { operands[0].value } public struct CaseIndexArray : RandomAccessCollection { fileprivate let switchEnum: SwitchEnumInst public var startIndex: Int { return 0 } public var endIndex: Int { SwitchEnumInst_getNumCases(switchEnum.bridged) } public subscript(_ index: Int) -> Int { SwitchEnumInst_getCaseIndex(switchEnum.bridged, index) } } var caseIndices: CaseIndexArray { CaseIndexArray(switchEnum: self) } var cases: Zip2Sequence<CaseIndexArray, SuccessorArray> { zip(caseIndices, successors) } // This does not handle the special case where the default covers exactly // the "missing" case. public func getUniqueSuccessor(forCaseIndex: Int) -> BasicBlock? { cases.first(where: { $0.0 == forCaseIndex })?.1 } // This does not handle the special case where the default covers exactly // the "missing" case. public func getUniqueCase(forSuccessor: BasicBlock) -> Int? { cases.first(where: { $0.1 == forSuccessor })?.0 } } final public class SwitchEnumAddrInst : TermInst { } final public class DynamicMethodBranchInst : TermInst { } final public class AwaitAsyncContinuationInst : TermInst, UnaryInstruction { } final public class CheckedCastBranchInst : TermInst, UnaryInstruction { } final public class CheckedCastAddrBranchInst : TermInst, UnaryInstruction { }
apache-2.0
28daf8304e416638c9734a19725c353f
30.437097
94
0.724591
4.909572
false
false
false
false
lyft/SwiftLint
Source/SwiftLintFramework/Rules/PrivateOverFilePrivateRule.swift
1
3742
import Foundation import SourceKittenFramework public struct PrivateOverFilePrivateRule: Rule, ConfigurationProviderRule, CorrectableRule { public var configuration = PrivateOverFilePrivateRuleConfiguration() public init() {} public static let description = RuleDescription( identifier: "private_over_fileprivate", name: "Private over fileprivate", description: "Prefer `private` over `fileprivate` declarations.", kind: .idiomatic, nonTriggeringExamples: [ "extension String {}", "private extension String {}", "public \n enum MyEnum {}", "open extension \n String {}", "internal extension String {}", "extension String {\nfileprivate func Something(){}\n}", "class MyClass {\nfileprivate let myInt = 4\n}", "class MyClass {\nfileprivate(set) var myInt = 4\n}", "struct Outter {\nstruct Inter {\nfileprivate struct Inner {}\n}\n}" ], triggeringExamples: [ "↓fileprivate enum MyEnum {}", "↓fileprivate class MyClass {\nfileprivate(set) var myInt = 4\n}" ], corrections: [ "↓fileprivate enum MyEnum {}": "private enum MyEnum {}", "↓fileprivate class MyClass {\nfileprivate(set) var myInt = 4\n}": "private class MyClass {\nfileprivate(set) var myInt = 4\n}" ] ) public func validate(file: File) -> [StyleViolation] { return violationRanges(in: file).map { StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severityConfiguration.severity, location: Location(file: file, characterOffset: $0.location)) } } private func violationRanges(in file: File) -> [NSRange] { let syntaxTokens = file.syntaxMap.tokens let contents = file.contents.bridge() return file.structure.dictionary.substructure.compactMap { dictionary -> NSRange? in guard let offset = dictionary.offset else { return nil } if !configuration.validateExtensions && dictionary.kind.flatMap(SwiftDeclarationKind.init) == .extension { return nil } let parts = syntaxTokens.prefix { offset > $0.offset } guard let lastKind = parts.last, SyntaxKind(rawValue: lastKind.type) == .attributeBuiltin, let aclName = contents.substringWithByteRange(start: lastKind.offset, length: lastKind.length), AccessControlLevel(description: aclName) == .fileprivate, let range = contents.byteRangeToNSRange(start: lastKind.offset, length: lastKind.length) else { return nil } return range } } public func correct(file: File) -> [Correction] { let violatingRanges = file.ruleEnabled(violatingRanges: violationRanges(in: file), for: self) var correctedContents = file.contents var adjustedLocations = [Int]() for violatingRange in violatingRanges.reversed() { if let indexRange = correctedContents.nsrangeToIndexRange(violatingRange) { correctedContents = correctedContents.replacingCharacters(in: indexRange, with: "private") adjustedLocations.insert(violatingRange.location, at: 0) } } file.write(correctedContents) return adjustedLocations.map { Correction(ruleDescription: type(of: self).description, location: Location(file: file, characterOffset: $0)) } } }
mit
070b8e7dbd4bbab0b5675d208a13c5f8
40.488889
111
0.607124
5.157459
false
true
false
false
abernerus/TTRTool
TTRTool/src/Edge.swift
1
825
// // Created by Andreas Bernerus on 14/09/15. // Copyright (c) 2015 chillturtle. All rights reserved. // import Foundation class Edge : Hashable { var id:String var source:Vertex var destination:Vertex var weight = 0 init(id:String, source: Vertex, destination:Vertex, weight:Int) { self.id = id self.source = source self.destination = destination self.weight = weight } func toString() -> String { return source.key + " " + destination.key } var hashValue: Int { return self.id.hashValue } } func ==(lhs: Edge, rhs: Edge) -> Bool { let stationsEquals = (lhs.source == rhs.source && lhs.destination == rhs.destination) || (lhs.source == rhs.destination && lhs.destination == rhs.source) return stationsEquals }
gpl-2.0
9f600561f28136699b914b4e091d8d71
24.030303
157
0.621818
3.966346
false
false
false
false
TENDIGI/Obsidian-UI-iOS
src/UIViewExtensions.swift
1
2614
// // UIViewExtensions.swift // Alfredo // // Created by Nick Lee on 8/10/15. // Copyright (c) 2015 TENDIGI, LLC. All rights reserved. // import UIKit public extension UIView { // MARK: Applying Borders /** Applies a border to the receiver's unerlying CALayer - parameter width: The width of the border - parameter color: The color of the border */ public func applyBorder(_ width: CGFloat, color: UIColor) { layer.borderColor = color.cgColor layer.borderWidth = width } /// Removes the border from the receiver's underlying CALayer public func removeBorder() { layer.borderColor = UIColor.clear.cgColor layer.borderWidth = 0.0 } // MARK: Rounding Corners /// Makes the view circular by setting the underlying's CALayer's cornerRadius and masking properties public func makeCircular() { let w = round((width + height) / 2.0) let radius = round(w / 2.0) roundCorners(radius) } /** Rounds the corners of the view's underlying CALayer - parameter radius: The value to use for the underlying CALayer's cornerRadius property - parameter mask: Whether or not the underlying layer should mask to its bounds */ public func roundCorners(_ radius: CGFloat, mask: Bool = true) { layer.cornerRadius = radius layer.masksToBounds = mask } // MARK: Geometry /// The x position of the view's frame public var x: CGFloat { get { return frame.origin.x } set { frame.origin.x = newValue } } /// The y position of the view's frame public var y: CGFloat { get { return frame.origin.y } set { frame.origin.y = newValue } } /// The width of the view's frame public var width: CGFloat { get { return frame.size.width } set { frame.size.width = newValue } } /// The height position of the view's frame public var height: CGFloat { get { return frame.size.height } set { frame.size.height = newValue } } // MARK: Search /// Returns a superview (by walking up the chain) of type klass public func findSuperview<T: UIView>(_ klass: UIView.Type) -> T? { if let s = superview { if s.isKind(of: klass) { return s as? T } else { return s.findSuperview(klass) } } return nil } }
mit
22c25cc93fc17f010117a4cbc86ec821
22.763636
105
0.569625
4.506897
false
false
false
false
blokadaorg/blokada
ios/App/Repository/ProcessingRepo.swift
1
2807
// // This file is part of Blokada. // // 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 https://mozilla.org/MPL/2.0/. // // Copyright © 2021 Blocka AB. All rights reserved. // // @author Karol Gusak // import Foundation import Combine // This repo is used by all other repos to report their processing state globally. class ProcessingRepo: Startable { var errorsHot: AnyPublisher<ComponentError, Never> { self.writeError.compactMap { $0 }.eraseToAnyPublisher() } var ongoingHot: AnyPublisher<ComponentOngoing, Never> { self.writeOngoing.compactMap { $0 }.eraseToAnyPublisher() } var currentlyOngoingHot: AnyPublisher<[ComponentOngoing], Never> { self.ongoingHot.scan([]) { acc, it in if it.ongoing && !acc.contains(where: { $0.component == it.component }) { return acc + [it] } else if !it.ongoing && acc.contains(where: { $0.component == it.component }) { return acc.filter { $0.component != it.component } } else { return acc } } .removeDuplicates() .eraseToAnyPublisher() } fileprivate let writeError = CurrentValueSubject<ComponentError?, Never>(nil) fileprivate let writeOngoing = CurrentValueSubject<ComponentOngoing?, Never>(nil) // Subscribers with lifetime same as the repository private var cancellables = Set<AnyCancellable>() func start() { } func notify(_ component: Any, _ error: Error, major: Bool) { writeError.send(ComponentError( component: String(describing: component), error: error, major: major )) notify(component, ongoing: false) } func notify(_ component: Any, ongoing: Bool) { writeOngoing.send(ComponentOngoing( component: String(describing: component), ongoing: ongoing )) } } class DebugProcessingRepo: ProcessingRepo { private let log = Logger("Processing") private var cancellables = Set<AnyCancellable>() override func start() { super.start() errorsHot.sink( onValue: { it in if it.major { self.log.e("Major error: \(it.component): \(it.error)") } else { self.log.w("Error: \(it.component): \(it.error)") } } ) .store(in: &cancellables) currentlyOngoingHot.sink( onValue: { it in self.log.v("\(it)") } ) .store(in: &cancellables) } func injectOngoing(_ ongoing: ComponentOngoing) { writeOngoing.send(ongoing) } }
mpl-2.0
4bf41f986533026e6a45c6cf8c79fc7c
27.927835
92
0.59444
4.357143
false
false
false
false
mcudich/TemplateKit
Source/Utilities/AsyncQueue.swift
1
1343
// // SerialOperationQueue.swift // TemplateKit // // Created by Matias Cudich on 8/29/16. // Copyright © 2016 Matias Cudich. All rights reserved. // import Foundation typealias Task = (@escaping () -> Void) -> Void class AsyncOperation: Operation { var task: Task? override var isAsynchronous: Bool { return false } override var isExecuting: Bool { return _executing } required override init() {} private var _executing = false { willSet { willChangeValue(forKey: "isExecuting") } didSet { didChangeValue(forKey: "isExecuting") } } override var isFinished: Bool { return _finished } private var _finished = false { willSet { willChangeValue(forKey: "isFinished") } didSet { didChangeValue(forKey: "isFinished") } } override func start() { _executing = true task? { self.complete() } } func complete() { _executing = false _finished = true } } class AsyncQueue<OperationType: AsyncOperation>: OperationQueue { init(maxConcurrentOperationCount: Int) { super.init() self.maxConcurrentOperationCount = maxConcurrentOperationCount } func enqueueOperation(withBlock block: @escaping Task) { let operation = OperationType() operation.task = block addOperation(operation) } }
mit
fa658d56968ce7ec315bc9496dc7c1ee
17.135135
66
0.654247
4.443709
false
false
false
false
ibari/ios-twitter
Twitter/ComposeViewController.swift
1
2417
// // ComposeViewController.swift // Twitter // // Created by Ian on 5/24/15. // Copyright (c) 2015 Ian Bari. All rights reserved. // import UIKit class ComposeViewController: UIViewController { @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var screenNameLabel: UILabel! @IBOutlet weak var tweetTextView: UITextView! @IBOutlet weak var tweetButton: UIButton! override func viewDidLoad() { super.viewDidLoad() profileImageView.setImageWithURL(User.currentUser!.profileImageURL!) nameLabel.text = User.currentUser!.name screenNameLabel.text = "@\(User.currentUser!.screenName!)" profileImageView.layer.cornerRadius = 5 profileImageView.clipsToBounds = true tweetTextView.layer.cornerRadius = 3 tweetTextView.clipsToBounds = true tweetButton.layer.cornerRadius = 3 tweetButton.clipsToBounds = true nameLabel.preferredMaxLayoutWidth = nameLabel.frame.size.width screenNameLabel.preferredMaxLayoutWidth = screenNameLabel.frame.size.width tweetTextView.delegate = self let tapRecognizer = UITapGestureRecognizer() tapRecognizer.addTarget(self, action: "didTapView") self.view.addGestureRecognizer(tapRecognizer) tweetButton.addTarget(self, action: "onTweet", forControlEvents: UIControlEvents.TouchUpInside) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func onCancel(sender: AnyObject) { self.navigationController?.popViewControllerAnimated(true) } func onTweet() { TwitterClient.sharedInstance.updateWithParams(["status" : tweetTextView.text], completion: { (status, error) -> () in self.tweetTextView.resignFirstResponder() var menuViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("MenuViewController") as! MenuViewController self.navigationController?.pushViewController(menuViewController, animated: true) }) } func didTapView(){ self.view.endEditing(true) } } extension ComposeViewController: UITextViewDelegate { func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { if text == "\n" { self.tweetTextView.resignFirstResponder() return false } return true } }
gpl-2.0
977cd3261a90b295b1b29f133b98e6a5
29.594937
155
0.730244
5.359202
false
false
false
false
mapsme/omim
iphone/Maps/UI/Search/Filters/FilterPriceCategoryCell.swift
5
818
@objc(MWMFilterPriceCategoryCell) final class FilterPriceCategoryCell: MWMTableViewCell { @IBOutlet private var priceButtons: [UIButton]! @IBOutlet weak var one: UIButton! @IBOutlet weak var two: UIButton! @IBOutlet weak var three: UIButton! @IBAction private func tap(sender: UIButton!) { sender.isSelected = !sender.isSelected let priceCategory: String switch sender { case one: priceCategory = kStat1 case two: priceCategory = kStat2 case three: priceCategory = kStat3 default: priceCategory = "" assert(false) } Statistics.logEvent(kStatSearchFilterClick, withParameters: [ kStatCategory: kStatHotel, kStatPriceCategory: priceCategory, ]) } override func awakeFromNib() { super.awakeFromNib() isSeparatorHidden = true } }
apache-2.0
c5f8d6ef6c43f188cac511d90b90fffc
25.387097
65
0.709046
4.519337
false
false
false
false
stevehe-campray/BSBDJ
BSBDJ/BSBDJ/FriendTrends(关注)/Views/BSBRecommendUserCell.swift
1
1511
// // BSBRecommendUserCell.swift // BSBDJ // // Created by hejingjin on 16/3/17. // Copyright © 2016年 baisibudejie. All rights reserved. // import UIKit class BSBRecommendUserCell: UITableViewCell { @IBOutlet weak var lineview: UIView! @IBOutlet weak var guanzhuButton: UIButton! @IBOutlet weak var fansLabel: UILabel! @IBOutlet weak var usericonimageview: UIImageView! @IBOutlet weak var usernameLabel: UILabel! var recommenduser : BSBRecommendUser?{ didSet{ self.lineview.backgroundColor = UIColor(red: 229/255.0, green: 229/255.0, blue: 229/255.0, alpha: 0.8) let str : String = String(recommenduser!.fans_count) self.fansLabel.text = str+"关注你" self.usernameLabel.text = recommenduser?.screen_name self.usericonimageview.layer.cornerRadius = 19.0 self.usericonimageview.sd_setImageWithURL(NSURL(string:(recommenduser?.header)!)) } } override func awakeFromNib() { super.awakeFromNib() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } class func cellWithTableview(tableview:UITableView) -> BSBRecommendUserCell{ let ID = "RecommendUser" let cell : BSBRecommendUserCell = tableview.dequeueReusableCellWithIdentifier(ID) as! BSBRecommendUserCell return cell } }
mit
f6d5a2b3e7384e141734f349cc49d673
30.291667
114
0.666445
4.353623
false
false
false
false
andrewarrow/boring_company_chat
chat4work/Channel.swift
1
1045
import Foundation import ObjectMapper import RealmSwift class ChannelObject: Object { dynamic var team = "" dynamic var name = "" dynamic var id = "" dynamic var pkey = "" dynamic var flavor = "" dynamic var ts = Double(0.0) dynamic var possibly_new = 0 dynamic var mute = 0 override class func primaryKey() -> String? { return "pkey" } } struct Channels: Mappable { var results: Array<Channel>? init?(map: Map) { } mutating func mapping(map: Map) { results <- map["channels"] } } struct Channel: Mappable, Equatable { var id: String? var name: String? var creator: String? var num_members: Int? var created: Int64? init?(map: Map) { } mutating func mapping(map: Map) { id <- map["id"] name <- map["name"] creator <- map["creator"] num_members <- map["num_members"] created <- map["created"] } func briefDescription() -> String { return name! } static func ==(lhs: Channel, rhs: Channel) -> Bool { return lhs.id == rhs.id } }
mit
f5ea1dedca0e5ca5fda6598aca2cd0e6
17.333333
63
0.610526
3.69258
false
false
false
false