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
Ryan-Vanderhoef/Antlers
AppIdea/Frameworks/Bond/Bond/Bond+UITextView.swift
1
4547
// // Bond+UITextView.swift // Bond // // The MIT License (MIT) // // Copyright (c) 2015 Srdan Rasic (@srdanrasic) // // 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 private var textDynamicHandleUITextView: UInt8 = 0; private var attributedTextDynamicHandleUITextView: UInt8 = 0; extension UITextView: Bondable { public var dynText: Dynamic<String> { if let d: AnyObject = objc_getAssociatedObject(self, &textDynamicHandleUITextView) { return (d as? Dynamic<String>)! } else { let d: InternalDynamic<String> = dynamicObservableFor(UITextViewTextDidChangeNotification, object: self) { notification -> String in if let textView = notification.object as? UITextView { return textView.text ?? "" } else { return "" } } let bond = Bond<String>() { [weak self] v in if let s = self { s.text = v } } d.bindTo(bond, fire: false, strongly: false) d.retain(bond) objc_setAssociatedObject(self, &textDynamicHandleUITextView, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) return d } } public var dynAttributedText: Dynamic<NSAttributedString> { if let d: AnyObject = objc_getAssociatedObject(self, &attributedTextDynamicHandleUITextView) { return (d as? Dynamic<NSAttributedString>)! } else { let d: InternalDynamic<NSAttributedString> = dynamicObservableFor(UITextViewTextDidChangeNotification, object: self) { notification -> NSAttributedString in if let textView = notification.object as? UITextView { return textView.attributedText ?? NSAttributedString(string: "") } else { return NSAttributedString(string: "") } } let bond = Bond<NSAttributedString>() { [weak self] v in if let s = self { s.attributedText = v } } d.bindTo(bond, fire: false, strongly: false) d.retain(bond) objc_setAssociatedObject(self, &attributedTextDynamicHandleUITextView, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) return d } } public var designatedDynamic: Dynamic<String> { return self.dynText } public var designatedBond: Bond<String> { return self.dynText.valueBond } } public func ->> (left: UITextView, right: Bond<String>) { left.designatedDynamic ->> right } public func ->> <U: Bondable where U.BondType == String>(left: UITextView, right: U) { left.designatedDynamic ->> right.designatedBond } public func ->> (left: UITextView, right: UITextView) { left.designatedDynamic ->> right.designatedBond } public func ->> (left: UITextView, right: UILabel) { left.designatedDynamic ->> right.designatedBond } public func ->> (left: UITextView, right: UITextField) { left.designatedDynamic ->> right.designatedBond } public func ->> <T: Dynamical where T.DynamicType == String>(left: T, right: UITextView) { left.designatedDynamic ->> right.designatedBond } public func ->> (left: Dynamic<String>, right: UITextView) { left ->> right.designatedBond } public func <->> (left: UITextView, right: UITextView) { left.designatedDynamic <->> right.designatedDynamic } public func <->> (left: Dynamic<String>, right: UITextView) { left <->> right.designatedDynamic } public func <->> (left: UITextView, right: Dynamic<String>) { left.designatedDynamic <->> right } public func <->> (left: UITextView, right: UITextField) { left.designatedDynamic <->> right.designatedDynamic }
mit
ef5ba535eaa6af10e5ba489434d0f524
34.523438
138
0.700682
4.393237
false
false
false
false
jamy0801/LGWeChatKit
LGWeChatKit/LGChatKit/Extension/LGColorEx.swift
1
2314
// // LGColorEx.swift // LGChatViewController // // Created by gujianming on 15/10/8. // Copyright © 2015年 jamy. All rights reserved. // import UIKit extension UIColor { convenience init?(hexString: String) { self.init(hexString: hexString, alpha: 1.0) } convenience init?(hexString: String, alpha: Float) { var hex = hexString if hex.hasPrefix("#") { hex = hex.substringFromIndex(hex.startIndex.advancedBy(1)) } if let _ = hex.rangeOfString("(^[0-9A-Fa-f]{6}$)|(^[0-9A-Fa-f]{3}$)", options: .RegularExpressionSearch) { if hex.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 3 { let redHex = hex.substringToIndex(hex.startIndex.advancedBy(1)) let greenHex = hex.substringWithRange(Range<String.Index>(start: hex.startIndex.advancedBy(1), end: hex.startIndex.advancedBy(2))) let blueHex = hex.substringFromIndex(hex.startIndex.advancedBy(2)) hex = redHex + redHex + greenHex + greenHex + blueHex + blueHex } let redHex = hex.substringToIndex(hex.startIndex.advancedBy(2)) let greenHex = hex.substringWithRange(Range<String.Index>(start: hex.startIndex.advancedBy(2), end: hex.startIndex.advancedBy(4))) let blueHex = hex.substringWithRange(Range<String.Index>(start: hex.startIndex.advancedBy(4), end: hex.startIndex.advancedBy(6))) var redInt: CUnsignedInt = 0 var greenInt: CUnsignedInt = 0 var blueInt: CUnsignedInt = 0 NSScanner(string: redHex).scanHexInt(&redInt) NSScanner(string: greenHex).scanHexInt(&greenInt) NSScanner(string: blueHex).scanHexInt(&blueInt) self.init(red: CGFloat(redInt) / 255.0, green: CGFloat(greenInt) / 255.0, blue: CGFloat(blueInt) / 255.0, alpha: CGFloat(alpha)) } else { self.init() return nil } } convenience init?(hex: Int) { self.init(hex: hex, alpha: 1.0) } convenience init?(hex: Int, alpha: Float) { let hexString = NSString(format: "%2X", hex) self.init(hexString: hexString as String, alpha: alpha) } }
mit
3624dd30072d1bc9d7a7a11181991e70
36.274194
146
0.597144
4.28757
false
false
false
false
austinzheng/swift
test/stdlib/POSIX.swift
2
6749
// RUN: %target-run-simple-swift %t // REQUIRES: executable_test import StdlibUnittest #if os(Linux) || os(Android) import Glibc #else import Darwin #endif chdir(CommandLine.arguments[1]) var POSIXTests = TestSuite("POSIXTests") let semaphoreName = "TestSem" #if os(Android) // In Android, the cwd is the root directory, which is not writable. let fn: String = { let capacity = Int(PATH_MAX) let resolvedPath = UnsafeMutablePointer<Int8>.allocate(capacity: capacity) resolvedPath.initialize(repeating: 0, count: capacity) defer { resolvedPath.deinitialize(count: capacity) resolvedPath.deallocate() } guard let _ = realpath("/proc/self/exe", resolvedPath) else { fatalError("Couldn't obtain executable path") } let length = strlen(resolvedPath) precondition(length != 0, "Couldn't obtain valid executable path") // Search backwards for the last /, and turn it into a null byte. for idx in stride(from: length-1, through: 0, by: -1) { if Unicode.Scalar(UInt8(resolvedPath[idx])) == Unicode.Scalar("/") { resolvedPath[idx] = 0 break } precondition(idx != 0, "Couldn't obtain valid executable directory") } return String(cString: resolvedPath) + "/test.txt" }() #else let fn = "test.txt" #endif POSIXTests.setUp { sem_unlink(semaphoreName) unlink(fn) } // Failed semaphore creation. #if !os(Android) // Android doesn’t implement sem_open and always return ENOSYS POSIXTests.test("sem_open fail") { let sem = sem_open(semaphoreName, 0) expectEqual(SEM_FAILED, sem) expectEqual(ENOENT, errno) } #endif // Successful semaphore creation. #if !os(Android) // Android doesn’t implement sem_open and always return ENOSYS POSIXTests.test("sem_open success") { let sem = sem_open(semaphoreName, O_CREAT, 0o777, 1) expectNotEqual(SEM_FAILED, sem) let res = sem_close(sem) expectEqual(0, res) let res2 = sem_unlink(semaphoreName) expectEqual(0, res2) } #endif // Successful semaphore creation with O_EXCL. #if !os(Android) // Android doesn’t implement sem_open and always return ENOSYS POSIXTests.test("sem_open O_EXCL success") { let sem = sem_open(semaphoreName, O_CREAT | O_EXCL, 0o777, 1) expectNotEqual(SEM_FAILED, sem) let res = sem_close(sem) expectEqual(0, res) let res2 = sem_unlink(semaphoreName) expectEqual(0, res2) } #endif // Successful creation and re-obtaining of existing semaphore. #if !os(Android) // Android doesn’t implement sem_open and always return ENOSYS POSIXTests.test("sem_open existing") { let sem = sem_open(semaphoreName, O_CREAT, 0o777, 1) expectNotEqual(SEM_FAILED, sem) let sem2 = sem_open(semaphoreName, 0) // Here, we'd like to test that the semaphores are the same, but it's quite // difficult. expectNotEqual(SEM_FAILED, sem2) let res = sem_close(sem) expectEqual(0, res) let res2 = sem_unlink(semaphoreName) expectEqual(0, res2) } #endif // Fail because the semaphore already exists. #if !os(Android) // Android doesn’t implement sem_open and always return ENOSYS POSIXTests.test("sem_open existing O_EXCL fail") { let sem = sem_open(semaphoreName, O_CREAT, 0o777, 1) expectNotEqual(SEM_FAILED, sem) let sem2 = sem_open(semaphoreName, O_CREAT | O_EXCL, 0o777, 1) expectEqual(SEM_FAILED, sem2) expectEqual(EEXIST, errno) let res = sem_close(sem) expectEqual(0, res) let res2 = sem_unlink(semaphoreName) expectEqual(0, res2) } #endif // Fail because the file descriptor is invalid. POSIXTests.test("ioctl(CInt, UInt, CInt): fail") { let fd = open(fn, 0) expectEqual(-1, fd) expectEqual(ENOENT, errno) // A simple check to verify that ioctl is available let _ = ioctl(fd, 0, 0) expectEqual(EBADF, errno) } #if os(Linux) || os(Android) // Successful creation of a socket and listing interfaces POSIXTests.test("ioctl(CInt, UInt, UnsafeMutableRawPointer): listing interfaces success") { // Create a socket let sock = socket(PF_INET, 1, 0) expectGT(Int(sock), 0) // List interfaces var ic = ifconf() let io = ioctl(sock, UInt(SIOCGIFCONF), &ic); expectGE(io, 0) //Cleanup let res = close(sock) expectEqual(0, res) } #endif // Fail because file doesn't exist. POSIXTests.test("fcntl(CInt, CInt): fail") { let fd = open(fn, 0) expectEqual(-1, fd) expectEqual(ENOENT, errno) let _ = fcntl(fd, F_GETFL) expectEqual(EBADF, errno) } // Change modes on existing file. POSIXTests.test("fcntl(CInt, CInt): F_GETFL/F_SETFL success with file") { // Create and open file. let fd = open(fn, O_CREAT, 0o666) expectGT(Int(fd), 0) var flags = fcntl(fd, F_GETFL) expectGE(Int(flags), 0) // Change to APPEND mode... var rc = fcntl(fd, F_SETFL, O_APPEND) expectEqual(0, rc) flags = fcntl(fd, F_GETFL) expectEqual(flags | O_APPEND, flags) // Change back... rc = fcntl(fd, F_SETFL, 0) expectEqual(0, rc) flags = fcntl(fd, F_GETFL) expectGE(Int(flags), 0) // Clean up... rc = close(fd) expectEqual(0, rc) rc = unlink(fn) expectEqual(0, rc) } POSIXTests.test("fcntl(CInt, CInt, CInt): block and unblocking sockets success") { // Create socket, note: socket created by default in blocking mode... let sock = socket(PF_INET, 1, 0) expectGT(Int(sock), 0) var flags = fcntl(sock, F_GETFL) expectGE(Int(flags), 0) // Change mode of socket to non-blocking... var rc = fcntl(sock, F_SETFL, flags | O_NONBLOCK) expectEqual(0, rc) flags = fcntl(sock, F_GETFL) expectEqual((flags | O_NONBLOCK), flags) // Change back to blocking... rc = fcntl(sock, F_SETFL, flags & ~O_NONBLOCK) expectEqual(0, rc) flags = fcntl(sock, F_GETFL) expectGE(Int(flags), 0) // Clean up... rc = close(sock) expectEqual(0, rc) } POSIXTests.test("fcntl(CInt, CInt, UnsafeMutableRawPointer): locking and unlocking success") { // Create the file and add data to it... var fd = open(fn, O_CREAT | O_WRONLY, 0o666) expectGT(Int(fd), 0) let data = "Testing 1 2 3" let bytesWritten = write(fd, data, data.utf8.count) expectEqual(data.utf8.count, bytesWritten) var rc = close(fd) expectEqual(0, rc) // Re-open the file... fd = open(fn, 0) expectGT(Int(fd), 0) // Lock for reading... var flck = flock() flck.l_type = Int16(F_RDLCK) #if os(Android) // In Android l_len is __kernel_off_t which is not the same size as off_t in // 64 bits. flck.l_len = __kernel_off_t(data.utf8.count) #else flck.l_len = off_t(data.utf8.count) #endif rc = fcntl(fd, F_SETLK, &flck) expectEqual(0, rc) // Unlock for reading... flck = flock() flck.l_type = Int16(F_UNLCK) rc = fcntl(fd, F_SETLK, &flck) expectEqual(0, rc) // Clean up... rc = close(fd) expectEqual(0, rc) rc = unlink(fn) expectEqual(0, rc) } runAllTests()
apache-2.0
d6522272699a91d6398dd8c285acf445
24.145522
94
0.68022
3.274538
false
true
false
false
ios-plugin/uexChart
EUExChart/EUExChart/BarChart.swift
1
3759
// // BarChart.swift // EUExChart // // Created by CeriNo on 2016/11/2. // Copyright © 2016年 AppCan. All rights reserved. // import Foundation import AppCanKit import AppCanKitSwift import Charts class BarChart{ struct Entity: JSArgumentConvertible { var barName: String! var barColor: UIColor! var data: [BarLineDataEntryGenerator.Unit] = [] static func jsa_fromJSArgument(_ argument: JSArgument) -> Entity? { var entity = Entity() guard entity.barName <~ argument["barName"], entity.barColor <~ argument["barColor"], entity.data <~ argument["data"] else{ return nil } return entity } } let view = BarChartView() var eventHandler: ChartEvent.Handler? var id: String! var isScrollWithWeb = false var duration: TimeInterval! var formatData: FormatData! required init?(jsConfig: JSArgument){ guard self.initialize(jsConfig: jsConfig) else{ return nil } view.delegate = self view.highlightPerTapEnabled = true view.highlightPerDragEnabled = true configureFrame(jsConfig: jsConfig) configureLegend(jsConfig: jsConfig) configureDescription(jsConfig: jsConfig) configureBackgroundColor(jsConfig: jsConfig) configureBorder(jsConfig: jsConfig) configureChartData(jsConfig: jsConfig) configureOptions(jsConfig: jsConfig) } } extension BarChart: BarLineChart{ var barLineChartView: BarLineChartViewBase{ get{ return view } } } extension BarChart{ func configureChartData(jsConfig: JSArgument) { var dataSets = [BarChartDataSet]() let entryGenerator = BarLineDataEntryGenerator(jsConfig: jsConfig) guard let entities: [Entity] = ~jsConfig["bars"] ,entities.count > 0 else{ return } var maxXCount = 0 for entity in entities{ let values = entryGenerator.generate(fromUnits: entity.data).map{BarChartDataEntry(x: $0.x,y: $0.y)} maxXCount = max(maxXCount, values.count) let dataSet = BarChartDataSet(values: values, label: entity.barName) dataSet.setColor(entity.barColor) dataSets.append(dataSet) } let data = BarChartData(dataSets: dataSets) let count = Double(dataSets.count) if count > 1{ //group bars let groupSpace = 0.08 let barSpace = (1 - groupSpace) / count * 0.2 let barWidth = (1 - groupSpace) / count * 0.8 data.barWidth = barWidth; data.groupBars(fromX: 0, groupSpace: groupSpace, barSpace: barSpace) view.xAxis.axisMinimum = 0 view.xAxis.axisMaximum = 0 + data.groupWidth(groupSpace: groupSpace, barSpace: barSpace) * Double(maxXCount) view.xAxis.centerAxisLabelsEnabled = true }else{ view.xAxis.drawGridLinesEnabled = false } data.setValueFont(formatData.valueFont) data.setValueTextColor(formatData.valueTextColor) data.highlightEnabled = true view.data = data view.xAxis.setLabelCount(maxXCount, force: false) view.xAxis.valueFormatter = entryGenerator.valueFormatter() } } extension BarChart: ChartViewDelegate{ func chartValueSelected(_ chartView: Charts.ChartViewBase, entry: Charts.ChartDataEntry, highlight: Charts.Highlight){ self.eventHandler?(ChartEvent.selected(entry: entry, highlight: highlight)) } }
lgpl-3.0
65b27397e2932f82067b9e5344536b4a
29.290323
122
0.611022
4.736444
false
true
false
false
petester42/SwiftCharts
Examples/Examples/Examples/MultipleLabelsExample.swift
4
3522
// // MultipleLabelsExample.swift // SwiftCharts // // Created by ischuetz on 04/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit class MultipleLabelsExample: UIViewController { private var chart: Chart? // arc override func viewDidLoad() { super.viewDidLoad() let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont) let cp1 = ChartPoint(x: MyMultiLabelAxisValue(myVal: 2), y: ChartAxisValueFloat(2)) let cp2 = ChartPoint(x: MyMultiLabelAxisValue(myVal: 4), y: ChartAxisValueFloat(6)) let cp3 = ChartPoint(x: MyMultiLabelAxisValue(myVal: 5), y: ChartAxisValueFloat(12)) let cp4 = ChartPoint(x: MyMultiLabelAxisValue(myVal: 8), y: ChartAxisValueFloat(4)) let chartPoints = [cp1, cp2, cp3, cp4] let xValues = chartPoints.map{$0.x} let yValues = ChartAxisValuesGenerator.generateYAxisValuesWithChartPoints(chartPoints, minSegmentCount: 10, maxSegmentCount: 20, multiple: 2, axisValueGenerator: {ChartAxisValueFloat($0, labelSettings: labelSettings)}, addPaddingSegmentIfEdge: false) let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings)) let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical())) let chartFrame = ExamplesDefaults.chartFrame(self.view.bounds) let chartSettings = ExamplesDefaults.chartSettings chartSettings.trailing = 20 let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel) let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame) let lineModel = ChartLineModel(chartPoints: chartPoints, lineColor: UIColor.redColor(), lineWidth: 1, animDuration: 1, animDelay: 0) let chartPointsLineLayer = ChartPointsLineLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, lineModels: [lineModel]) var settings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth) let guidelinesLayer = ChartGuideLinesDottedLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings) let chart = Chart( frame: chartFrame, layers: [ xAxis, yAxis, guidelinesLayer, chartPointsLineLayer ] ) self.view.addSubview(chart.view) self.chart = chart } } private class MyMultiLabelAxisValue: ChartAxisValue { private let myVal: Int private let derivedVal: Double init(myVal: Int) { self.myVal = myVal self.derivedVal = Double(myVal) / 5.0 super.init(scalar: Double(myVal)) } override var labels:[ChartAxisLabel] { return [ ChartAxisLabel(text: "\(self.myVal)", settings: ChartLabelSettings(font: UIFont.systemFontOfSize(18), fontColor: UIColor.blackColor())), ChartAxisLabel(text: "blabla", settings: ChartLabelSettings(font: UIFont.systemFontOfSize(10), fontColor: UIColor.blueColor())), ChartAxisLabel(text: "\(self.derivedVal)", settings: ChartLabelSettings(font: UIFont.systemFontOfSize(14), fontColor: UIColor.purpleColor())) ] } }
apache-2.0
e001a26deecce8f78d32b52e6f844140
44.153846
258
0.68711
5.038627
false
false
false
false
lelandjansen/fatigue
ios/fatigue/Constants.swift
1
261
import UIKit struct UIConstants { static let buttonWidth: CGFloat = 200 static let buttonHeight: CGFloat = 50 static let buttonSpacing: CGFloat = 16 static let navigationBarHeight: CGFloat = 65 static let tableViewRowHeight: CGFloat = 44 }
apache-2.0
d52901728cbca625b975f0298720454c
28
48
0.735632
5.117647
false
false
false
false
mobilabsolutions/jenkins-ios
JenkinsiOS/Controller/ActionsCollectionViewController.swift
1
6886
// // ActionsTableViewController.swift // JenkinsiOS // // Created by Robert on 10.10.16. // Copyright © 2016 MobiLab Solutions. All rights reserved. // import UIKit class ActionsCollectionViewController: UICollectionViewController, AccountProvidable { var account: Account? var actions: [JenkinsAction] = [.restart, .safeRestart, .exit, .safeExit, .quietDown, .cancelQuietDown] override func viewDidLoad() { super.viewDidLoad() collectionView.backgroundColor = Constants.UI.backgroundColor collectionView.collectionViewLayout = createFlowLayout() collectionView.register(UINib(nibName: "ActionHeaderCollectionReusableView", bundle: .main), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: Constants.Identifiers.actionHeader) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tabBarController?.navigationItem.title = "Actions" // Make sure the navigation item does not contain the search bar. if #available(iOS 11.0, *) { tabBarController?.navigationItem.searchController = nil } } func performAction(action: JenkinsAction) { // Methods for presenting messages to the user func showSuccessMessage() { displayError(title: "Success", message: "The action was completed", textFieldConfigurations: [], actions: [ UIAlertAction(title: "Alright", style: .cancel, handler: nil), ]) } func showFailureMessage(error: Error) { displayNetworkError(error: error, onReturnWithTextFields: { data in self.account?.password = data["password"]! self.account?.username = data["username"]! self.performAction(action: action) }) } guard let account = account else { return } // Perform request NetworkManager.manager.perform(action: action, on: account) { error in DispatchQueue.main.async { if let error = error { if let networkManagerError = error as? NetworkManagerError, case let .HTTPResponseNoSuccess(code, _) = networkManagerError, Constants.Networking.successCodes.contains(code) || code == 503 { showSuccessMessage() } else { showFailureMessage(error: error) } } else { showSuccessMessage() LoggingManager.loggingManager.logTriggeredAction(action: action) } } } } // MARK: - Collection view delegate and datasource override func numberOfSections(in _: UICollectionView) -> Int { return 1 } override func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int { return actions.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Constants.Identifiers.actionCell, for: indexPath) as! ActionCollectionViewCell cell.setup(for: actions[indexPath.row]) return cell } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { guard kind == UICollectionView.elementKindSectionHeader else { fatalError("Only section header supported as supplementary view") } return collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: Constants.Identifiers.actionHeader, for: indexPath) } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard account != nil else { return } verifyAction(action: actions[indexPath.row]) { [unowned self] action in self.performAction(action: action) } collectionView.deselectItem(at: indexPath, animated: true) } private func verifyAction(action: JenkinsAction, onSuccess completion: @escaping (JenkinsAction) -> Void) { let alert = alertWithImage(image: UIImage(named: action.alertImageName), title: action.alertTitle, message: action.alertMessage, height: 49) alert.addAction(UIAlertAction(title: "Yes, do it", style: .default, handler: { _ in completion(action) })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } private func createFlowLayout() -> UICollectionViewFlowLayout { let layout = UICollectionViewFlowLayout() layout.minimumInteritemSpacing = 7 layout.minimumLineSpacing = 7 let width = (view.frame.width - 3 * layout.minimumInteritemSpacing) / 2.0 let height: CGFloat = 70.0 layout.itemSize = CGSize(width: width, height: height) layout.sectionInset = UIEdgeInsets(top: 0, left: 7, bottom: 0, right: 7) layout.headerReferenceSize = CGSize(width: collectionView.frame.width, height: 220) return layout } } private extension JenkinsAction { var alertTitle: String { switch self { case .exit: return "Exit" case .safeExit: return "Safe Exit" case .quietDown: return "Quiet Down" case .cancelQuietDown: return "Cancel Quiet Down" case .restart: return "Restart" case .safeRestart: return "Safe Restart" } } var alertMessage: String { let operation: String switch self { case .exit: operation = "shutdown" case .safeExit: operation = "safely shutdown" case .quietDown: operation = "quiet down" case .cancelQuietDown: operation = "cancel quieting down" case .restart: operation = "restart" case .safeRestart: operation = "safely restart" } return "Do you want to \(operation) the server?" } var alertImageName: String { let identifier: String switch self { case .safeRestart: identifier = "safe-restart" case .safeExit: identifier = "safe-exit" case .exit: identifier = "exit" case .restart: identifier = "restart" case .quietDown: identifier = "quiet-down" case .cancelQuietDown: identifier = "cancel-quiet-down" } return "\(identifier)-server-illustration" } }
mit
10e52fa8ceb4288bee5808b1a5089c2b
37.25
209
0.626434
5.267789
false
false
false
false
kang77649119/DouYuDemo
DouYuDemo/DouYuDemo/Classes/Home/Controller/RecommendVC.swift
1
4769
// // TestViewController.swift // DouYuDemo // // Created by 也许、 on 16/10/8. // Copyright © 2016年 K. All rights reserved. // import UIKit class RecommendVC: BaseAnchorVC { // 轮播 lazy var recommendCarouselView : RecommendCarouselView = { let carouselView = RecommendCarouselView.initView() carouselView.frame = CGRect(x: 0, y: -(carouselViewH + recommendGameViewH), width: screenW, height: carouselViewH) return carouselView }() // 游戏推荐视图 lazy var recommendGameView : RecommendGameView = { let gameView = RecommendGameView.initView() gameView.frame = CGRect(x: 0, y: -recommendGameViewH, width: screenW, height: recommendGameViewH) return gameView }() // 推荐VM lazy var recommentViewModel = RecommendViewModel() } // MARK: - 初始化UI extension RecommendVC { override func setupUI() { self.baseAnchorVM = self.recommentViewModel // 添加直播间collectionView super.setupUI() // 添加轮播视图 collectionView.addSubview(recommendCarouselView) // 添加推荐游戏视图 collectionView.addSubview(recommendGameView) // 设置collectionView的内边距 collectionView.contentInset = UIEdgeInsetsMake(carouselViewH + recommendGameViewH, 0, 0, 0) // 加载轮播数据 loadCarouselData() // 加载主播数据 loadAnchorData() } // 加载主播房间数据 func loadAnchorData() { recommentViewModel.loadData { // 1.加载主播房间数据 self.collectionView.reloadData() // 2.加载游戏推荐数据 var recommendAnchorGroups = self.recommentViewModel.anchorGroups // 去除 推荐和颜值 recommendAnchorGroups.removeFirst() recommendAnchorGroups.removeFirst() // 添加更多按钮 let moreGroup = AnchorGroup() moreGroup.tag_name = "更多" recommendAnchorGroups.append(moreGroup) self.recommendGameView.anchorGroups = recommendAnchorGroups // 请求数据完成,隐藏加载动画,显示内容 self.loadDataFinished() } } // 加载轮播数据 func loadCarouselData() { recommentViewModel.loadCarouselData { self.recommendCarouselView.carouselModels = self.recommentViewModel.carouselModels } } } extension RecommendVC { override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // section = 1 颜值组 if indexPath.section == 1 { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: recommendPrettyCellId, for: indexPath) as! CollectionPrettyCell cell.anchor = self.recommentViewModel.anchorGroups[indexPath.section].anchors[indexPath.item] return cell } else { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: recommendNormalCellId, for: indexPath) as! CollectionNormalCell cell.anchor = self.recommentViewModel.anchorGroups[indexPath.section].anchors[indexPath.item] return cell } } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader.self, withReuseIdentifier: sectionHeaderId, for: indexPath) as! CollectionHeaderView let anchorGroup = self.recommentViewModel.anchorGroups[indexPath.section] // 前两组的头视图图片与其他组的不同 if indexPath.section > 1 { anchorGroup.icon_url = "home_header_normal" } headerView.anchorGroup = anchorGroup return headerView } // 设置cell的itemSize override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 1 { return CGSize(width: prettyItemW, height: prettyItemH) } return CGSize(width: normalItemW, height: normalItemW) } }
mit
acc9f7e1b3f087685a0ccc6707e7bd10
28.946667
202
0.615093
5.657431
false
false
false
false
TheSurfOffice/Foodpic
Foodpic/Beacons/MMBeaconManager.swift
1
8084
// // MMBeaconManager.swift // Foodpic // // Created by Olga Dalton on 17/08/14. // Copyright (c) 2014 Olga Dalton. All rights reserved. // import Foundation import UIKit protocol MMBeaconManagerDelegate { func actionsEntered(manager: MMBeaconManager, actions: [MMBeaconAction]) func actionsExited(manager: MMBeaconManager, actions: [MMBeaconAction]) func locationInfoUpdated(manager: MMBeaconManager, beacons: MMBeaconsArray) } private let _SingletonASharedInstance = MMBeaconManager() // MARK: - // MARK: Actions constants enum SupportedActions: String { case ShowMenu = "ShowMenu" case HideMenu = "HideMenu" } class MMBeaconManager : NSObject, ESTBeaconManagerDelegate { let beaconManager: ESTBeaconManager var beacons: MMBeaconsArray var activeBeacons: MMBeaconsArray var rangingRegions = [ESTBeaconRegion]() var activeActionsDictionary = [String: [MMBeaconAction]]() var exitActionsDictionary = [String: [MMBeaconAction]]() class var sharedInstance : MMBeaconManager { return _SingletonASharedInstance } // MARK: - // MARK: Initialize override init() { beaconManager = ESTBeaconManager() let filePath = NSBundle.mainBundle().pathForResource("beacons", ofType: "json") let jsonData = NSData(contentsOfFile: filePath!, options: .DataReadingMappedIfSafe, error: nil) let jsonObj: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData!, options: .AllowFragments, error: nil) if let jsonDict = jsonObj as? Dictionary<String, AnyObject> { beacons = MMBeaconsArray(jsonDictionary: jsonDict) } else { beacons = MMBeaconsArray() } activeBeacons = MMBeaconsArray() super.init() beaconManager.avoidUnknownStateBeacons = true beaconManager.delegate = self } // MARK: - // MARK: Start monitoring func start() { if self.deviceSettingsAreCorrect() { for beacon in beacons.items { var region = beacon.region beaconManager.startMonitoringForRegion(region) activeActionsDictionary[region.identifier] = [MMBeaconAction]() exitActionsDictionary[region.identifier] = [MMBeaconAction]() } self.startRanging() } } // MARK: - // MARK: Beacons ranging func startRanging() { for beacon in beacons.items { var region = beacon.region beaconManager.startRangingBeaconsInRegion(region) rangingRegions.append(region) } } // MARK: - // MARK: Check device settings func deviceSettingsAreCorrect() -> Bool { var errorMessage = "" if !CLLocationManager.locationServicesEnabled() || (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Denied) { errorMessage += "Location services are turned off! Please turn them on!\n" } if !CLLocationManager.isRangingAvailable() { errorMessage += "Ranging not available!\n" } if !CLLocationManager.isMonitoringAvailableForClass(CLBeaconRegion) { errorMessage += "Beacons ranging not supported!\n" } let errorLen = countElements(errorMessage) if errorLen > 0 { self.showErrorMessage(errorMessage) } return errorLen == 0 } // MARK: - // MARK: Background handling func startForegroundMode() { if self.deviceSettingsAreCorrect() { self.startRanging() } } // MARK: - // MARK: Error alert func showErrorMessage(message: String) { var alert = UIAlertView(title: message, message: nil, delegate: nil, cancelButtonTitle: "Ok") alert.show() } var delegate: MMBeaconManagerDelegate? // MARK: - // MARK: ESTBeaconManager callbacks func beaconManager(manager: ESTBeaconManager!, didEnterRegion region: ESTBeaconRegion!) { if UIApplication.sharedApplication().applicationState == .Active { beaconManager.startRangingBeaconsInRegion(region) } } func beaconManager(manager: ESTBeaconManager!, monitoringDidFailForRegion region: ESTBeaconRegion!, withError error: NSError!) { self.showErrorMessage(error.localizedDescription) } func beaconManager(manager: ESTBeaconManager!, rangingBeaconsDidFailForRegion region: ESTBeaconRegion!, withError error: NSError!) { self.showErrorMessage(error.localizedDescription) } func beaconManager(manager: ESTBeaconManager!, didDetermineState state: CLRegionState, forRegion region: ESTBeaconRegion!) { // if state == .Inside { // // if UIApplication.sharedApplication().applicationState == .Active { // beaconManager.startRangingBeaconsInRegion(region) // } // // } else if state == .Outside { // beaconManager.stopRangingBeaconsInRegion(region) // } } func beaconManager(manager: ESTBeaconManager!, didRangeBeacons estimoteBeacons: [AnyObject]!, inRegion region: ESTBeaconRegion!) { NSLog("Did range beacons %@ in region %@", estimoteBeacons, region) for estBeacon in estimoteBeacons as [ESTBeacon] { if estBeacon.distance.intValue != -1 { let beacon = beacons.getBeacon(estBeacon.proximityUUID, major: estBeacon.major.integerValue, minor: estBeacon.minor.integerValue); if let mmBeacon = beacon { if let found = find(activeBeacons.items, mmBeacon) { activeBeacons.items.removeAtIndex(found) } mmBeacon.estimoteBeacon = estBeacon; mmBeacon.updateBeaconDistance(estBeacon.distance.doubleValue) activeBeacons.items.append(mmBeacon) } } } activeBeacons.sortByAverageDistance() NSLog("Active beacons %@", activeBeacons.description) if activeBeacons.items.count > 0 { let firstBeacon = activeBeacons.items[0] as MMBeacon if firstBeacon.distanceCalculated { delegate?.locationInfoUpdated(self, beacons: activeBeacons) var activeActions = activeActionsDictionary[region.identifier]! var activeExitActions = exitActionsDictionary[region.identifier]! var currentEntryBeaconsActions = activeBeacons.getActiveActions(true) var currentExitBeaconsActions = activeBeacons.getActiveActions(false) var enteredActions = self.distinct(currentEntryBeaconsActions, otherArray: activeActions) var exitedActions = self.distinct(activeExitActions, otherArray: currentExitBeaconsActions) delegate?.actionsEntered(self, actions: enteredActions) delegate?.actionsExited(self, actions: exitedActions) activeActionsDictionary[region.identifier] = currentEntryBeaconsActions exitActionsDictionary[region.identifier] = currentExitBeaconsActions } } } func distinct<T:Equatable>(firstArray: [T], otherArray: [T]) -> [T] { var missingObjects = [T]() for object in firstArray { if !contains(otherArray, object) { missingObjects.append(object) } } return missingObjects } }
mit
356060c436e7166a4e18cadd6c1b52ea
31.732794
146
0.59859
5.567493
false
false
false
false
TCA-Team/iOS
TUM Campus App/PersonDetailTableViewController.swift
1
4482
// // PersonDetailTableViewController.swift // TUM Campus App // // This file is part of the TUM Campus App distribution https://github.com/TCA-Team/iOS // Copyright (c) 2018 TCA // // 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, version 3. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import UIKit class PersonDetailTableViewController: UITableViewController, DetailView { var user: DataElement? weak var delegate: DetailViewDelegate? var contactInfo: [(ContactInfoType, String)] { return (user as? UserData)?.contactInfo ?? [] } var addingContact = false @objc func addContact(_ sender: AnyObject?) { let handler = { () in DoneHUD.showInView(self.view, message: "Contact Added") } if let data = user as? UserData { if data.contactsLoaded { addingContact = false data.addContact(handler) } else { addingContact = true } } } } extension PersonDetailTableViewController { func fetch(for user: UserData) { delegate?.dataManager()?.personDetailsManager.fetch(for: user).onSuccess(in: .main) { user in self.user = user self.tableView.reloadData() if self.addingContact { self.addContact(nil) } } } } extension PersonDetailTableViewController { override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = tableView.rowHeight tableView.rowHeight = UITableView.automaticDimension title = user?.text let barItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(PersonDetailTableViewController.addContact(_:))) navigationItem.rightBarButtonItem = barItem if let data = user as? UserData { self.fetch(for: data) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) if #available(iOS 11.0, *) { self.navigationController?.navigationBar.prefersLargeTitles = false self.navigationController?.navigationItem.largeTitleDisplayMode = .never } } } extension PersonDetailTableViewController { override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 1 } return contactInfo.count } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 1 && !contactInfo.isEmpty { return "Contact Info" } return nil } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { if let data = user { let cell = tableView.dequeueReusableCell(withIdentifier: data.getCellIdentifier()) as? CardTableViewCell ?? CardTableViewCell() cell.setElement(data) return cell } } let cell = tableView.dequeueReusableCell(withIdentifier: "contact") ?? UITableViewCell() if indexPath.row < contactInfo.count { cell.textLabel?.text = contactInfo[indexPath.row].0.rawValue cell.detailTextLabel?.text = contactInfo[indexPath.row].1 } else { cell.textLabel?.text = "" cell.detailTextLabel?.text = "" } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 1 && indexPath.row < contactInfo.count { contactInfo[indexPath.row].0.handle(contactInfo[indexPath.row].1, sender: self) } } }
gpl-3.0
64a0454ebc463494c65d92ad2e276a99
31.244604
145
0.624052
5.024664
false
false
false
false
nvzqz/Sage
Sources/Color.swift
1
2464
// // Color.swift // Sage // // Copyright 2016-2017 Nikolai Vazquez // // 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. // /// A chess color. public enum Color: String, CustomStringConvertible { #if swift(>=3) /// White chess color. case white /// Black chess color. case black /// White color regardless of Swift version. internal static let _white = Color.white /// Black color regardless of Swift version. internal static let _black = Color.black /// An array of all colors. public static let all: [Color] = [.white, .black] #else /// White chess color. case White /// Black chess color. case Black /// White color regardless of Swift version. internal static let _white = Color.White /// Black color regardless of Swift version. internal static let _black = Color.Black /// An array of all colors. public static let all: [Color] = [.White, .Black] #endif /// Whether the color is white or not. public var isWhite: Bool { return self == ._white } /// Whether the color is black or not. public var isBlack: Bool { return self == ._black } /// A textual representation of `self`. public var description: String { return rawValue } /// The lowercase character for the color. `White` is "w", `Black` is "b". public var character: Character { return self.isWhite ? "w" : "b" } /// Create a color from a character of any case. public init?(character: Character) { switch character { case "W", "w": self = ._white case "B", "b": self = ._black default: return nil } } /// Returns the inverse of `self`. public func inverse() -> Color { return self.isWhite ? ._black : ._white } /// Inverts the color of `self`. public mutating func invert() { self = inverse() } }
apache-2.0
ad54df6b06ca322a084bf6ffd943c3a3
24.142857
78
0.622159
4.183362
false
false
false
false
AlesTsurko/DNMKit
DNMModel/Pitch.swift
1
8900
// // Pitch.swift // denm_pitch // // Created by James Bean on 8/11/15. // Copyright © 2015 James Bean. All rights reserved. // import Foundation /** Pitch */ public class Pitch: CustomStringConvertible, Equatable { // MARK: String Representation /// Printable description of Pitch public var description: String { return getDescription() } // MARK: Attributes /// MIDI representation of Pitch (middle-c = 60.0, C5 = 72.0, C3 = 48.0, etc) public var midi: MIDI /// Frequency representation of Pitch (middle-c = 261.6) public var frequency: Frequency /// Modulo 12 representation of Pitch // dedicated class? public var pitchClass: Pitch { return PitchClass(pitch: self) } /// Resolution of Pitch (1.0 = chromatic, 0.5 = 1/4-tone, 0.25 = 1/8-tone) public var resolution: Float { return midi.value % 1 == 0 ? 1.0 : midi.value % 0.5 == 0 ? 0.5 : 0.25 } public var octave: Int { get { return getOctave() } } // MARK: Spelling a Pitch /// PitchSpelling of Pitch, if it has been spelled. public var spelling: PitchSpelling? /// All possible PitchSpellings of Pitch public var possibleSpellings: [PitchSpelling] { return PitchSpelling.pitchSpellingsForPitch(pitch: self) } /// Check if this Pitch has been spelled public var hasBeenSpelled: Bool { return spelling != nil } // NYI: Create random pitch with Frequency /** Creates a random pitch within sensible values. - returns: Pitch with random value */ public class func random() -> Pitch { let randomMIDI: Float = randomFloat(min: 60, max: 79, resolution: 0.25) //assert(randomMIDI > 60, "random MIDI not in range") return Pitch(midi: MIDI(randomMIDI)) } /** Creates a pitch within range and with resolution decided by user - parameter min: Minimum MIDI value - parameter max: Maximum MIDI value - parameter resolution: Resolution of Pitch (1.0: Half-tone, 0.5: Quarter-tone, 0.25: Eighth-tone) - returns: Pitch within range and resolution decided by user */ public class func random(min: Float, max: Float, resolution: Float) -> Pitch { let randomMIDI: Float = randomFloat(min: min, max: max, resolution: resolution) return Pitch(midi: MIDI(randomMIDI)) } /** Creates an array of pitches with random values - parameter amount: Amount of pitches desired - returns: Array of pitches with random values */ public class func random(amount: Int) -> [Pitch] { var pitches: [Pitch] = [] for _ in 0..<amount { pitches.append(Pitch.random()) } return pitches } public class func random(amount: Int, min: Float, max: Float, resolution: Float) -> [Pitch] { var pitches: [Pitch] = [] for _ in 0..<amount { pitches.append(Pitch.random(min, max: max, resolution: resolution)) } return pitches } public static func middleC() -> Pitch { return Pitch(midi: MIDI(60)) } // MARK: Create a Pitch /** Create a Pitch with MIDI value and optional resolution. - parameter midi: MIDI representation of Pitch (middle-c = 60.0, C5 = 72.0, C3 = 48.0) - parameter resolution: Resolution of returned MIDI. Default is nil (objective resolution). (1 = chromatic, 0.5 = 1/4-tone resolution, 0.25 = 1/8-tone resolution) - returns: Initialized Pitch object */ public init(midi: MIDI, resolution: Float? = nil) { // add resolution functionality self.midi = MIDI(value: midi.value, resolution: resolution) self.frequency = Frequency(midi: midi) } /** Create a Pitch with Frequency and optional resolution - parameter frequency: Frequency representation of Pitch - parameter resolution: Resolution of returned MIDI. Default is nil (objective resolution). (1 = chromatic, 0.5 = 1/4-tone resolution, 0.25 = 1/8-tone resolution) - returns: Initialized Pitch object */ public init(frequency: Frequency, resolution: Float? = nil) { var m = MIDI(frequency: frequency) if let resolution = resolution { m.quantizeToResolution(resolution) } self.midi = m self.frequency = Frequency(midi: m) } // TODO: init(var string: String, andEnforceSpelling shouldEnforceSpelling: Bool) throws // move this to Parser, and call it from there... get it outta here! /** Create a Pitch with String. - Defaults: octave starting at middle-c (c4), natural - Specify sharp: "#" or "s" - Specify flat: "b" - Specify quarterSharp: "q#", "qs" - Specify quarterFlat: "qf" - Specify eighthTones: "gup", "d_qf_down_7", etc - Underscores are ignored, and helpful for visualization For example: - "c" or "C" = middleC - "d#","ds","ds4","d_s_4" = midi value 63.0 ("d sharp" above middle c) - "eqb5","e_qf_5" = midi value 75.5 - "eb_up" = midi value 63.25 - parameter string: String representation of Pitch - returns: Initialized Pitch object if you didn't fuck up the formatting of the String. */ public convenience init?(string: String) { if let midi = midiFloatWithString(string) { self.init(midi: MIDI(midi)) } else { return nil } } // MARK: Set attributes of a Pitch /** Set MIDI value of Pitch - parameter midi: MIDI value (middle-c = 60.0, C5 = 72.0, C3 = 48.0) - returns: Pitch object */ public func setMIDI(midi: MIDI) -> Pitch { self.midi = midi self.frequency = Frequency(midi: midi) return self } /** Set frequency of Pitch - parameter frequency: Frequency of Pitch - returns: Pitch object */ public func setFrequency(frequency: Frequency) -> Pitch { self.frequency = frequency self.midi = MIDI(frequency: frequency) return self } /** Set PitchSpelling of Pitch - parameter pitchSpelling: PitchSpelling - returns: Pitch object */ public func setPitchSpelling(pitchSpelling: PitchSpelling) -> Pitch { self.spelling = pitchSpelling return self } public func clearPitchSpelling() { self.spelling = nil } // MARK: Operations /** Make a copy of Pitch without spelling - returns: Copy of Pitch without PitchSpelling */ public func copy() -> Pitch { return Pitch(midi: midi) } // transposeByInterval() // invertAroundPitch // MARK: Get information of partials of Pitch /** Get MIDI representation of partial of Pitch - parameter partial: Desired partial - parameter resolution: Resolution of returned MIDI. Default is nil (objective resolution). (1 = chromatic, 0.5 = 1/4-tone resolution, 0.25 = 1/8-tone resolution) - returns: MIDI representation of partial */ public func getMIDIOfPartial(partial: Int, resolution: Float? = nil) -> MIDI { return MIDI(frequency: frequency * Float(partial)) } /** Get Frequency representation of partial of Pitch - parameter partial: Desired partial - parameter resolution: Resolution of returned MIDI. Default is nil (objective resolution). (1 = chromatic, 0.5 = 1/4-tone resolution, 0.25 = 1/8-tone resolution) - returns: Frequency representation of partial */ public func frequencyOfPartial(partial: Int, resolution: Float? = nil) -> Frequency { return frequency * Float(partial) } internal func getOctave() -> Int { var octave = Int(floor(midi.value / 12)) - 1 if spelling != nil { if spelling!.letterName == .C && spelling!.coarse == 0 && spelling!.fine == -0.25 { octave += 1 } else if spelling!.letterName == .C && spelling!.coarse == -0.5 { octave += 1 } } return octave } internal func getDescription() -> String { var description: String = "Pitch: \(midi.value)" if hasBeenSpelled { description += "; \(spelling!)" } return description } } public func ==(lhs: Pitch, rhs: Pitch) -> Bool { return lhs.midi.value == rhs.midi.value } public func <(lhs: Pitch, rhs: Pitch) -> Bool { return lhs.midi.value < rhs.midi.value } public func >(lhs: Pitch, rhs: Pitch) -> Bool { return lhs.midi.value > rhs.midi.value } public func <=(lhs: Pitch, rhs: Pitch) -> Bool { return lhs.midi.value <= rhs.midi.value } public func >=(lhs: Pitch, rhs: Pitch) -> Bool { return lhs.midi.value >= rhs.midi.value }
gpl-2.0
81143e5220a206bf75581e9b7a833054
29.375427
102
0.608945
4.162301
false
false
false
false
kstaring/swift
validation-test/compiler_crashers_fixed/00537-swift-constraints-solution-computesubstitutions.swift
11
633
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse protocol A : T { var e: H.b { }() var d = c>: NSObject { } func b> { var b.h == .B == """ class func a(#object1, f, b = c() { for b { let c(() -> T -> T where T> Void>) { protocol e = a() -> (g<T) { } } } } typealias F = b } print(f: A.b in
apache-2.0
d0a5e398a58e73692fafd52d2cc385ce
23.346154
78
0.64455
3.028708
false
false
false
false
nicemohawk/nmf-ios
nmf/MapViewController.swift
1
6717
// // MapViewController.swift // nmf // // Created by Ben Lachman on 5/29/16. // Copyright © 2017 Nelsonville Music Festival. All rights reserved. // import UIKit import Contacts import MapKit class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { lazy var locationManager: CLLocationManager = { let manager = CLLocationManager() manager.delegate = self manager.desiredAccuracy = kCLLocationAccuracyBest return manager }() // Old location: 39.441332° N, 82.218652° W // New Location 39.45847° N, 82.173037° W let nmf = CLLocation(latitude: 39.45847, longitude: -82.173037) let nmfDirections = CLLocation(latitude: 39.46042, longitude: -82.17936) // for maps directions let tileOverlay = TileOverlay(urlTemplate: Bundle.main.bundleURL.absoluteString + "mapdata/{z}/{x}/{y}.png") @IBOutlet var mapView: MKMapView! @IBOutlet weak var currentLocationButton: UIButton! @IBOutlet weak var singleTapLegendRecognizer: UITapGestureRecognizer! override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidLoad() { // 2.17 miles = 3500 meters let region = MKCoordinateRegion.init(center: nmf.coordinate, latitudinalMeters: 600.0, longitudinalMeters: 600.0) mapView.setRegion(region, animated: true) tileOverlay.canReplaceMapContent = false tileOverlay.tileSize = CGSize(width: 512, height: 512) mapView.insertOverlay(tileOverlay, at: 0, level: .aboveRoads) let doubleTap = UITapGestureRecognizer(target: self, action: nil) doubleTap.numberOfTapsRequired = 2 doubleTap.numberOfTouchesRequired = 1 mapView.addGestureRecognizer(doubleTap) singleTapLegendRecognizer.require(toFail: doubleTap) } override func viewWillAppear(_ animated: Bool) { // location manager let authorization = CLLocationManager.authorizationStatus() if authorization == .denied || authorization == .restricted { print("Unabled to access location") } else { if authorization == .notDetermined { locationManager.requestWhenInUseAuthorization() } if CLLocationManager.locationServicesEnabled() == true { locationManager.startUpdatingLocation() } } currentLocationButton.layer.borderColor = UIColor.mapBackgroundColor().cgColor currentLocationButton.layer.borderWidth = 1 currentLocationButton.layer.cornerRadius = 12 super.viewWillAppear(animated) } private lazy var setupLegend: Void = { self.toggleLegendAction(self) // Do this once }() override func viewDidAppear(_ animated: Bool) { _ = setupLegend } // MARK: - Actions @IBOutlet weak var lengendTopConstraint: NSLayoutConstraint! @IBOutlet weak var legendImageView: UIImageView! @IBAction func toggleLegendAction(_ sender: AnyObject) { var height = -(legendImageView.bounds.height) var delay = 0.0 if sender is MapViewController { delay = 0.33 } if lengendTopConstraint.constant < 0 { height = self.mapView.frame.height + height } else { height *= 2 // off screen } self.lengendTopConstraint.constant = height UIView.animate(withDuration: 0.4, delay: delay, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.25, options: [], animations: { self.view.layoutIfNeeded() }, completion: nil) } @IBAction func locationButtonAction(_ sender: UIButton) { if let userLocation = locationManager.location { mapView.setCenter(userLocation.coordinate, animated: true) } } @IBAction func nmfButtonAction(_ sender: AnyObject) { let region = MKCoordinateRegion.init(center: nmf.coordinate, latitudinalMeters: 310.0, longitudinalMeters: 310.0) mapView.setRegion(region, animated: true) } @IBAction func actionButtonAction(_ sender: UIBarButtonItem) { let alertController = UIAlertController(title: "Need Directions to NMF?", message: nil, preferredStyle: .actionSheet) alertController.addAction(UIAlertAction(title: "Open in Maps", style: .default, handler: { (action) in let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: self.nmfDirections.coordinate, addressDictionary: [CNPostalAddressStreetKey: "Happy Hollow Rd", CNPostalAddressCityKey: "Nelsonville", CNPostalAddressStateKey: "Ohio"])) let launchOptions = [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving] mapItem.openInMaps(launchOptions: launchOptions) })) if (UIApplication.shared.canOpenURL(URL(string:"comgooglemaps://")!)) { alertController.addAction(UIAlertAction(title: "Open in Google Maps", style: .default, handler: { (action) in UIApplication.shared.open(NSURL(string: "comgooglemaps://?saddr=&daddr=\(Float(self.nmf.coordinate.latitude)),\(Float(self.nmf.coordinate.longitude))&directionsmode=driving")! as URL) })) } alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) in self.dismiss(animated: true, completion: nil) })) present(alertController, animated: true, completion: nil) } // MARK: - MapKit delegate methods func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { return MKTileOverlayRenderer(tileOverlay: self.tileOverlay) } // MARK: - CLLocationManagerDelegate // func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { // } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .authorizedWhenInUse { manager.startUpdatingLocation() } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print(error.localizedDescription) } } class TileOverlay : MKTileOverlay { override func loadTile(at path: MKTileOverlayPath, result: @escaping (Data?, Error?) -> Void) { super.loadTile(at: path, result: result) } }
apache-2.0
775cd552da4406f7a1ded9abf83d8e8b
36.082873
241
0.64854
5.131498
false
false
false
false
jeroendesloovere/examples-swift
Swift-Playgrounds/SwiftStanardLibrary/Array.playground/section-1.swift
2
3913
// Swift Standard Library - Types - Array // An Array is a generic type that manages an ordered collection of items, all of which must be of the same underlying type. // Creating and Array var emptyArray = Array<Int>() var equivilentEmptyArray = [Int]() let numericArray = Array(count: 3, repeatedValue: 42) let stringArray = Array(count: 2, repeatedValue: "Hello") // Accessing Array Elements var subscriptableArray = ["zero", "one", "two", "three"] let zero = subscriptableArray[0] let three = subscriptableArray[3] subscriptableArray[0] = "nothing" subscriptableArray[3] = "three items" subscriptableArray // It is not possible to insert additional items into the array using subscripting: // subscriptableArray[4] = "new item" // Fatal erro: Array Index out of range // Instead use append() or += // You also can't modify the contents of an array that was initialised using let let constantArray = ["zero", "one", "two", "three"] //constantArray[0] = "nothing" subscriptableArray = ["zero", "one", "two", "three"] let subRange = subscriptableArray[1...3] subscriptableArray[1...2] = ["oneone", "twotwo"] subscriptableArray subscriptableArray[1...2] = [] subscriptableArray // It is not possible to insert additional items into the array using subscripting //subscriptableArray[4...5] = ["four", "five"] // Adding and Removing Elements var array = [0, 1] array.append(2) array array.append(3) array // You can only append to an array that has been initialised with the var keyword. //constantArray.append("another") array = [1, 2, 3] array.insert(0, atIndex: 0) array // The index must be less than or equal to the number of items in the collection //array.insert(6, atIndex: 6) // You can't insert into an array that was initialised with let let removed = array.removeAtIndex(0) array // The index must be valid // You can't remove from an array that was created with let let lastRemoved = array.removeLast() array // There must be at least one element in the array // You can't removeLast() from a constant array array = [0, 1, 2, 3] array.removeAll() let count = array.count array // Unless you specify otherwise, the underlying backing storage will be cleared array = [0, 1, 2, 3] array.removeAll(keepCapacity: true) array array.reserveCapacity(10) // Ensures that the underlying storage can hold the given total number of elements // Querying an array var arrayToCount = ["zero", "one", "two"] let firstCount = arrayToCount.count arrayToCount += ["three"] let secondCount = arrayToCount.count let firstIsEmpty = arrayToCount.isEmpty arrayToCount.removeAll() let secondIsEmpty = arrayToCount.isEmpty var capacity = arrayToCount.capacity arrayToCount.reserveCapacity(1000) capacity = arrayToCount.capacity // Algorithms // Sort // The closure that you supply for isOrderedBefore should return a Boolean value to indicate whether one element should be before (true) or after (false) another element: var arrayToSort = [3, 2, 5, 1, 4] arrayToSort.sort { $0 < $1 } arrayToSort arrayToSort.sort { $1 < $0 } arrayToSort // You can only sort an array inplace if it was declared with var arrayToSort = [3, 2, 5, 1, 4] let sortedArray = arrayToSort.sorted { $0 < $1 } sortedArray let descendingArray = arrayToSort.sorted { $1 < $0 } descendingArray sortedArray let reversedArray = sortedArray.reverse() reversedArray let filteredArray = sortedArray.filter { $0 % 2 == 0 } filteredArray let multipliedArray = sortedArray.map { $0 * 2 } multipliedArray let describedArray = sortedArray.map { "Number: \($0)" } describedArray let addResult = sortedArray.reduce(0) { $0 + $1 } addResult let multipliedResult = sortedArray.reduce(0) { $0 * $1 } multipliedResult // Operators var operatorArray = [0, 1, 2] operatorArray += [3] operatorArray += [4, 5, 6] // The type of elements must match // You can only add new elements to an array that has been declared with var
mit
b22258e6c445e221dc5545142361fa27
23.45625
170
0.732175
3.701987
false
false
false
false
Coderian/SwiftedKML
SwiftedKML/Elements/Location.swift
1
2406
// // Location.swift // SwiftedKML // // Created by 佐々木 均 on 2016/02/02. // Copyright © 2016年 S-Parts. All rights reserved. // import Foundation /// KML Location /// /// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd) /// /// <element name="Location" type="kml:LocationType" substitutionGroup="kml:AbstractObjectGroup"/> public class Location :SPXMLElement, AbstractObjectGroup, HasXMLElementValue { public static var elementName:String = "Location" public override var parent:SPXMLElement! { didSet { // 複数回呼ばれたて同じものがある場合は追加しない if self.parent.childs.contains(self) == false { self.parent.childs.insert(self) switch parent { case let v as Model: v.value.location = self default: break } } } } public var value : LocationType required public init(attributes:[String:String]){ self.value = LocationType(attributes: attributes) super.init(attributes: attributes) } public var abstractObject : AbstractObjectType { return self.value } } /// KML LocationType /// /// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd) /// /// <complexType name="LocationType" final="#all"> /// <complexContent> /// <extension base="kml:AbstractObjectType"> /// <sequence> /// <element ref="kml:longitude" minOccurs="0"/> /// <element ref="kml:latitude" minOccurs="0"/> /// <element ref="kml:altitude" minOccurs="0"/> /// <element ref="kml:LocationSimpleExtensionGroup" minOccurs="0" maxOccurs="unbounded"/> /// <element ref="kml:LocationObjectExtensionGroup" minOccurs="0" maxOccurs="unbounded"/> /// </sequence> /// </extension> /// </complexContent> /// </complexType> /// <element name="LocationSimpleExtensionGroup" abstract="true" type="anySimpleType"/> /// <element name="LocationObjectExtensionGroup" abstract="true" substitutionGroup="kml:AbstractObjectGroup"/> public class LocationType: AbstractObjectType { public var longitude: Longitude! // = 0.0 public var latitude: Latitude! // = 0.0 public var altitude: Altitude! // = 0.0 public var locationSimpleExtensionGroup: [AnyObject] = [] public var locationObjectExtensionGroup: [AbstractObjectGroup] = [] }
mit
56c264c2246da0c295286b8721647be0
36.887097
114
0.651767
3.981356
false
false
false
false
lemberg/obd2-swift-lib
OBD2-Swift/Classes/Scanner/Scanner.swift
1
6723
// // Sanner.swift // OBD2Swift // // Created by Max Vitruk on 24/05/2017. // Copyright © 2017 Lemberg. All rights reserved. // import Foundation enum ReadInputError: Error { case initResponseUnreadable } enum InitScannerError: Error { case outputTimeout case inputTimeout } public typealias StateChangeCallback = (_ state: ScanState) -> () class `Scanner`: StreamHolder { typealias CallBack = (Bool, Error?) -> () var defaultSensors: [UInt8] = [0x0C, 0x0D] var supportedSensorList = [Int]() private var repeatCommands = Set<DataRequest>() var state: ScanState = .none { didSet { if state == .none { obdQueue.cancelAllOperations() } stateChanged?(state) } } var stateChanged: StateChangeCallback? var `protocol`: ScanProtocol = .none var currentPIDGroup: UInt8 = 0x00 init(host: String, port: Int) { super.init() self.host = host self.port = port delegate = self } open func request(command: DataRequest, response : @escaping (_ response:Response) -> ()){ let request = CommandOperation(inputStream: inputStream, outputStream: outputStream, command: command) request.onReceiveResponse = response request.queuePriority = .high request.completionBlock = { print("Request operation completed") } obdQueue.addOperation(request) } open func startRepeatCommand(command: DataRequest, response : @escaping (_ response:Response) -> ()) { if repeatCommands.contains(command) { print("Command alredy on repeat loop and can be observed") return } repeatCommands.insert(command) request(repeat: command, response: response) } open func stopRepeatCommand(command: DataRequest) { repeatCommands.remove(command) } open func isRepeating(command: DataRequest) -> Bool { return repeatCommands.contains(command) } private func request(repeat command: DataRequest, response : @escaping (_ response:Response) -> ()) { let request = CommandOperation(inputStream: inputStream, outputStream: outputStream, command: command) request.queuePriority = .low request.onReceiveResponse = response request.completionBlock = { [weak self] in print("Request operation completed") if let error = request.error { print("Error occured \(error)") self?.state = .none } else { guard let strong = self else { return } if strong.repeatCommands.contains(command) { strong.request(repeat: command, response: response) } } } obdQueue.addOperation(request) } open func startScan(callback: @escaping CallBack){ if state != .none { return } state = .openingConnection obdQueue.cancelAllOperations() createStreams() // Open connection to OBD let openConnectionOperation = OpenOBDConnectionOperation(inputStream: inputStream, outputStream: outputStream) openConnectionOperation.completionBlock = { [weak self] in if let error = openConnectionOperation.error { print("open operation completed with error \(error)") self?.state = .none self?.obdQueue.cancelAllOperations() } else { self?.state = .initializing print("open operation completed without errors") } } obdQueue.addOperation(openConnectionOperation) // Initialize connection with OBD let initOperation = InitScanerOperation(inputStream: inputStream, outputStream: outputStream) initOperation.completionBlock = { [weak self] in if let error = initOperation.error { callback(false, error) self?.state = .none self?.obdQueue.cancelAllOperations() } else { self?.state = .connected callback(true, nil) } } obdQueue.addOperation(initOperation) } open func pauseScan() { obdQueue.isSuspended = true } open func resumeScan() { obdQueue.isSuspended = false } open func cancelScan() { repeatCommands.removeAll() obdQueue.cancelAllOperations() } open func disconnect() { cancelScan() inputStream.close() outputStream.close() state = .none } open func isService01PIDSupported(pid : Int) -> Bool { var supported = false for supportedPID in supportedSensorList { if supportedPID == pid { supported = true break } } return supported } } extension Scanner: StreamFlowDelegate { func didOpen(stream: Stream){ } func error(_ error: Error, on stream: Stream){ } func hasInput(on stream: Stream){ // // do { // // if state == .init { // try readInitResponse() // } else if state == .idle || state == .waiting { // waitingForVoltageCommand ? readVoltageResponse() : readInput() // // } else { // print("Error: Received bytes in unknown state: \(state)") // } // // } catch { // // print("Error: Init response unreadable. Need reconnect") // //TODO: try reconnect // } // // } } extension Scanner { enum State : UInt { case unknown = 1 case reset = 2 case echoOff = 4 case version = 8 case search = 16 case `protocol` = 32 case complete = 64 static var all : [State] { return [.unknown, .reset, .echoOff, .version, .search, .`protocol`, .complete] } static func <<= (left: State, right: UInt) -> State { let move = left.rawValue << right return self.all.filter({$0.rawValue == move}).first ?? .unknown } mutating func next() { self = self <<= 1 } } }
mit
a7a17a71d2c87f2a2952e257e6cb401e
26.325203
118
0.535257
5.020164
false
false
false
false
rsmoz/swift-corelibs-foundation
Foundation/NSDictionary.swift
1
25494
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation extension Dictionary : _ObjectTypeBridgeable { public func _bridgeToObject() -> NSDictionary { let keyBuffer = UnsafeMutablePointer<NSObject>.alloc(count) let valueBuffer = UnsafeMutablePointer<AnyObject>.alloc(count) var idx = 0 self.forEach { let key = _NSObjectRepresentableBridge($0.0) let value = _NSObjectRepresentableBridge($0.1) keyBuffer.advancedBy(idx).initialize(key) valueBuffer.advancedBy(idx).initialize(value) idx += 1 } let dict = NSDictionary(objects: valueBuffer, forKeys: keyBuffer, count: count) keyBuffer.destroy(count) valueBuffer.destroy(count) keyBuffer.dealloc(count) valueBuffer.dealloc(count) return dict } public static func _forceBridgeFromObject(x: NSDictionary, inout result: Dictionary?) { var dict = [Key: Value]() var failedConversion = false if x.dynamicType == NSDictionary.self || x.dynamicType == NSMutableDictionary.self { x.enumerateKeysAndObjectsUsingBlock { key, value, stop in if let k = key as? Key { if let v = value as? Value { dict[k] = v } else { failedConversion = true stop.memory = true } } else { failedConversion = true stop.memory = true } } } else if x.dynamicType == _NSCFDictionary.self { let cf = x._cfObject let cnt = CFDictionaryGetCount(cf) let keys = UnsafeMutablePointer<UnsafePointer<Void>>.alloc(cnt) let values = UnsafeMutablePointer<UnsafePointer<Void>>.alloc(cnt) CFDictionaryGetKeysAndValues(cf, keys, values) for idx in 0..<cnt { let key = unsafeBitCast(keys.advancedBy(idx).memory, AnyObject.self) let value = unsafeBitCast(values.advancedBy(idx).memory, AnyObject.self) if let k = key as? Key { if let v = value as? Value { dict[k] = v } else { failedConversion = true break } } else { failedConversion = true break } } keys.destroy(cnt) values.destroy(cnt) keys.dealloc(cnt) values.dealloc(cnt) } if !failedConversion { result = dict } } public static func _conditionallyBridgeFromObject(x: NSDictionary, inout result: Dictionary?) -> Bool { _forceBridgeFromObject(x, result: &result) return true } } public class NSDictionary : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCoding { private let _cfinfo = _CFInfo(typeID: CFDictionaryGetTypeID()) internal var _storage = [NSObject: AnyObject]() public var count: Int { get { if self.dynamicType === NSDictionary.self || self.dynamicType === NSMutableDictionary.self { return _storage.count } else { NSRequiresConcreteImplementation() } } } public func objectForKey(aKey: AnyObject) -> AnyObject? { if self.dynamicType === NSDictionary.self || self.dynamicType === NSMutableDictionary.self { return _storage[aKey as! NSObject] } else { NSRequiresConcreteImplementation() } } public func keyEnumerator() -> NSEnumerator { if self.dynamicType === NSDictionary.self || self.dynamicType === NSMutableDictionary.self { return NSGeneratorEnumerator(_storage.keys.generate()) } else { NSRequiresConcreteImplementation() } } public override convenience init() { self.init(objects: nil, forKeys: nil, count: 0) } public required init(objects: UnsafePointer<AnyObject>, forKeys keys: UnsafePointer<NSObject>, count cnt: Int) { for idx in 0..<cnt { let key = keys[idx].copy() let value = objects[idx] _storage[key as! NSObject] = value } } public required convenience init?(coder aDecoder: NSCoder) { self.init(objects: nil, forKeys: nil, count: 0) } public func encodeWithCoder(aCoder: NSCoder) { NSUnimplemented() } public static func supportsSecureCoding() -> Bool { return true } public override func copy() -> AnyObject { return copyWithZone(nil) } public func copyWithZone(zone: NSZone) -> AnyObject { if self.dynamicType === NSDictionary.self { // return self for immutable type return self } else if self.dynamicType === NSMutableDictionary.self { let dictionary = NSDictionary() dictionary._storage = self._storage return dictionary } return NSDictionary(objects: self.allValues, forKeys: self.allKeys.map({ $0 as! NSObject})) } public override func mutableCopy() -> AnyObject { return mutableCopyWithZone(nil) } public func mutableCopyWithZone(zone: NSZone) -> AnyObject { if self.dynamicType === NSDictionary.self || self.dynamicType === NSMutableDictionary.self { // always create and return an NSMutableDictionary let mutableDictionary = NSMutableDictionary() mutableDictionary._storage = self._storage return mutableDictionary } return NSMutableDictionary(objects: self.allValues, forKeys: self.allKeys.map({ $0 as! NSObject})) } public convenience init(object: AnyObject, forKey key: NSCopying) { self.init(objects: [object], forKeys: [key as! NSObject]) } // public convenience init(dictionary otherDictionary: [NSObject : AnyObject]) { // self.init(dictionary: otherDictionary, copyItems: false) // } // public convenience init(dictionary otherDictionary: [NSObject : AnyObject], copyItems flag: Bool) { // var keys = Array<KeyType>() // var values = Array<AnyObject>() // for key in otherDictionary.keys { // keys.append(key) // var value = otherDictionary[key] // if flag { // if let val = value as? NSObject { // value = val.copy() // } // } // values.append(value!) // } // self.init(objects: values, forKeys: keys) // } public convenience init(objects: [AnyObject], forKeys keys: [NSObject]) { let keyBuffer = UnsafeMutablePointer<NSObject>.alloc(keys.count) keyBuffer.initializeFrom(keys) let valueBuffer = UnsafeMutablePointer<AnyObject>.alloc(objects.count) valueBuffer.initializeFrom(objects) self.init(objects: valueBuffer, forKeys:keyBuffer, count: keys.count) keyBuffer.destroy(keys.count) valueBuffer.destroy(objects.count) keyBuffer.dealloc(keys.count) valueBuffer.dealloc(objects.count) } public override func isEqual(object: AnyObject?) -> Bool { guard let otherObject = object where otherObject is NSDictionary else { return false } let otherDictionary = otherObject as! NSDictionary return self.isEqualToDictionary(otherDictionary.bridge()) } public override var hash: Int { return self.count } public var allKeys: [AnyObject] { get { if self.dynamicType === NSDictionary.self || self.dynamicType === NSMutableDictionary.self { return _storage.keys.map { $0 } } else { var keys = [AnyObject]() let enumerator = keyEnumerator() while let key = enumerator.nextObject() { keys.append(key) } return keys } } } public var allValues: [AnyObject] { get { if self.dynamicType === NSDictionary.self || self.dynamicType === NSMutableDictionary.self { return _storage.values.map { $0 } } else { var values = [AnyObject]() let enumerator = keyEnumerator() while let key = enumerator.nextObject() { values.append(objectForKey(key)!) } return values } } } /// Alternative pseudo funnel method for fastpath fetches from dictionaries /// - Experiment: This is a draft API currently under consideration for official import into Foundation /// - Note: Since this API is under consideration it may be either removed or revised in the near future public func getObjects(inout objects: [AnyObject], inout andKeys keys: [AnyObject], count: Int) { if self.dynamicType === NSDictionary.self || self.dynamicType === NSMutableDictionary.self { for (key, value) in _storage { keys.append(key) objects.append(value) } } else { let enumerator = keyEnumerator() while let key = enumerator.nextObject() { let value = objectForKey(key)! keys.append(key) objects.append(value) } } } public subscript (key: AnyObject) -> AnyObject? { get { return objectForKey(key) } } public func allKeysForObject(anObject: AnyObject) -> [AnyObject] { var matching = Array<AnyObject>() enumerateKeysAndObjectsWithOptions([]) { key, value, _ in if value === anObject { matching.append(key) } } return matching } /// A string that represents the contents of the dictionary, formatted as /// a property list (read-only) /// /// If each key in the dictionary is an NSString object, the entries are /// listed in ascending order by key, otherwise the order in which the entries /// are listed is undefined. This property is intended to produce readable /// output for debugging purposes, not for serializing data. If you want to /// store dictionary data for later retrieval, see /// [Property List Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/Introduction/Introduction.html#//apple_ref/doc/uid/10000048i) /// and [Archives and Serializations Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Archiving/Archiving.html#//apple_ref/doc/uid/10000047i). public override var description: String { get { return descriptionWithLocale(nil) } } public var descriptionInStringsFileFormat: String { NSUnimplemented() } /// Returns a string object that represents the contents of the dictionary, /// formatted as a property list. /// /// - parameter locale: An object that specifies options used for formatting /// each of the dictionary’s keys and values; pass `nil` if you don’t /// want them formatted. public func descriptionWithLocale(locale: AnyObject?) -> String { return descriptionWithLocale(locale, indent: 0) } /// Returns a string object that represents the contents of the dictionary, /// formatted as a property list. /// /// - parameter locale: An object that specifies options used for formatting /// each of the dictionary’s keys and values; pass `nil` if you don’t /// want them formatted. /// /// - parameter level: Specifies a level of indentation, to make the output /// more readable: the indentation is (4 spaces) * level. /// /// - returns: A string object that represents the contents of the dictionary, /// formatted as a property list. public func descriptionWithLocale(locale: AnyObject?, indent level: Int) -> String { if level > 100 { return "..." } var lines = [String]() let indentation = String(count: level * 4, repeatedValue: Character(" ")) lines.append(indentation + "{") for key in self.allKeys { var line = String(count: (level + 1) * 4, repeatedValue: Character(" ")) if key is NSArray { line += (key as! NSArray).descriptionWithLocale(locale, indent: level + 1) } else if key is NSDate { line += (key as! NSDate).descriptionWithLocale(locale) } else if key is NSDecimalNumber { line += (key as! NSDecimalNumber).descriptionWithLocale(locale) } else if key is NSDictionary { line += (key as! NSDictionary).descriptionWithLocale(locale, indent: level + 1) } else if key is NSOrderedSet { line += (key as! NSOrderedSet).descriptionWithLocale(locale, indent: level + 1) } else if key is NSSet { line += (key as! NSSet).descriptionWithLocale(locale) } else { line += "\(key)" } line += " = " let object = objectForKey(key)! if object is NSArray { line += (object as! NSArray).descriptionWithLocale(locale, indent: level + 1) } else if object is NSDate { line += (object as! NSDate).descriptionWithLocale(locale) } else if object is NSDecimalNumber { line += (object as! NSDecimalNumber).descriptionWithLocale(locale) } else if object is NSDictionary { line += (object as! NSDictionary).descriptionWithLocale(locale, indent: level + 1) } else if object is NSOrderedSet { line += (object as! NSOrderedSet).descriptionWithLocale(locale, indent: level + 1) } else if object is NSSet { line += (object as! NSSet).descriptionWithLocale(locale) } else { line += "\(object)" } line += ";" lines.append(line) } lines.append(indentation + "}") return lines.joinWithSeparator("\n") } public func isEqualToDictionary(otherDictionary: [NSObject : AnyObject]) -> Bool { if count != otherDictionary.count { return false } for key in keyEnumerator() { if let otherValue = otherDictionary[key as! NSObject] as? NSObject { let value = objectForKey(key as! NSObject)! as! NSObject if otherValue != value { return false } } else { return false } } return true } public struct Generator : GeneratorType { let dictionary : NSDictionary var keyGenerator : Array<AnyObject>.Generator public mutating func next() -> (key: AnyObject, value: AnyObject)? { if let key = keyGenerator.next() { return (key, dictionary.objectForKey(key)!) } else { return nil } } init(_ dict : NSDictionary) { self.dictionary = dict self.keyGenerator = dict.allKeys.generate() } } internal struct ObjectGenerator: GeneratorType { let dictionary : NSDictionary var keyGenerator : Array<AnyObject>.Generator mutating func next() -> AnyObject? { if let key = keyGenerator.next() { return dictionary.objectForKey(key)! } else { return nil } } init(_ dict : NSDictionary) { self.dictionary = dict self.keyGenerator = dict.allKeys.generate() } } public func objectEnumerator() -> NSEnumerator { return NSGeneratorEnumerator(ObjectGenerator(self)) } public func objectsForKeys(keys: [NSObject], notFoundMarker marker: AnyObject) -> [AnyObject] { var objects = [AnyObject]() for key in keys { if let object = objectForKey(key) { objects.append(object) } else { objects.append(marker) } } return objects } public func writeToFile(path: String, atomically useAuxiliaryFile: Bool) -> Bool { NSUnimplemented() } public func writeToURL(url: NSURL, atomically: Bool) -> Bool { NSUnimplemented() } // the atomically flag is ignored if url of a type that cannot be written atomically. public func enumerateKeysAndObjectsUsingBlock(block: (NSObject, AnyObject, UnsafeMutablePointer<ObjCBool>) -> Void) { enumerateKeysAndObjectsWithOptions([], usingBlock: block) } public func enumerateKeysAndObjectsWithOptions(opts: NSEnumerationOptions, usingBlock block: (NSObject, AnyObject, UnsafeMutablePointer<ObjCBool>) -> Void) { let count = self.count var keys = [AnyObject]() var objects = [AnyObject]() getObjects(&objects, andKeys: &keys, count: count) var stop = ObjCBool(false) for idx in 0..<count { withUnsafeMutablePointer(&stop, { stop in block(keys[idx] as! NSObject, objects[idx], stop) }) if stop { break } } } public func keysSortedByValueUsingComparator(cmptr: NSComparator) -> [AnyObject] { return keysSortedByValueWithOptions([], usingComparator: cmptr) } public func keysSortedByValueWithOptions(opts: NSSortOptions, usingComparator cmptr: NSComparator) -> [AnyObject] { let sorted = allKeys.sort { lhs, rhs in return cmptr(lhs, rhs) == .OrderedSame } return sorted } public func keysOfEntriesPassingTest(predicate: (AnyObject, AnyObject, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<NSObject> { return keysOfEntriesWithOptions([], passingTest: predicate) } public func keysOfEntriesWithOptions(opts: NSEnumerationOptions, passingTest predicate: (AnyObject, AnyObject, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<NSObject> { var matching = Set<NSObject>() enumerateKeysAndObjectsWithOptions(opts) { key, value, stop in if predicate(key, value, stop) { matching.insert(key) } } return matching } override public var _cfTypeID: CFTypeID { return CFDictionaryGetTypeID() } required public convenience init(dictionaryLiteral elements: (NSObject, AnyObject)...) { var keys = [NSObject]() var values = [AnyObject]() for (key, value) in elements { keys.append(key) values.append(value) } self.init(objects: values, forKeys: keys) } } extension NSDictionary : _CFBridgable, _SwiftBridgable { internal var _cfObject: CFDictionaryRef { return unsafeBitCast(self, CFDictionaryRef.self) } internal var _swiftObject: Dictionary<NSObject, AnyObject> { var dictionary: [NSObject: AnyObject]? Dictionary._forceBridgeFromObject(self, result: &dictionary) return dictionary! } } extension NSMutableDictionary { internal var _cfMutableObject: CFMutableDictionaryRef { return unsafeBitCast(self, CFMutableDictionaryRef.self) } } extension CFDictionaryRef : _NSBridgable, _SwiftBridgable { internal var _nsObject: NSDictionary { return unsafeBitCast(self, NSDictionary.self) } internal var _swiftObject: [NSObject: AnyObject] { return _nsObject._swiftObject } } extension Dictionary : _NSBridgable, _CFBridgable { internal var _nsObject: NSDictionary { return _bridgeToObject() } internal var _cfObject: CFDictionaryRef { return _nsObject._cfObject } } public class NSMutableDictionary : NSDictionary { public func removeObjectForKey(aKey: AnyObject) { if self.dynamicType === NSDictionary.self || self.dynamicType === NSMutableDictionary.self { if let key = aKey as? NSObject { _storage.removeValueForKey(key) } // CFDictionaryRemoveValue(unsafeBitCast(self, CFMutableDictionaryRef.self), unsafeBitCast(aKey, UnsafePointer<Void>.self)) } else { NSRequiresConcreteImplementation() } } public func setObject(anObject: AnyObject, forKey aKey: NSObject) { if self.dynamicType === NSDictionary.self || self.dynamicType === NSMutableDictionary.self { _storage[aKey] = anObject // CFDictionarySetValue(unsafeBitCast(self, CFMutableDictionaryRef.self), unsafeBitCast(aKey, UnsafePointer<Void>.self), unsafeBitCast(anObject, UnsafePointer<Void>.self)) } else { NSRequiresConcreteImplementation() } } public convenience required init() { self.init(capacity: 0) } public init(capacity numItems: Int) { super.init(objects: nil, forKeys: nil, count: 0) } public convenience required init?(coder aDecoder: NSCoder) { self.init() } public required init(objects: UnsafePointer<AnyObject>, forKeys keys: UnsafePointer<NSObject>, count cnt: Int) { super.init(objects: objects, forKeys: keys, count: cnt) } public convenience init?(contentsOfFile path: String) { NSUnimplemented() } public convenience init?(contentsOfURL url: NSURL) { NSUnimplemented() } } extension NSMutableDictionary { public func addEntriesFromDictionary(otherDictionary: [NSObject : AnyObject]) { for (key, obj) in otherDictionary { setObject(obj, forKey: key) } } public func removeAllObjects() { if self.dynamicType === NSDictionary.self || self.dynamicType === NSMutableDictionary.self { _storage.removeAll() // CFDictionaryRemoveAllValues(unsafeBitCast(self, CFMutableDictionaryRef.self)) } else { for key in allKeys { removeObjectForKey(key) } } } public func removeObjectsForKeys(keyArray: [AnyObject]) { for key in keyArray { removeObjectForKey(key) } } public func setDictionary(otherDictionary: [NSObject : AnyObject]) { if self.dynamicType === NSDictionary.self || self.dynamicType === NSMutableDictionary.self { _storage = otherDictionary } else { removeAllObjects() for (key, obj) in otherDictionary { setObject(obj, forKey: key) } } } public subscript (key: NSObject) -> AnyObject? { get { return objectForKey(key) } set { if let val = newValue { setObject(val, forKey: key) } else { removeObjectForKey(key) } } } } extension NSDictionary : SequenceType { public func generate() -> Generator { return Generator(self) } } // MARK - Shared Key Sets extension NSDictionary { /* Use this method to create a key set to pass to +dictionaryWithSharedKeySet:. The keys are copied from the array and must be copyable. If the array parameter is nil or not an NSArray, an exception is thrown. If the array of keys is empty, an empty key set is returned. The array of keys may contain duplicates, which are ignored (it is undefined which object of each duplicate pair is used). As for any usage of hashing, is recommended that the keys have a well-distributed implementation of -hash, and the hash codes must satisfy the hash/isEqual: invariant. Keys with duplicate hash codes are allowed, but will cause lower performance and increase memory usage. */ public class func sharedKeySetForKeys(keys: [NSCopying]) -> AnyObject { NSUnimplemented() } } extension NSMutableDictionary { /* Create a mutable dictionary which is optimized for dealing with a known set of keys. Keys that are not in the key set can still be set into the dictionary, but that usage is not optimal. As with any dictionary, the keys must be copyable. If keyset is nil, an exception is thrown. If keyset is not an object returned by +sharedKeySetForKeys:, an exception is thrown. */ public convenience init(sharedKeySet keyset: AnyObject) { NSUnimplemented() } } extension NSDictionary : DictionaryLiteralConvertible { } extension Dictionary : Bridgeable { public func bridge() -> NSDictionary { return _nsObject } } extension NSDictionary : Bridgeable { public func bridge() -> [NSObject: AnyObject] { return _swiftObject } }
apache-2.0
343d69889d06529aa49e00ba35fb2aec
36.314788
188
0.601585
5.132098
false
false
false
false
lorentey/swift
test/Constraints/conditionally_defined_types.swift
3
12209
// RUN: %target-typecheck-verify-swift protocol P {} struct X: P {} struct Y {} protocol AssociatedType { associatedtype T } struct Z1: AssociatedType { typealias T = X } struct Z2: AssociatedType { typealias T = Y } struct SameType<T> {} extension SameType where T == X { // expected-note 13{{requirement specified as 'T' == 'X' [with T = Y]}} typealias TypeAlias1 = T typealias TypeAlias2 = Y typealias TypeAlias3<U> = (T, U) // expected-note {{requirement specified as 'T' == 'X' [with T = Y]}} struct Decl1 {} enum Decl2 {} class Decl3 {} struct Decl4<U> {} // expected-note 17 {{requirement specified as 'T' == 'X' [with T = Y]}} enum Decl5<U: P> {} // expected-note {{requirement specified as 'T' == 'X' [with T = Y]}} } let _ = SameType<X>.TypeAlias1.self let _ = SameType<X>.TypeAlias2.self let _ = SameType<X>.TypeAlias3<X>.self let _ = SameType<X>.Decl1.self let _ = SameType<X>.Decl2.self let _ = SameType<X>.Decl3.self let _ = SameType<X>.Decl4<X>.self let _ = SameType<X>.Decl5<X>.self let _ = SameType<Y>.TypeAlias1.self // expected-error {{'SameType<Y>.TypeAlias1' (aka 'X') requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.TypeAlias2.self // expected-error {{'SameType<Y>.TypeAlias2' (aka 'Y') requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.TypeAlias3<X>.self // expected-error {{'SameType<Y>.TypeAlias3' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl1.self // expected-error {{'SameType<Y>.Decl1' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl2.self // expected-error {{'SameType<Y>.Decl2' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl3.self // expected-error {{'SameType<Y>.Decl3' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl4<X>.self // expected-error {{'SameType<Y>.Decl4' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl5<X>.self // expected-error {{'SameType<Y>.Decl5' requires the types 'Y' and 'X' be equivalent}} extension SameType: AssociatedType where T == X {} // expected-note@-1 {{requirement specified as 'T' == 'X' [with T = Y]}} let _ = SameType<X>.T.self let _ = SameType<Y>.T.self // expected-error {{'SameType<Y>.T' (aka 'X') requires the types 'Y' and 'X' be equivalent}} struct Conforms<T> {} extension Conforms where T: P { typealias TypeAlias1 = T typealias TypeAlias2 = Y typealias TypeAlias3<U> = (T, U) struct Decl1 {} enum Decl2 {} class Decl3 {} struct Decl4<U> {} enum Decl5<U: P> {} } let _ = Conforms<X>.TypeAlias1.self let _ = Conforms<X>.TypeAlias2.self let _ = Conforms<X>.TypeAlias3<X>.self let _ = Conforms<X>.Decl1.self let _ = Conforms<X>.Decl2.self let _ = Conforms<X>.Decl3.self let _ = Conforms<X>.Decl4<X>.self let _ = Conforms<X>.Decl5<X>.self let _ = Conforms<Y>.TypeAlias1.self // expected-error {{type 'Y' does not conform to protocol 'P'}} let _ = Conforms<Y>.TypeAlias2.self // expected-error {{type 'Y' does not conform to protocol 'P'}} let _ = Conforms<Y>.TypeAlias3<X>.self // expected-error {{type 'Y' does not conform to protocol 'P'}} let _ = Conforms<Y>.Decl1.self // expected-error {{type 'Y' does not conform to protocol 'P'}} let _ = Conforms<Y>.Decl2.self // expected-error {{type 'Y' does not conform to protocol 'P'}} let _ = Conforms<Y>.Decl3.self // expected-error {{type 'Y' does not conform to protocol 'P'}} let _ = Conforms<Y>.Decl4<X>.self // expected-error {{type 'Y' does not conform to protocol 'P'}} let _ = Conforms<Y>.Decl5<X>.self // expected-error {{type 'Y' does not conform to protocol 'P'}} extension Conforms: AssociatedType where T: P {} let _ = Conforms<Y>.T.self // expected-error {{type 'Y' does not conform to protocol 'P'}} let _ = Conforms<X>.T.self // Now, even more nesting! extension SameType.Decl1 { typealias TypeAlias1 = T typealias TypeAlias2 = Y typealias TypeAlias3<U> = (T, U) struct Decl1 {} enum Decl2 {} class Decl3 {} struct Decl4<U> {} enum Decl5<U: P> {} } let _ = SameType<X>.Decl1.TypeAlias1.self let _ = SameType<X>.Decl1.TypeAlias2.self let _ = SameType<X>.Decl1.TypeAlias3<X>.self let _ = SameType<X>.Decl1.Decl1.self let _ = SameType<X>.Decl1.Decl2.self let _ = SameType<X>.Decl1.Decl3.self let _ = SameType<X>.Decl1.Decl4<X>.self let _ = SameType<X>.Decl1.Decl5<X>.self let _ = SameType<Y>.Decl1.TypeAlias1.self // expected-error {{'SameType<Y>.Decl1' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl1.TypeAlias2.self // expected-error {{'SameType<Y>.Decl1' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl1.TypeAlias3<X>.self // expected-error {{'SameType<Y>.Decl1' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl1.Decl1.self // expected-error {{'SameType<Y>.Decl1' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl1.Decl2.self // expected-error {{'SameType<Y>.Decl1' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl1.Decl3.self // expected-error {{'SameType<Y>.Decl1' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl1.Decl4<X>.self // expected-error {{'SameType<Y>.Decl1' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl1.Decl5<X>.self // expected-error {{'SameType<Y>.Decl1' requires the types 'Y' and 'X' be equivalent}} extension SameType.Decl4 where U == X { // expected-note 5 {{requirement specified as 'U' == 'X' [with U = Y]}} typealias TypeAlias1 = T typealias TypeAlias2 = Y typealias TypeAlias3<V> = (T, U, V) // expected-note {{requirement specified as 'U' == 'X' [with U = Y]}} struct Decl1 {} enum Decl2 {} class Decl3 {} struct Decl4<V> {} // expected-note {{requirement specified as 'U' == 'X' [with U = Y]}} enum Decl5<V: P> {} // expected-note {{requirement specified as 'U' == 'X' [with U = Y]}} } // All the combinations let _ = SameType<X>.Decl4<X>.TypeAlias1.self let _ = SameType<X>.Decl4<X>.TypeAlias2.self let _ = SameType<X>.Decl4<X>.TypeAlias3<X>.self let _ = SameType<X>.Decl4<X>.Decl1.self let _ = SameType<X>.Decl4<X>.Decl2.self let _ = SameType<X>.Decl4<X>.Decl3.self let _ = SameType<X>.Decl4<X>.Decl4<X>.self let _ = SameType<X>.Decl4<X>.Decl5<X>.self let _ = SameType<X>.Decl4<Y>.TypeAlias1.self // expected-error {{'SameType<X>.Decl4<Y>.TypeAlias1' (aka 'X') requires the types 'Y' and 'X' be equivalent}} let _ = SameType<X>.Decl4<Y>.TypeAlias2.self // expected-error {{'SameType<X>.Decl4<Y>.TypeAlias2' (aka 'Y') requires the types 'Y' and 'X' be equivalent}} let _ = SameType<X>.Decl4<Y>.TypeAlias3<X>.self // expected-error {{'SameType<X>.Decl4<Y>.TypeAlias3' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<X>.Decl4<Y>.Decl1.self // expected-error {{'SameType<X>.Decl4<Y>.Decl1' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<X>.Decl4<Y>.Decl2.self // expected-error {{'SameType<X>.Decl4<Y>.Decl2' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<X>.Decl4<Y>.Decl3.self // expected-error {{'SameType<X>.Decl4<Y>.Decl3' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<X>.Decl4<Y>.Decl4<X>.self // expected-error {{'SameType<X>.Decl4<Y>.Decl4' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<X>.Decl4<Y>.Decl5<X>.self // expected-error {{'SameType<X>.Decl4<Y>.Decl5' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl4<X>.TypeAlias1.self // expected-error {{'SameType<Y>.Decl4' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl4<X>.TypeAlias2.self // expected-error {{'SameType<Y>.Decl4' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl4<X>.TypeAlias3<X>.self // expected-error {{'SameType<Y>.Decl4' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl4<X>.Decl1.self // expected-error {{'SameType<Y>.Decl4' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl4<X>.Decl2.self // expected-error {{'SameType<Y>.Decl4' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl4<X>.Decl3.self // expected-error {{'SameType<Y>.Decl4' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl4<X>.Decl4<X>.self // expected-error {{'SameType<Y>.Decl4' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl4<X>.Decl5<X>.self // expected-error {{'SameType<Y>.Decl4' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl4<Y>.TypeAlias1.self // expected-error {{'SameType<Y>.Decl4' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl4<Y>.TypeAlias2.self // expected-error {{'SameType<Y>.Decl4' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl4<Y>.TypeAlias3<X>.self // expected-error {{'SameType<Y>.Decl4' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl4<Y>.Decl1.self // expected-error {{'SameType<Y>.Decl4' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl4<Y>.Decl2.self // expected-error {{'SameType<Y>.Decl4' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl4<Y>.Decl3.self // expected-error {{'SameType<Y>.Decl4' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl4<Y>.Decl4<X>.self // expected-error {{'SameType<Y>.Decl4' requires the types 'Y' and 'X' be equivalent}} let _ = SameType<Y>.Decl4<Y>.Decl5<X>.self // expected-error {{'SameType<Y>.Decl4' requires the types 'Y' and 'X' be equivalent}} // Finally, extra complicated: extension Conforms.Decl4 where U: AssociatedType, U.T: P { typealias TypeAlias1 = T typealias TypeAlias2 = Y typealias TypeAlias3<V> = (T, U, V) struct Decl1 {} enum Decl2 {} class Decl3 {} struct Decl4<V> {} enum Decl5<V: P> {} } let _ = Conforms<X>.Decl4<Z1>.TypeAlias1.self let _ = Conforms<X>.Decl4<Z1>.TypeAlias2.self let _ = Conforms<X>.Decl4<Z1>.TypeAlias3<X>.self let _ = Conforms<X>.Decl4<Z1>.Decl1.self let _ = Conforms<X>.Decl4<Z1>.Decl2.self let _ = Conforms<X>.Decl4<Z1>.Decl3.self let _ = Conforms<X>.Decl4<Z1>.Decl4<X>.self let _ = Conforms<X>.Decl4<Z1>.Decl5<X>.self // Two different forms of badness, corresponding to the two requirements: let _ = Conforms<X>.Decl4<Y>.TypeAlias1.self // expected-error@-1 {{type 'Y' does not conform to protocol 'AssociatedType'}} let _ = Conforms<X>.Decl4<Y>.TypeAlias2.self // expected-error@-1 {{type 'Y' does not conform to protocol 'AssociatedType'}} let _ = Conforms<X>.Decl4<Y>.TypeAlias3<X>.self // expected-error {{type 'Y' does not conform to protocol 'AssociatedType'}} let _ = Conforms<X>.Decl4<Y>.Decl1.self // expected-error@-1 {{type 'Y' does not conform to protocol 'AssociatedType'}} let _ = Conforms<X>.Decl4<Y>.Decl2.self // expected-error@-1 {{type 'Y' does not conform to protocol 'AssociatedType'}} let _ = Conforms<X>.Decl4<Y>.Decl3.self // expected-error@-1 {{type 'Y' does not conform to protocol 'AssociatedType'}} let _ = Conforms<X>.Decl4<Y>.Decl4<X>.self // expected-error {{type 'Y' does not conform to protocol 'AssociatedType'}} let _ = Conforms<X>.Decl4<Y>.Decl5<X>.self // expected-error {{type 'Y' does not conform to protocol 'AssociatedType'}} let _ = Conforms<X>.Decl4<Z2>.TypeAlias1.self // expected-error {{type 'Z2.T' (aka 'Y') does not conform to protocol 'P'}} let _ = Conforms<X>.Decl4<Z2>.TypeAlias2.self // expected-error {{type 'Z2.T' (aka 'Y') does not conform to protocol 'P'}} let _ = Conforms<X>.Decl4<Z2>.TypeAlias3<X>.self // expected-error {{type 'Z2.T' (aka 'Y') does not conform to protocol 'P'}} let _ = Conforms<X>.Decl4<Z2>.Decl1.self // expected-error {{type 'Z2.T' (aka 'Y') does not conform to protocol 'P'}} let _ = Conforms<X>.Decl4<Z2>.Decl2.self // expected-error {{type 'Z2.T' (aka 'Y') does not conform to protocol 'P'}} let _ = Conforms<X>.Decl4<Z2>.Decl3.self // expected-error {{type 'Z2.T' (aka 'Y') does not conform to protocol 'P'}} let _ = Conforms<X>.Decl4<Z2>.Decl4<X>.self // expected-error {{type 'Z2.T' (aka 'Y') does not conform to protocol 'P'}} let _ = Conforms<X>.Decl4<Z2>.Decl5<X>.self // expected-error {{type 'Z2.T' (aka 'Y') does not conform to protocol 'P'}}
apache-2.0
3600a9a41a4d3c7024bc9b5b3d264795
53.504464
155
0.670735
2.982898
false
false
false
false
blubblub/DrawerPanel
drawer/ViewController.swift
1
1856
// // ViewController.swift // drawer // // Created by Alen Kirm on 18. 08. 17. // Copyright © 2017 Alen Kirm. All rights reserved. // import UIKit class ViewController: UIViewController { private var drawer : DrawerView! override func viewDidLoad() { super.viewDidLoad() guard let drawerVC = storyboard?.instantiateViewController(withIdentifier: "DrawViewController") else { return } let drawer = self.addDrawer(viewController: drawerVC) drawer.topOffset = 150 drawer.innerView?.backgroundColor = UIColor.green // let view = UIView() // view.frame = CGRect(origin: self.view.center, size: CGSize(width: 250, height: 300)) // view.backgroundColor = .blue // // drawer = addDrawer(contentView: view) } // override func viewDidLayoutSubviews() { // super.viewDidLayoutSubviews() // // drawer.frame = CGRect(x: 0, y: self.view.frame.size.height - 80, width: self.view.frame.size.width, height: self.view.frame.size.height) // } } extension UIViewController { func addDrawer(viewController: UIViewController) -> DrawerView { let drawerView = DrawerView(frame: CGRect(x: 0, y: self.view.frame.size.height - 80, width: self.view.frame.size.width, height: self.view.frame.size.height)) drawerView.innerView = viewController.view self.addChildViewController(viewController) self.view.addSubview(drawerView) return drawerView } func addDrawer(contentView: UIView) -> DrawerView { let drawer = DrawerView(frame: contentView.frame) drawer.innerView?.backgroundColor = UIColor.red drawer.innerView = contentView self.view.addSubview(drawer) return drawer } }
mit
10dc1c6f7c81cd22f62397ab4ac15bc2
27.538462
165
0.637736
4.324009
false
false
false
false
vector-im/vector-ios
Riot/Modules/Room/TimelineCells/Styles/Bubble/Cells/VoiceMessage/Incoming/VoiceMessageIncomingBubbleCell.swift
1
1570
// // Copyright 2021 New Vector Ltd // // 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 class VoiceMessageIncomingBubbleCell: VoiceMessagePlainCell, BubbleIncomingRoomCellProtocol { override func setupViews() { super.setupViews() roomCellContentView?.innerContentViewLeadingConstraint.constant = BubbleRoomCellLayoutConstants.incomingBubbleBackgroundMargins.left roomCellContentView?.innerContentViewTrailingConstraint.constant = BubbleRoomCellLayoutConstants.incomingBubbleBackgroundMargins.right playbackController.playbackView.stackViewTrailingContraint.constant = BubbleRoomCellLayoutConstants.voiceMessagePlaybackViewRightMargin self.setupBubbleDecorations() } override func update(theme: Theme) { guard let playbackController = playbackController else { return } playbackController.playbackView.customBackgroundViewColor = theme.roomCellIncomingBubbleBackgroundColor } }
apache-2.0
092d628d6a3ca3b22c090bbe05fe4124
38.25
143
0.740764
5.432526
false
false
false
false
hardikamal/actor-platform
actor-apps/app-ios/Actor/Views/Cells/UATableViewCell.swift
24
3363
// // UATableViewCell.swift // ActorApp // // Created by Stepan Korshakov on 05.08.15. // Copyright (c) 2015 Actor LLC. All rights reserved. // import Foundation class UATableViewCell: UITableViewCell { private var topSeparator: UIView = UIView() private var bottomSeparator: UIView = UIView() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) // Cell colors backgroundColor = MainAppTheme.list.bgColor var selectedView = UIView() selectedView.backgroundColor = MainAppTheme.list.bgSelectedColor selectedBackgroundView = selectedView bottomSeparator.backgroundColor = MainAppTheme.list.separatorColor topSeparator.backgroundColor = MainAppTheme.list.separatorColor } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var topSeparatorLeftInset: CGFloat = 0.0 { didSet { setNeedsLayout() } } var bottomSeparatorLeftInset: CGFloat = 0.0 { didSet { setNeedsLayout() } } var topSeparatorVisible: Bool = false { didSet { if topSeparatorVisible == oldValue { return } if topSeparatorVisible { contentView.addSubview(topSeparator) } else { topSeparator.removeFromSuperview() } setNeedsLayout() } } var bottomSeparatorVisible: Bool = false { didSet { if bottomSeparatorVisible == oldValue { return } if bottomSeparatorVisible { contentView.addSubview(bottomSeparator) } else { bottomSeparator.removeFromSuperview() } setNeedsLayout() } } override func prepareForReuse() { bottomSeparatorVisible = false topSeparatorVisible = false super.prepareForReuse() } override func layoutSubviews() { super.layoutSubviews() if topSeparatorVisible { topSeparator.frame = CGRect(x: topSeparatorLeftInset, y: 0, width: bounds.width - topSeparatorLeftInset, height: 0.5) } if bottomSeparatorVisible { bottomSeparator.frame = CGRect(x: bottomSeparatorLeftInset, y: contentView.bounds.height - Utils.retinaPixel(), width: bounds.width - bottomSeparatorLeftInset, height: 0.5) } } override func setHighlighted(highlighted: Bool, animated: Bool) { super.setHighlighted(highlighted, animated: animated) if !highlighted { topSeparator.backgroundColor = MainAppTheme.list.separatorColor bottomSeparator.backgroundColor = MainAppTheme.list.separatorColor } } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) if !selected { topSeparator.backgroundColor = MainAppTheme.list.separatorColor bottomSeparator.backgroundColor = MainAppTheme.list.separatorColor } } }
mit
40141b2148346fa378e6571d5d59989e
28.769912
184
0.59887
5.983986
false
false
false
false
tjw/swift
test/IRGen/sil_generic_witness_methods.swift
5
4868
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir | %FileCheck %s // REQUIRES: CPU=x86_64 // FIXME: These should be SIL tests, but we can't parse generic types in SIL // yet. protocol P { func concrete_method() static func concrete_static_method() func generic_method<Z>(_ x: Z) } struct S {} // CHECK-LABEL: define hidden swiftcc void @"$S27sil_generic_witness_methods05call_D0{{[_0-9a-zA-Z]*}}F"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T, %swift.type* %U, i8** %T.P) func call_methods<T: P, U>(_ x: T, y: S, z: U) { // CHECK: [[STATIC_METHOD_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.P, i32 2 // CHECK: [[STATIC_METHOD_PTR:%.*]] = load i8*, i8** [[STATIC_METHOD_ADDR]], align 8 // CHECK: [[STATIC_METHOD:%.*]] = bitcast i8* [[STATIC_METHOD_PTR]] to void (%swift.type*, %swift.type*, i8**)* // CHECK: call swiftcc void [[STATIC_METHOD]](%swift.type* swiftself %T, %swift.type* %T, i8** %T.P) T.concrete_static_method() // CHECK: [[CONCRETE_METHOD_PTR_GEP:%.*]] = getelementptr inbounds i8*, i8** %T.P, i32 1 // CHECK: [[CONCRETE_METHOD_PTR:%.*]] = load i8*, i8** [[CONCRETE_METHOD_PTR_GEP]] // CHECK: [[CONCRETE_METHOD:%.*]] = bitcast i8* [[CONCRETE_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, i8**)* // CHECK: call swiftcc void [[CONCRETE_METHOD]](%swift.opaque* noalias nocapture swiftself {{%.*}}, %swift.type* %T, i8** %T.P) x.concrete_method() // CHECK: [[GENERIC_METHOD_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.P, i32 3 // CHECK: [[GENERIC_METHOD_PTR:%.*]] = load i8*, i8** [[GENERIC_METHOD_ADDR]], align 8 // CHECK: [[GENERIC_METHOD:%.*]] = bitcast i8* [[GENERIC_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, %swift.opaque*, %swift.type*, i8**)* // CHECK: call swiftcc void [[GENERIC_METHOD]](%swift.opaque* noalias nocapture {{.*}}, %swift.type* {{.*}} @"$S27sil_generic_witness_methods1SVMf", {{.*}} %swift.opaque* noalias nocapture swiftself {{.*}}, %swift.type* %T, i8** %T.P) x.generic_method(y) // CHECK: [[GENERIC_METHOD_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.P, i32 3 // CHECK: [[GENERIC_METHOD_PTR:%.*]] = load i8*, i8** [[GENERIC_METHOD_ADDR]], align 8 // CHECK: [[GENERIC_METHOD:%.*]] = bitcast i8* [[GENERIC_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, %swift.opaque*, %swift.type*, i8**)* // CHECK: call swiftcc void [[GENERIC_METHOD]](%swift.opaque* noalias nocapture {{.*}}, %swift.type* %U, %swift.opaque* noalias nocapture swiftself {{.*}}, %swift.type* %T, i8** %T.P) x.generic_method(z) } // CHECK-LABEL: define hidden swiftcc void @"$S27sil_generic_witness_methods017call_existential_D0{{[_0-9a-zA-Z]*}}F"(%T27sil_generic_witness_methods1PP* noalias nocapture dereferenceable({{.*}})) func call_existential_methods(_ x: P, y: S) { // CHECK: [[METADATA_ADDR:%.*]] = getelementptr inbounds %T27sil_generic_witness_methods1PP, %T27sil_generic_witness_methods1PP* [[X:%0]], i32 0, i32 1 // CHECK: [[METADATA:%.*]] = load %swift.type*, %swift.type** [[METADATA_ADDR]], align 8 // CHECK: [[WTABLE_ADDR:%.*]] = getelementptr inbounds %T27sil_generic_witness_methods1PP, %T27sil_generic_witness_methods1PP* [[X]], i32 0, i32 2 // CHECK: [[WTABLE:%.*]] = load i8**, i8*** [[WTABLE_ADDR]], align 8 // CHECK: [[CONCRETE_METHOD_PTR_GEP:%.*]] = getelementptr inbounds i8*, i8** [[WTABLE]], i32 1 // CHECK: [[CONCRETE_METHOD_PTR:%.*]] = load i8*, i8** [[CONCRETE_METHOD_PTR_GEP]], align 8 // CHECK: [[CONCRETE_METHOD:%.*]] = bitcast i8* [[CONCRETE_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, i8**)* // CHECK: call swiftcc void [[CONCRETE_METHOD]](%swift.opaque* noalias nocapture swiftself {{%.*}}, %swift.type* [[METADATA]], i8** [[WTABLE]]) x.concrete_method() // CHECK: [[METADATA_ADDR:%.*]] = getelementptr inbounds %T27sil_generic_witness_methods1PP, %T27sil_generic_witness_methods1PP* [[X]], i32 0, i32 1 // CHECK: [[METADATA:%.*]] = load %swift.type*, %swift.type** [[METADATA_ADDR]], align 8 // CHECK: [[WTABLE_ADDR:%.*]] = getelementptr inbounds %T27sil_generic_witness_methods1PP, %T27sil_generic_witness_methods1PP* [[X:%.*]], i32 0, i32 2 // CHECK: [[WTABLE:%.*]] = load i8**, i8*** [[WTABLE_ADDR]], align 8 // CHECK: [[GENERIC_METHOD_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[WTABLE]], i32 3 // CHECK: [[GENERIC_METHOD_PTR:%.*]] = load i8*, i8** [[GENERIC_METHOD_ADDR]], align 8 // CHECK: [[GENERIC_METHOD:%.*]] = bitcast i8* [[GENERIC_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, %swift.opaque*, %swift.type*, i8**)* // CHECK: call swiftcc void [[GENERIC_METHOD]](%swift.opaque* noalias nocapture {{.*}}, %swift.type* {{.*}} @"$S27sil_generic_witness_methods1SVMf", {{.*}} %swift.opaque* noalias nocapture swiftself {{%.*}}, %swift.type* [[METADATA]], i8** [[WTABLE]]) x.generic_method(y) }
apache-2.0
5f86ee03a65b76277b9b75802bd9d9f7
77.516129
253
0.637634
3.247498
false
false
false
false
dflax/amazeballs
Legacy Versions/Swift 3.x Version/AmazeBalls/Config.swift
1
4506
// // Config.swift // Amazeballs // // Created by Daniel Flax on 5/18/15. // Copyright (c) 2015 Daniel Flax. All rights reserved. // // The MIT License (MIT) // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import Foundation import UIKit //UI Constants let ScreenWidth = UIScreen.main.bounds.size.width let ScreenHeight = UIScreen.main.bounds.size.height let ScreenCenter = CGPoint(x: ScreenWidth / 2.0, y: ScreenHeight / 2.0) let ScreenSize = CGSize(width: ScreenWidth, height: ScreenHeight) let ScreenRect = CGRect(x: 0.0, y: 0.0, width: ScreenWidth, height: ScreenHeight) // Device type - true if iPad or iPad Simulator let isPad: Bool = { if (UIDevice.current.userInterfaceIdiom == .pad) { return true } else { return false } }() // Calculate the right size for the settingsViewController ball images var settingsBallSize: CGFloat { return ((ScreenWidth - 50) / 8) } //Random Integer generator func randomNumber(#minX:UInt32, #maxX:UInt32) -> Int { let result = (arc4random() % (maxX - minX + 1)) + minX return Int(result) } // Collision categories struct CollisionCategories{ static let Ball : UInt32 = 0x1 << 0 static let Floor : UInt32 = 0x1 << 1 static let EdgeBody: UInt32 = 0x1 << 2 } // Extensions to enable CGFloat casting extension Int { var cf: CGFloat { return CGFloat(self) } var f: Float { return Float(self) } } extension Float { var cf: CGFloat { return CGFloat(self) } var f: Float { return self } } extension Double { var cf: CGFloat { return CGFloat(self) } var f: Float { return Float(self) } } // Determine the device type private let DeviceList = [ /* iPod 5 */ "iPod5,1": "iPod Touch 5", /* iPhone 4 */ "iPhone3,1": "iPhone 4", "iPhone3,2": "iPhone 4", "iPhone3,3": "iPhone 4", /* iPhone 4S */ "iPhone4,1": "iPhone 4S", /* iPhone 5 */ "iPhone5,1": "iPhone 5", "iPhone5,2": "iPhone 5", /* iPhone 5C */ "iPhone5,3": "iPhone 5C", "iPhone5,4": "iPhone 5C", /* iPhone 5S */ "iPhone6,1": "iPhone 5S", "iPhone6,2": "iPhone 5S", /* iPhone 6 */ "iPhone7,2": "iPhone 6", /* iPhone 6 Plus */ "iPhone7,1": "iPhone 6 Plus", /* iPad 2 */ "iPad2,1": "iPad 2", "iPad2,2": "iPad 2", "iPad2,3": "iPad 2", "iPad2,4": "iPad 2", /* iPad 3 */ "iPad3,1": "iPad 3", "iPad3,2": "iPad 3", "iPad3,3": "iPad 3", /* iPad 4 */ "iPad3,4": "iPad 4", "iPad3,5": "iPad 4", "iPad3,6": "iPad 4", /* iPad Air */ "iPad4,1": "iPad Air", "iPad4,2": "iPad Air", "iPad4,3": "iPad Air", /* iPad Air 2 */ "iPad5,1": "iPad Air 2", "iPad5,3": "iPad Air 2", "iPad5,4": "iPad Air 2", /* iPad Mini */ "iPad2,5": "iPad Mini", "iPad2,6": "iPad Mini", "iPad2,7": "iPad Mini", /* iPad Mini 2 */ "iPad4,4": "iPad Mini", "iPad4,5": "iPad Mini", "iPad4,6": "iPad Mini", /* iPad Mini 3 */ "iPad4,7": "iPad Mini", "iPad4,8": "iPad Mini", "iPad4,9": "iPad Mini", /* Simulator */ "x86_64": "Simulator", "i386": "Simulator" ] // Extension to UIDevice. Usage: let modelName = UIDevice.currentDevice().modelName public extension UIDevice { var modelName: String { var systemInfo = utsname() uname(&systemInfo) let machine = systemInfo.machine let mirror = reflect(machine) var identifier = "" for i in 0..<mirror.count { if let value = mirror[i].1.value as? Int8, value != 0 { identifier.append(String(UnicodeScalar(UInt8(value)))) } } return DeviceList[identifier] ?? identifier } }
mit
30ed6e5a0e4aca95b75f456fc9621a1a
37.186441
106
0.652241
3.279476
false
false
false
false
banxi1988/BXCityPicker
Example/Pods/BXForm/Pod/Classes/Cells/InputCell.swift
2
1813
// // InputCell.swift // Pods // // Created by Haizhen Lee on 16/1/23. // // // Build for target uimodel import UIKit import BXModel import BXiOSUtils import PinAuto //-InputCell:stc //_[l15,y,w72](f17,cst) //_[l18,y,r15](f15,cht):f open class InputCell : StaticTableViewCell{ open let label = UILabel(frame:CGRect.zero) open let textField = UITextField(frame:CGRect.zero) public convenience init() { self.init(style: .default, reuseIdentifier: "InputCellCell") } public override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) commonInit() } open override func awakeFromNib() { super.awakeFromNib() commonInit() } var allOutlets :[UIView]{ return [label,textField] } var allUILabelOutlets :[UILabel]{ return [label] } var allUITextFieldOutlets :[UITextField]{ return [textField] } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open func commonInit(){ for childView in allOutlets{ contentView.addSubview(childView) childView.translatesAutoresizingMaskIntoConstraints = false } installConstaints() setupAttrs() } open func installConstaints(){ label.pa_centerY.install() label.pa_leading.eq(15).install() label.pa_width.eq(72).install() textField.pa_centerY.install() textField.pa_after(label, offset: sdp2dp(15)).install() textField.pa_trailing.eq(15).install() } open func setupAttrs(){ label.textAlignment = .left label.textColor = FormColors.secondaryTextColor label.font = UIFont.systemFont(ofSize: 17) textField.textColor = UIColor.darkText textField.font = UIFont.systemFont(ofSize: 17) shouldHighlight = false } }
mit
8865db1246632f2d55dc7d206b6ab325
22.545455
79
0.691671
4.019956
false
false
false
false
apple/swift-corelibs-foundation
Sources/Foundation/NSCalendar.swift
1
74761
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // @_implementationOnly import CoreFoundation internal let kCFCalendarUnitEra = CFCalendarUnit.era internal let kCFCalendarUnitYear = CFCalendarUnit.year internal let kCFCalendarUnitMonth = CFCalendarUnit.month internal let kCFCalendarUnitDay = CFCalendarUnit.day internal let kCFCalendarUnitHour = CFCalendarUnit.hour internal let kCFCalendarUnitMinute = CFCalendarUnit.minute internal let kCFCalendarUnitSecond = CFCalendarUnit.second internal let kCFCalendarUnitWeekday = CFCalendarUnit.weekday internal let kCFCalendarUnitWeekdayOrdinal = CFCalendarUnit.weekdayOrdinal internal let kCFCalendarUnitQuarter = CFCalendarUnit.quarter internal let kCFCalendarUnitWeekOfMonth = CFCalendarUnit.weekOfMonth internal let kCFCalendarUnitWeekOfYear = CFCalendarUnit.weekOfYear internal let kCFCalendarUnitYearForWeekOfYear = CFCalendarUnit.yearForWeekOfYear internal let kCFCalendarUnitNanosecond = CFCalendarUnit(rawValue: CFOptionFlags(CoreFoundation.kCFCalendarUnitNanosecond)) internal func _CFCalendarUnitRawValue(_ unit: CFCalendarUnit) -> CFOptionFlags { return unit.rawValue } internal let kCFDateFormatterNoStyle = CFDateFormatterStyle.noStyle internal let kCFDateFormatterShortStyle = CFDateFormatterStyle.shortStyle internal let kCFDateFormatterMediumStyle = CFDateFormatterStyle.mediumStyle internal let kCFDateFormatterLongStyle = CFDateFormatterStyle.longStyle internal let kCFDateFormatterFullStyle = CFDateFormatterStyle.fullStyle extension NSCalendar { public struct Identifier : RawRepresentable, Equatable, Hashable, Comparable { public private(set) var rawValue: String public init(_ rawValue: String) { self.rawValue = rawValue } public init(rawValue: String) { self.rawValue = rawValue } public static let gregorian = NSCalendar.Identifier("gregorian") public static let buddhist = NSCalendar.Identifier("buddhist") public static let chinese = NSCalendar.Identifier("chinese") public static let coptic = NSCalendar.Identifier("coptic") public static let ethiopicAmeteMihret = NSCalendar.Identifier("ethiopic") public static let ethiopicAmeteAlem = NSCalendar.Identifier("ethiopic-amete-alem") public static let hebrew = NSCalendar.Identifier("hebrew") public static let ISO8601 = NSCalendar.Identifier("iso8601") public static let indian = NSCalendar.Identifier("indian") public static let islamic = NSCalendar.Identifier("islamic") public static let islamicCivil = NSCalendar.Identifier("islamic-civil") public static let japanese = NSCalendar.Identifier("japanese") public static let persian = NSCalendar.Identifier("persian") public static let republicOfChina = NSCalendar.Identifier("roc") public static let islamicTabular = NSCalendar.Identifier("islamic-tbla") public static let islamicUmmAlQura = NSCalendar.Identifier("islamic-umalqura") } public struct Unit: OptionSet { public let rawValue: UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let era = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitEra)) public static let year = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitYear)) public static let month = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitMonth)) public static let day = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitDay)) public static let hour = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitHour)) public static let minute = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitMinute)) public static let second = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitSecond)) public static let weekday = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitWeekday)) public static let weekdayOrdinal = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitWeekdayOrdinal)) public static let quarter = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitQuarter)) public static let weekOfMonth = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitWeekOfMonth)) public static let weekOfYear = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitWeekOfYear)) public static let yearForWeekOfYear = Unit(rawValue: _CFCalendarUnitRawValue(kCFCalendarUnitYearForWeekOfYear)) public static let nanosecond = Unit(rawValue: UInt(1 << 15)) public static let calendar = Unit(rawValue: UInt(1 << 20)) public static let timeZone = Unit(rawValue: UInt(1 << 21)) internal var _cfValue: CFCalendarUnit { return CFCalendarUnit(rawValue: self.rawValue) } } public struct Options : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let wrapComponents = Options(rawValue: 1 << 0) public static let matchStrictly = Options(rawValue: 1 << 1) public static let searchBackwards = Options(rawValue: 1 << 2) public static let matchPreviousTimePreservingSmallerUnits = Options(rawValue: 1 << 8) public static let matchNextTimePreservingSmallerUnits = Options(rawValue: 1 << 9) public static let matchNextTime = Options(rawValue: 1 << 10) public static let matchFirst = Options(rawValue: 1 << 12) public static let matchLast = Options(rawValue: 1 << 13) } } extension NSCalendar.Identifier { public static func <(_ lhs: NSCalendar.Identifier, _ rhs: NSCalendar.Identifier) -> Bool { return lhs.rawValue < rhs.rawValue } } open class NSCalendar : NSObject, NSCopying, NSSecureCoding { typealias CFType = CFCalendar private var _base = _CFInfo(typeID: CFCalendarGetTypeID()) private var _identifier: UnsafeMutableRawPointer? = nil private var _locale: UnsafeMutableRawPointer? = nil private var _tz: UnsafeMutableRawPointer? = nil private var _firstWeekday: Int = 0 private var _minDaysInFirstWeek: Int = 0 private var _gregorianStart: UnsafeMutableRawPointer? = nil private var _cal: UnsafeMutableRawPointer? = nil private var _userSet_firstWeekday: Bool = false private var _userSet_minDaysInFirstWeek: Bool = false private var _userSet_gregorianStart: Bool = false internal var _cfObject: CFType { return unsafeBitCast(self, to: CFCalendar.self) } public convenience required init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } guard let calendarIdentifier = aDecoder.decodeObject(of: NSString.self, forKey: "NS.identifier") else { return nil } self.init(identifier: NSCalendar.Identifier.init(rawValue: calendarIdentifier._swiftObject)) if aDecoder.containsValue(forKey: "NS.timezone") { if let timeZone = aDecoder.decodeObject(of: NSTimeZone.self, forKey: "NS.timezone") { self.timeZone = timeZone._swiftObject } } if aDecoder.containsValue(forKey: "NS.locale") { if let locale = aDecoder.decodeObject(of: NSLocale.self, forKey: "NS.locale") { self.locale = locale._swiftObject } } self.firstWeekday = aDecoder.decodeInteger(forKey: "NS.firstwkdy") self.minimumDaysInFirstWeek = aDecoder.decodeInteger(forKey: "NS.mindays") if aDecoder.containsValue(forKey: "NS.gstartdate") { if let startDate = aDecoder.decodeObject(of: NSDate.self, forKey: "NS.gstartdate") { self.gregorianStartDate = startDate._swiftObject } } } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(self.calendarIdentifier.rawValue._bridgeToObjectiveC(), forKey: "NS.identifier") aCoder.encode(self.timeZone._nsObject, forKey: "NS.timezone") aCoder.encode(self.locale?._bridgeToObjectiveC(), forKey: "NS.locale") aCoder.encode(self.firstWeekday, forKey: "NS.firstwkdy") aCoder.encode(self.minimumDaysInFirstWeek, forKey: "NS.mindays") aCoder.encode(self.gregorianStartDate?._nsObject, forKey: "NS.gstartdate") } static public var supportsSecureCoding: Bool { return true } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { let copy = NSCalendar(identifier: calendarIdentifier)! copy.locale = locale copy.timeZone = timeZone copy.firstWeekday = firstWeekday copy.minimumDaysInFirstWeek = minimumDaysInFirstWeek copy.gregorianStartDate = gregorianStartDate return copy } open class var current: Calendar { return Calendar.current } open class var autoupdatingCurrent: Calendar { // swift-corelibs-foundation does not yet support autoupdating, but we can return the current calendar (which will not change). return Calendar.autoupdatingCurrent } public /*not inherited*/ init?(identifier calendarIdentifierConstant: Identifier) { super.init() if !_CFCalendarInitWithIdentifier(_cfObject, calendarIdentifierConstant.rawValue._cfObject) { return nil } } public init?(calendarIdentifier ident: Identifier) { super.init() if !_CFCalendarInitWithIdentifier(_cfObject, ident.rawValue._cfObject) { return nil } } internal override init() { super.init() } open override var hash: Int { return Int(bitPattern: CFHash(_cfObject)) } open override func isEqual(_ value: Any?) -> Bool { if let value = value, self === value as AnyObject { return true } if let calendar = __SwiftValue.fetch(value as AnyObject) as? NSCalendar { return calendar.calendarIdentifier == calendarIdentifier && calendar.timeZone == timeZone && calendar.locale == locale && calendar.firstWeekday == firstWeekday && calendar.minimumDaysInFirstWeek == minimumDaysInFirstWeek && calendar.gregorianStartDate == gregorianStartDate } return false } open override var description: String { return CFCopyDescription(_cfObject)._swiftObject } deinit { _CFDeinit(self) } open var calendarIdentifier: Identifier { get { return Identifier(rawValue: CFCalendarGetIdentifier(_cfObject)._swiftObject) } } /*@NSCopying*/ open var locale: Locale? { get { return CFCalendarCopyLocale(_cfObject)._swiftObject } set { CFCalendarSetLocale(_cfObject, newValue?._cfObject) } } /*@NSCopying*/ open var timeZone: TimeZone { get { return CFCalendarCopyTimeZone(_cfObject)._swiftObject } set { CFCalendarSetTimeZone(_cfObject, newValue._cfObject) } } open var firstWeekday: Int { get { return CFCalendarGetFirstWeekday(_cfObject) } set { CFCalendarSetFirstWeekday(_cfObject, CFIndex(newValue)) } } open var minimumDaysInFirstWeek: Int { get { return CFCalendarGetMinimumDaysInFirstWeek(_cfObject) } set { CFCalendarSetMinimumDaysInFirstWeek(_cfObject, CFIndex(newValue)) } } internal var gregorianStartDate: Date? { get { return CFCalendarCopyGregorianStartDate(_cfObject)?._swiftObject } set { let date = newValue as NSDate? CFCalendarSetGregorianStartDate(_cfObject, date?._cfObject) } } // Methods to return component name strings localized to the calendar's locale private final func _symbols(_ key: CFString) -> [String] { let dateFormatter = CFDateFormatterCreate(kCFAllocatorSystemDefault, locale?._cfObject, kCFDateFormatterNoStyle, kCFDateFormatterNoStyle) CFDateFormatterSetProperty(dateFormatter, kCFDateFormatterCalendarKey, _cfObject) let result = (CFDateFormatterCopyProperty(dateFormatter, key) as! NSArray)._swiftObject return result.map { return ($0 as! NSString)._swiftObject } } private final func _symbol(_ key: CFString) -> String { let dateFormatter = CFDateFormatterCreate(kCFAllocatorSystemDefault, locale?._bridgeToObjectiveC()._cfObject, kCFDateFormatterNoStyle, kCFDateFormatterNoStyle) CFDateFormatterSetProperty(dateFormatter, kCFDateFormatterCalendarKey, self._cfObject) return (CFDateFormatterCopyProperty(dateFormatter, key) as! NSString)._swiftObject } open var eraSymbols: [String] { return _symbols(kCFDateFormatterEraSymbolsKey) } open var longEraSymbols: [String] { return _symbols(kCFDateFormatterLongEraSymbolsKey) } open var monthSymbols: [String] { return _symbols(kCFDateFormatterMonthSymbolsKey) } open var shortMonthSymbols: [String] { return _symbols(kCFDateFormatterShortMonthSymbolsKey) } open var veryShortMonthSymbols: [String] { return _symbols(kCFDateFormatterVeryShortMonthSymbolsKey) } open var standaloneMonthSymbols: [String] { return _symbols(kCFDateFormatterStandaloneMonthSymbolsKey) } open var shortStandaloneMonthSymbols: [String] { return _symbols(kCFDateFormatterShortStandaloneMonthSymbolsKey) } open var veryShortStandaloneMonthSymbols: [String] { return _symbols(kCFDateFormatterVeryShortStandaloneMonthSymbolsKey) } open var weekdaySymbols: [String] { return _symbols(kCFDateFormatterWeekdaySymbolsKey) } open var shortWeekdaySymbols: [String] { return _symbols(kCFDateFormatterShortWeekdaySymbolsKey) } open var veryShortWeekdaySymbols: [String] { return _symbols(kCFDateFormatterVeryShortWeekdaySymbolsKey) } open var standaloneWeekdaySymbols: [String] { return _symbols(kCFDateFormatterStandaloneWeekdaySymbolsKey) } open var shortStandaloneWeekdaySymbols: [String] { return _symbols(kCFDateFormatterShortStandaloneWeekdaySymbolsKey) } open var veryShortStandaloneWeekdaySymbols: [String] { return _symbols(kCFDateFormatterVeryShortStandaloneWeekdaySymbolsKey) } open var quarterSymbols: [String] { return _symbols(kCFDateFormatterQuarterSymbolsKey) } open var shortQuarterSymbols: [String] { return _symbols(kCFDateFormatterShortQuarterSymbolsKey) } open var standaloneQuarterSymbols: [String] { return _symbols(kCFDateFormatterStandaloneQuarterSymbolsKey) } open var shortStandaloneQuarterSymbols: [String] { return _symbols(kCFDateFormatterShortStandaloneQuarterSymbolsKey) } open var amSymbol: String { return _symbol(kCFDateFormatterAMSymbolKey) } open var pmSymbol: String { return _symbol(kCFDateFormatterPMSymbolKey) } // Calendrical calculations open func minimumRange(of unit: Unit) -> NSRange { let r = CFCalendarGetMinimumRangeOfUnit(self._cfObject, unit._cfValue) if (r.location == kCFNotFound) { return NSRange(location: NSNotFound, length: NSNotFound) } return NSRange(location: r.location, length: r.length) } open func maximumRange(of unit: Unit) -> NSRange { let r = CFCalendarGetMaximumRangeOfUnit(_cfObject, unit._cfValue) if r.location == kCFNotFound { return NSRange(location: NSNotFound, length: NSNotFound) } return NSRange(location: r.location, length: r.length) } open func range(of smaller: Unit, in larger: Unit, for date: Date) -> NSRange { let r = CFCalendarGetRangeOfUnit(_cfObject, smaller._cfValue, larger._cfValue, date.timeIntervalSinceReferenceDate) if r.location == kCFNotFound { return NSRange(location: NSNotFound, length: NSNotFound) } return NSRange(location: r.location, length: r.length) } open func ordinality(of smaller: Unit, in larger: Unit, for date: Date) -> Int { return Int(CFCalendarGetOrdinalityOfUnit(_cfObject, smaller._cfValue, larger._cfValue, date.timeIntervalSinceReferenceDate)) } /// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer. /// The current exposed API in Foundation on Darwin platforms is: /// open func rangeOfUnit(_ unit: Unit, startDate datep: AutoreleasingUnsafeMutablePointer<NSDate?>, interval tip: UnsafeMutablePointer<NSTimeInterval>, forDate date: NSDate) -> Bool /// which is not implementable on Linux due to the lack of being able to properly implement AutoreleasingUnsafeMutablePointer. /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future open func range(of unit: Unit, for date: Date) -> DateInterval? { var start: CFAbsoluteTime = 0.0 var ti: CFTimeInterval = 0.0 let res: Bool = withUnsafeMutablePointer(to: &start) { startp in withUnsafeMutablePointer(to: &ti) { tip in return CFCalendarGetTimeRangeOfUnit(_cfObject, unit._cfValue, date.timeIntervalSinceReferenceDate, startp, tip) } } if res { return DateInterval(start: Date(timeIntervalSinceReferenceDate: start), duration: ti) } return nil } private func _convert(_ comp: Int?, type: String, vector: inout [Int32], compDesc: inout [Int8]) { if let component = comp { vector.append(Int32(component)) compDesc.append(Int8(type.utf8[type.utf8.startIndex])) } } private func _convert(_ comp: Bool?, type: String, vector: inout [Int32], compDesc: inout [Int8]) { if let component = comp { vector.append(Int32(component ? 0 : 1)) compDesc.append(Int8(type.utf8[type.utf8.startIndex])) } } private func _convert(_ comps: DateComponents) -> (Array<Int32>, Array<Int8>) { var vector = [Int32]() var compDesc = [Int8]() _convert(comps.era, type: "G", vector: &vector, compDesc: &compDesc) _convert(comps.year, type: "y", vector: &vector, compDesc: &compDesc) _convert(comps.quarter, type: "Q", vector: &vector, compDesc: &compDesc) if comps.weekOfYear != NSDateComponentUndefined { _convert(comps.weekOfYear, type: "w", vector: &vector, compDesc: &compDesc) } else { // _convert(comps.week, type: "^", vector: &vector, compDesc: &compDesc) } _convert(comps.month, type: "M", vector: &vector, compDesc: &compDesc) _convert(comps.weekOfMonth, type: "W", vector: &vector, compDesc: &compDesc) _convert(comps.yearForWeekOfYear, type: "Y", vector: &vector, compDesc: &compDesc) _convert(comps.weekday, type: "E", vector: &vector, compDesc: &compDesc) _convert(comps.weekdayOrdinal, type: "F", vector: &vector, compDesc: &compDesc) _convert(comps.isLeapMonth, type: "l", vector: &vector, compDesc: &compDesc) _convert(comps.day, type: "d", vector: &vector, compDesc: &compDesc) _convert(comps.hour, type: "H", vector: &vector, compDesc: &compDesc) _convert(comps.minute, type: "m", vector: &vector, compDesc: &compDesc) _convert(comps.second, type: "s", vector: &vector, compDesc: &compDesc) _convert(comps.nanosecond, type: "#", vector: &vector, compDesc: &compDesc) compDesc.append(0) return (vector, compDesc) } open func date(from comps: DateComponents) -> Date? { var (vector, compDesc) = _convert(comps) let oldTz = self.timeZone self.timeZone = comps.timeZone ?? timeZone var at: CFAbsoluteTime = 0.0 let res: Bool = withUnsafeMutablePointer(to: &at) { t in return vector.withUnsafeMutableBufferPointer { (vectorBuffer: inout UnsafeMutableBufferPointer<Int32>) in return _CFCalendarComposeAbsoluteTimeV(_cfObject, t, compDesc, vectorBuffer.baseAddress!, Int32(vectorBuffer.count)) } } self.timeZone = oldTz if res { return Date(timeIntervalSinceReferenceDate: at) } else { return nil } } private func _setup(_ unitFlags: Unit, field: Unit, type: String, compDesc: inout [Int8]) { if unitFlags.contains(field) { compDesc.append(Int8(type.utf8[type.utf8.startIndex])) } } private func _setup(_ unitFlags: Unit, addIsLeapMonth: Bool = true) -> [Int8] { var compDesc = [Int8]() _setup(unitFlags, field: .era, type: "G", compDesc: &compDesc) _setup(unitFlags, field: .year, type: "y", compDesc: &compDesc) _setup(unitFlags, field: .quarter, type: "Q", compDesc: &compDesc) _setup(unitFlags, field: .weekOfYear, type: "w", compDesc: &compDesc) _setup(unitFlags, field: .month, type: "M", compDesc: &compDesc) if addIsLeapMonth { _setup(unitFlags, field: .month, type: "l", compDesc: &compDesc) } _setup(unitFlags, field: .weekOfMonth, type: "W", compDesc: &compDesc) _setup(unitFlags, field: .yearForWeekOfYear, type: "Y", compDesc: &compDesc) _setup(unitFlags, field: .weekday, type: "E", compDesc: &compDesc) _setup(unitFlags, field: .weekdayOrdinal, type: "F", compDesc: &compDesc) _setup(unitFlags, field: .day, type: "d", compDesc: &compDesc) _setup(unitFlags, field: .hour, type: "H", compDesc: &compDesc) _setup(unitFlags, field: .minute, type: "m", compDesc: &compDesc) _setup(unitFlags, field: .second, type: "s", compDesc: &compDesc) _setup(unitFlags, field: .nanosecond, type: "#", compDesc: &compDesc) compDesc.append(0) return compDesc } private func _setComp(_ unitFlags: Unit, field: Unit, vector: [Int32], compIndex: inout Int, setter: (Int32) -> Void) { if unitFlags.contains(field) { setter(vector[compIndex]) compIndex += 1 } } private func _components(_ unitFlags: Unit, vector: [Int32], addIsLeapMonth: Bool = true) -> DateComponents { var compIdx = 0 var comps = DateComponents() _setComp(unitFlags, field: .era, vector: vector, compIndex: &compIdx) { comps.era = Int($0) } _setComp(unitFlags, field: .year, vector: vector, compIndex: &compIdx) { comps.year = Int($0) } _setComp(unitFlags, field: .quarter, vector: vector, compIndex: &compIdx) { comps.quarter = Int($0) } _setComp(unitFlags, field: .weekOfYear, vector: vector, compIndex: &compIdx) { comps.weekOfYear = Int($0) } _setComp(unitFlags, field: .month, vector: vector, compIndex: &compIdx) { comps.month = Int($0) } if addIsLeapMonth { _setComp(unitFlags, field: .month, vector: vector, compIndex: &compIdx) { comps.isLeapMonth = $0 != 0 } } _setComp(unitFlags, field: .weekOfMonth, vector: vector, compIndex: &compIdx) { comps.weekOfMonth = Int($0) } _setComp(unitFlags, field: .yearForWeekOfYear, vector: vector, compIndex: &compIdx) { comps.yearForWeekOfYear = Int($0) } _setComp(unitFlags, field: .weekday, vector: vector, compIndex: &compIdx) { comps.weekday = Int($0) } _setComp(unitFlags, field: .weekdayOrdinal, vector: vector, compIndex: &compIdx) { comps.weekdayOrdinal = Int($0) } _setComp(unitFlags, field: .day, vector: vector, compIndex: &compIdx) { comps.day = Int($0) } _setComp(unitFlags, field: .hour, vector: vector, compIndex: &compIdx) { comps.hour = Int($0) } _setComp(unitFlags, field: .minute, vector: vector, compIndex: &compIdx) { comps.minute = Int($0) } _setComp(unitFlags, field: .second, vector: vector, compIndex: &compIdx) { comps.second = Int($0) } _setComp(unitFlags, field: .nanosecond, vector: vector, compIndex: &compIdx) { comps.nanosecond = Int($0) } if unitFlags.contains(.calendar) { comps.calendar = self._swiftObject } if unitFlags.contains(.timeZone) { comps.timeZone = timeZone } return comps } /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// The Darwin version is not nullable but this one is since the conversion from the date and unit flags can potentially return nil open func components(_ unitFlags: Unit, from date: Date) -> DateComponents { let compDesc = _setup(unitFlags) // _CFCalendarDecomposeAbsoluteTimeV requires a bit of a funky vector layout; which does not express well in swift; this is the closest I can come up with to the required format // int32_t ints[20]; // int32_t *vector[20] = {&ints[0], &ints[1], &ints[2], &ints[3], &ints[4], &ints[5], &ints[6], &ints[7], &ints[8], &ints[9], &ints[10], &ints[11], &ints[12], &ints[13], &ints[14], &ints[15], &ints[16], &ints[17], &ints[18], &ints[19]}; var ints = [Int32](repeating: 0, count: 20) let res = ints.withUnsafeMutableBufferPointer { (intArrayBuffer: inout UnsafeMutableBufferPointer<Int32>) -> Bool in var vector: [UnsafeMutablePointer<Int32>] = (0..<20).map { idx in intArrayBuffer.baseAddress!.advanced(by: idx) } return vector.withUnsafeMutableBufferPointer { (vecBuffer: inout UnsafeMutableBufferPointer<UnsafeMutablePointer<Int32>>) in return _CFCalendarDecomposeAbsoluteTimeV(_cfObject, date.timeIntervalSinceReferenceDate, compDesc, vecBuffer.baseAddress!, Int32(compDesc.count - 1)) } } if res { return _components(unitFlags, vector: ints) } fatalError() } open func date(byAdding comps: DateComponents, to date: Date, options opts: Options = []) -> Date? { var (vector, compDesc) = _convert(comps) var at: CFAbsoluteTime = date.timeIntervalSinceReferenceDate let res: Bool = withUnsafeMutablePointer(to: &at) { t in let count = Int32(vector.count) return vector.withUnsafeMutableBufferPointer { (vectorBuffer: inout UnsafeMutableBufferPointer<Int32>) in return _CFCalendarAddComponentsV(_cfObject, t, CFOptionFlags(opts.rawValue), compDesc, vectorBuffer.baseAddress!, count) } } if res { return Date(timeIntervalSinceReferenceDate: at) } return nil } open func components(_ unitFlags: Unit, from startingDate: Date, to resultDate: Date, options opts: Options = []) -> DateComponents { let validUnitFlags: NSCalendar.Unit = [ .era, .year, .month, .day, .hour, .minute, .second, .nanosecond, .weekOfYear, .weekOfMonth, .yearForWeekOfYear, .weekday, .weekdayOrdinal ] let invalidUnitFlags: NSCalendar.Unit = [ .quarter, .timeZone, .calendar] // Mask off the unsupported fields let newUnitFlags = Unit(rawValue: unitFlags.rawValue & validUnitFlags.rawValue) let compDesc = _setup(newUnitFlags, addIsLeapMonth: false) var ints = [Int32](repeating: 0, count: 20) let res = ints.withUnsafeMutableBufferPointer { (intArrayBuffer: inout UnsafeMutableBufferPointer<Int32>) -> Bool in var vector: [UnsafeMutablePointer<Int32>] = (0..<20).map { idx in return intArrayBuffer.baseAddress!.advanced(by: idx) } let count = Int32(vector.count) return vector.withUnsafeMutableBufferPointer { (vecBuffer: inout UnsafeMutableBufferPointer<UnsafeMutablePointer<Int32>>) in return _CFCalendarGetComponentDifferenceV(_cfObject, startingDate.timeIntervalSinceReferenceDate, resultDate.timeIntervalSinceReferenceDate, CFOptionFlags(opts.rawValue), compDesc, vecBuffer.baseAddress!, count) } } if res { let emptyUnitFlags = Unit(rawValue: unitFlags.rawValue & invalidUnitFlags.rawValue) var components = _components(newUnitFlags, vector: ints, addIsLeapMonth: false) // quarter always gets set to zero if requested in the output if emptyUnitFlags.contains(.quarter) { components.quarter = 0 } // isLeapMonth is always set components.isLeapMonth = false return components } fatalError() } /* This API is a convenience for getting era, year, month, and day of a given date. Pass NULL for a NSInteger pointer parameter if you don't care about that value. */ open func getEra(_ eraValuePointer: UnsafeMutablePointer<Int>?, year yearValuePointer: UnsafeMutablePointer<Int>?, month monthValuePointer: UnsafeMutablePointer<Int>?, day dayValuePointer: UnsafeMutablePointer<Int>?, from date: Date) { let comps = components([.era, .year, .month, .day], from: date) eraValuePointer?.pointee = comps.era ?? NSDateComponentUndefined yearValuePointer?.pointee = comps.year ?? NSDateComponentUndefined monthValuePointer?.pointee = comps.month ?? NSDateComponentUndefined dayValuePointer?.pointee = comps.day ?? NSDateComponentUndefined } /* This API is a convenience for getting era, year for week-of-year calculations, week of year, and weekday of a given date. Pass NULL for a NSInteger pointer parameter if you don't care about that value. */ open func getEra(_ eraValuePointer: UnsafeMutablePointer<Int>?, yearForWeekOfYear yearValuePointer: UnsafeMutablePointer<Int>?, weekOfYear weekValuePointer: UnsafeMutablePointer<Int>?, weekday weekdayValuePointer: UnsafeMutablePointer<Int>?, from date: Date) { let comps = components([.era, .yearForWeekOfYear, .weekOfYear, .weekday], from: date) eraValuePointer?.pointee = comps.era ?? NSDateComponentUndefined yearValuePointer?.pointee = comps.yearForWeekOfYear ?? NSDateComponentUndefined weekValuePointer?.pointee = comps.weekOfYear ?? NSDateComponentUndefined weekdayValuePointer?.pointee = comps.weekday ?? NSDateComponentUndefined } /* This API is a convenience for getting hour, minute, second, and nanoseconds of a given date. Pass NULL for a NSInteger pointer parameter if you don't care about that value. */ open func getHour(_ hourValuePointer: UnsafeMutablePointer<Int>?, minute minuteValuePointer: UnsafeMutablePointer<Int>?, second secondValuePointer: UnsafeMutablePointer<Int>?, nanosecond nanosecondValuePointer: UnsafeMutablePointer<Int>?, from date: Date) { let comps = components([.hour, .minute, .second, .nanosecond], from: date) hourValuePointer?.pointee = comps.hour ?? NSDateComponentUndefined minuteValuePointer?.pointee = comps.minute ?? NSDateComponentUndefined secondValuePointer?.pointee = comps.second ?? NSDateComponentUndefined nanosecondValuePointer?.pointee = comps.nanosecond ?? NSDateComponentUndefined } /* Get just one component's value. */ open func component(_ unit: Unit, from date: Date) -> Int { let comps = components(unit, from: date) if let res = comps.value(for: Calendar._fromCalendarUnit(unit)) { return res } else { return NSDateComponentUndefined } } /* Create a date with given components. Current era is assumed. */ open func date(era eraValue: Int, year yearValue: Int, month monthValue: Int, day dayValue: Int, hour hourValue: Int, minute minuteValue: Int, second secondValue: Int, nanosecond nanosecondValue: Int) -> Date? { var comps = DateComponents() comps.era = eraValue comps.year = yearValue comps.month = monthValue comps.day = dayValue comps.hour = hourValue comps.minute = minuteValue comps.second = secondValue comps.nanosecond = nanosecondValue return date(from: comps) } /* Create a date with given components. Current era is assumed. */ open func date(era eraValue: Int, yearForWeekOfYear yearValue: Int, weekOfYear weekValue: Int, weekday weekdayValue: Int, hour hourValue: Int, minute minuteValue: Int, second secondValue: Int, nanosecond nanosecondValue: Int) -> Date? { var comps = DateComponents() comps.era = eraValue comps.yearForWeekOfYear = yearValue comps.weekOfYear = weekValue comps.weekday = weekdayValue comps.hour = hourValue comps.minute = minuteValue comps.second = secondValue comps.nanosecond = nanosecondValue return date(from: comps) } /* This API returns the first moment date of a given date. Pass in [NSDate date], for example, if you want the start of "today". If there were two midnights, it returns the first. If there was none, it returns the first moment that did exist. */ open func startOfDay(for date: Date) -> Date { return range(of: .day, for: date)!.start } /* This API returns all the date components of a date, as if in a given time zone (instead of the receiving calendar's time zone). The time zone overrides the time zone of the NSCalendar for the purposes of this calculation. Note: if you want "date information in a given time zone" in order to display it, you should use NSDateFormatter to format the date. */ /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// The Darwin version is not nullable but this one is since the conversion from the date and unit flags can potentially return nil open func components(in timezone: TimeZone, from date: Date) -> DateComponents { let oldTz = self.timeZone self.timeZone = timezone let comps = components([.era, .year, .month, .day, .hour, .minute, .second, .nanosecond, .weekday, .weekdayOrdinal, .quarter, .weekOfMonth, .weekOfYear, .yearForWeekOfYear, .calendar, .timeZone], from: date) self.timeZone = oldTz return comps } /* This API compares the given dates down to the given unit, reporting them equal if they are the same in the given unit and all larger units, otherwise either less than or greater than. */ open func compare(_ date1: Date, to date2: Date, toUnitGranularity unit: Unit) -> ComparisonResult { switch (unit) { case .calendar: return .orderedSame case .timeZone: return .orderedSame case .day: fallthrough case .hour: let range = self.range(of: unit, for: date1) let ats = range!.start.timeIntervalSinceReferenceDate let at2 = date2.timeIntervalSinceReferenceDate if ats <= at2 && at2 < ats + range!.duration { return .orderedSame } if at2 < ats { return .orderedDescending } return .orderedAscending case .minute: var int1 = 0.0 var int2 = 0.0 modf(date1.timeIntervalSinceReferenceDate, &int1) modf(date2.timeIntervalSinceReferenceDate, &int2) int1 = floor(int1 / 60.0) int2 = floor(int2 / 60.0) if int1 == int2 { return .orderedSame } if int2 < int1 { return .orderedDescending } return .orderedAscending case .second: var int1 = 0.0 var int2 = 0.0 modf(date1.timeIntervalSinceReferenceDate, &int1) modf(date2.timeIntervalSinceReferenceDate, &int2) if int1 == int2 { return .orderedSame } if int2 < int1 { return .orderedDescending } return .orderedAscending case .nanosecond: var int1 = 0.0 var int2 = 0.0 let frac1 = modf(date1.timeIntervalSinceReferenceDate, &int1) let frac2 = modf(date2.timeIntervalSinceReferenceDate, &int2) int1 = floor(frac1 * 1000000000.0) int2 = floor(frac2 * 1000000000.0) if int1 == int2 { return .orderedSame } if int2 < int1 { return .orderedDescending } return .orderedAscending default: break } let calendarUnits1: [Unit] = [.era, .year, .month, .day] let calendarUnits2: [Unit] = [.era, .year, .month, .weekdayOrdinal, .day] let calendarUnits3: [Unit] = [.era, .year, .month, .weekOfMonth, .weekday] let calendarUnits4: [Unit] = [.era, .yearForWeekOfYear, .weekOfYear, .weekday] var units: [Unit] if unit == .yearForWeekOfYear || unit == .weekOfYear { units = calendarUnits4 } else if unit == .weekdayOrdinal { units = calendarUnits2 } else if unit == .weekday || unit == .weekOfMonth { units = calendarUnits3 } else { units = calendarUnits1 } // TODO: verify that the return value here is never going to be nil; it seems like it may - thusly making the return value here optional which would result in sadness and regret let reducedUnits = units.reduce(Unit()) { $0.union($1) } let comp1 = components(reducedUnits, from: date1) let comp2 = components(reducedUnits, from: date2) for testedUnit in units { let value1 = comp1.value(for: Calendar._fromCalendarUnit(testedUnit)) let value2 = comp2.value(for: Calendar._fromCalendarUnit(testedUnit)) if value1! > value2! { return .orderedDescending } else if value1! < value2! { return .orderedAscending } if testedUnit == .month && calendarIdentifier == .chinese { if let leap1 = comp1.isLeapMonth { if let leap2 = comp2.isLeapMonth { if !leap1 && leap2 { return .orderedAscending } else if leap1 && !leap2 { return .orderedDescending } } } } if testedUnit == unit { return .orderedSame } } return .orderedSame } /* This API compares the given dates down to the given unit, reporting them equal if they are the same in the given unit and all larger units. */ open func isDate(_ date1: Date, equalTo date2: Date, toUnitGranularity unit: Unit) -> Bool { return compare(date1, to: date2, toUnitGranularity: unit) == .orderedSame } /* This API compares the Days of the given dates, reporting them equal if they are in the same Day. */ open func isDate(_ date1: Date, inSameDayAs date2: Date) -> Bool { return compare(date1, to: date2, toUnitGranularity: .day) == .orderedSame } /* This API reports if the date is within "today". */ open func isDateInToday(_ date: Date) -> Bool { return compare(date, to: Date(), toUnitGranularity: .day) == .orderedSame } /* This API reports if the date is within "yesterday". */ open func isDateInYesterday(_ date: Date) -> Bool { if let interval = range(of: .day, for: Date()) { let inYesterday = interval.start - 60.0 return compare(date, to: inYesterday, toUnitGranularity: .day) == .orderedSame } else { return false } } /* This API reports if the date is within "tomorrow". */ open func isDateInTomorrow(_ date: Date) -> Bool { if let interval = range(of: .day, for: Date()) { let inTomorrow = interval.end + 60.0 return compare(date, to: inTomorrow, toUnitGranularity: .day) == .orderedSame } else { return false } } /* This API reports if the date is within a weekend period, as defined by the calendar and calendar's locale. */ open func isDateInWeekend(_ date: Date) -> Bool { return _CFCalendarIsDateInWeekend(_cfObject, date._cfObject) } /// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer. /// The current exposed API in Foundation on Darwin platforms is: /// open func rangeOfWeekendStartDate(_ datep: AutoreleasingUnsafeMutablePointer<NSDate?>, interval tip: UnsafeMutablePointer<NSTimeInterval>, containingDate date: NSDate) -> Bool /// which is not implementable on Linux due to the lack of being able to properly implement AutoreleasingUnsafeMutablePointer. /// Find the range of the weekend around the given date, returned via two by-reference parameters. /// Returns nil if the given date is not in a weekend. /// - Note: A given entire Day within a calendar is not necessarily all in a weekend or not; weekends can start in the middle of a Day in some calendars and locales. /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future open func range(ofWeekendContaining date: Date) -> DateInterval? { if let next = nextWeekendAfter(date, options: []) { if let prev = nextWeekendAfter(next.start, options: .searchBackwards) { if prev.start <= date && date < prev.end /* exclude the end since it's the start of the next day */ { return prev } } } return nil } /// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer. /// The current exposed API in Foundation on Darwin platforms is: /// open func nextWeekendStartDate(_ datep: AutoreleasingUnsafeMutablePointer<NSDate?>, interval tip: UnsafeMutablePointer<NSTimeInterval>, options: Options, afterDate date: NSDate) -> Bool /// Returns the range of the next weekend, via two by-reference parameters, which starts strictly after the given date. /// The .SearchBackwards option can be used to find the previous weekend range strictly before the date. /// Returns nil if there are no such things as weekend in the calendar and its locale. /// - Note: A given entire Day within a calendar is not necessarily all in a weekend or not; weekends can start in the middle of a Day in some calendars and locales. /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future open func nextWeekendAfter(_ date: Date, options: Options) -> DateInterval? { var range = _CFCalendarWeekendRange() let res = withUnsafeMutablePointer(to: &range) { rangep in return _CFCalendarGetNextWeekend(_cfObject, rangep) } if res { var comp = DateComponents() comp.weekday = range.start if let nextStart = nextDate(after: date, matching: comp, options: options.union(.matchNextTime)) { let start = startOfDay(for: nextStart + range.onsetTime) comp.weekday = range.end if let nextEnd = nextDate(after: start, matching: comp, options: .matchNextTime) { var end = nextEnd if range.ceaseTime > 0 { end = end + range.ceaseTime } else { if let dayEnd = self.range(of: .day, for: end) { end = startOfDay(for: dayEnd.end) } else { return nil } } return DateInterval(start: start, end: end) } } } return nil } /* This API returns the difference between two dates specified as date components. For units which are not specified in each NSDateComponents, but required to specify an absolute date, the base value of the unit is assumed. For example, for an NSDateComponents with just a Year and a Month specified, a Day of 1, and an Hour, Minute, Second, and Nanosecond of 0 are assumed. Calendrical calculations with unspecified Year or Year value prior to the start of a calendar are not advised. For each date components object, if its time zone property is set, that time zone is used for it; if the calendar property is set, that is used rather than the receiving calendar, and if both the calendar and time zone are set, the time zone property value overrides the time zone of the calendar property. No options are currently defined; pass 0. */ open func components(_ unitFlags: Unit, from startingDateComp: DateComponents, to resultDateComp: DateComponents, options: Options = []) -> DateComponents { var startDate: Date? var toDate: Date? if let startCalendar = startingDateComp.calendar { startDate = startCalendar.date(from: startingDateComp) } else { startDate = date(from: startingDateComp) } if let toCalendar = resultDateComp.calendar { toDate = toCalendar.date(from: resultDateComp) } else { toDate = date(from: resultDateComp) } if let start = startDate { if let end = toDate { return components(unitFlags, from: start, to: end, options: options) } } fatalError() } /* This API returns a new NSDate object representing the date calculated by adding an amount of a specific component to a given date. The NSCalendarWrapComponents option specifies if the component should be incremented and wrap around to zero/one on overflow, and should not cause higher units to be incremented. */ open func date(byAdding unit: Unit, value: Int, to date: Date, options: Options = []) -> Date? { var comps = DateComponents() comps.setValue(value, for: Calendar._fromCalendarUnit(unit)) return self.date(byAdding: comps, to: date, options: options) } /* This method computes the dates which match (or most closely match) a given set of components, and calls the block once for each of them, until the enumeration is stopped. There will be at least one intervening date which does not match all the components (or the given date itself must not match) between the given date and any result. If the NSCalendarSearchBackwards option is used, this method finds the previous match before the given date. The intent is that the same matches as for a forwards search will be found (that is, if you are enumerating forwards or backwards for each hour with minute "27", the seconds in the date you will get in forwards search would obviously be 00, and the same will be true in a backwards search in order to implement this rule. Similarly for DST backwards jumps which repeats times, you'll get the first match by default, where "first" is defined from the point of view of searching forwards. So, when searching backwards looking for a particular hour, with no minute and second specified, you don't get a minute and second of 59:59 for the matching hour (which would be the nominal first match within a given hour, given the other rules here, when searching backwards). If the NSCalendarMatchStrictly option is used, the algorithm travels as far forward or backward as necessary looking for a match, but there are ultimately implementation-defined limits in how far distant the search will go. If the NSCalendarMatchStrictly option is not specified, the algorithm searches up to the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument. If you want to find the next Feb 29 in the Gregorian calendar, for example, you have to specify the NSCalendarMatchStrictly option to guarantee finding it. If an exact match is not possible, and requested with the NSCalendarMatchStrictly option, nil is passed to the block and the enumeration ends. (Logically, since an exact match searches indefinitely into the future, if no match is found there's no point in continuing the enumeration.) If the NSCalendarMatchStrictly option is NOT used, exactly one option from the set {NSCalendarMatchPreviousTimePreservingSmallerUnits, NSCalendarMatchNextTimePreservingSmallerUnits, NSCalendarMatchNextTime} must be specified, or an illegal argument exception will be thrown. If the NSCalendarMatchPreviousTimePreservingSmallerUnits option is specified, and there is no matching time before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the previous existing value of the missing unit and preserves the lower units' values (e.g., no 2:37am results in 1:37am, if that exists). If the NSCalendarMatchNextTimePreservingSmallerUnits option is specified, and there is no matching time before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the next existing value of the missing unit and preserves the lower units' values (e.g., no 2:37am results in 3:37am, if that exists). If the NSCalendarMatchNextTime option is specified, and there is no matching time before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the next existing time which exists (e.g., no 2:37am results in 3:00am, if that exists). If the NSCalendarMatchFirst option is specified, and there are two or more matching times (all the components are the same, including isLeapMonth) before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the first occurrence. If the NSCalendarMatchLast option is specified, and there are two or more matching times (all the components are the same, including isLeapMonth) before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the last occurrence. If neither the NSCalendarMatchFirst or NSCalendarMatchLast option is specified, the default behavior is to act as if NSCalendarMatchFirst was specified. There is no option to return middle occurrences of more than two occurrences of a matching time, if such exist. Result dates have an integer number of seconds (as if 0 was specified for the nanoseconds property of the NSDateComponents matching parameter), unless a value was set in the nanoseconds property, in which case the result date will have that number of nanoseconds (or as close as possible with floating point numbers). The enumeration is stopped by setting *stop = YES in the block and return. It is not necessary to set *stop to NO to keep the enumeration going. */ open func enumerateDates(startingAfter start: Date, matching comps: DateComponents, options opts: NSCalendar.Options = [], using block: (Date?, Bool, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) { if !verifyCalendarOptions(opts) { return } withoutActuallyEscaping(block) { (nonescapingBlock) in _CFCalendarEnumerateDates(_cfObject, start._cfObject, comps._createCFDateComponents(), CFOptionFlags(opts.rawValue)) { (cfDate, exact, stop) in guard let cfDate = cfDate else { stop.pointee = true return } var ourStop: ObjCBool = false nonescapingBlock(cfDate._swiftObject, exact, &ourStop) if ourStop.boolValue { stop.pointee = true } } } } private func verifyCalendarOptions(_ options: NSCalendar.Options) -> Bool { var optionsAreValid = true let matchStrictly = options.contains(.matchStrictly) let matchPrevious = options.contains(.matchPreviousTimePreservingSmallerUnits) let matchNextKeepSmaller = options.contains(.matchNextTimePreservingSmallerUnits) let matchNext = options.contains(.matchNextTime) let matchFirst = options.contains(.matchFirst) let matchLast = options.contains(.matchLast) if matchStrictly && (matchPrevious || matchNextKeepSmaller || matchNext) { // We can't throw here because we've never thrown on this case before, even though it is technically an invalid case. The next best thing is to return. optionsAreValid = false } if !matchStrictly { if (matchPrevious && matchNext) || (matchPrevious && matchNextKeepSmaller) || (matchNext && matchNextKeepSmaller) || (!matchPrevious && !matchNext && !matchNextKeepSmaller) { fatalError("Exactly one option from the set {NSCalendarMatchPreviousTimePreservingSmallerUnits, NSCalendarMatchNextTimePreservingSmallerUnits, NSCalendarMatchNextTime} must be specified.") } } if (matchFirst && matchLast) { fatalError("Only one option from the set {NSCalendarMatchFirst, NSCalendarMatchLast} can be specified.") } return optionsAreValid } /* This method computes the next date which matches (or most closely matches) a given set of components. The general semantics follow those of the -enumerateDatesStartingAfterDate:... method above. To compute a sequence of results, use the -enumerateDatesStartingAfterDate:... method above, rather than looping and calling this method with the previous loop iteration's result. */ open func nextDate(after date: Date, matching comps: DateComponents, options: Options = []) -> Date? { var result: Date? enumerateDates(startingAfter: date, matching: comps, options: options) { date, exactMatch, stop in result = date stop.pointee = true } return result } /* This API returns a new NSDate object representing the date found which matches a specific component value. The general semantics follow those of the -enumerateDatesStartingAfterDate:... method above. To compute a sequence of results, use the -enumerateDatesStartingAfterDate:... method above, rather than looping and calling this method with the previous loop iteration's result. */ open func nextDate(after date: Date, matching unit: Unit, value: Int, options: Options = []) -> Date? { var comps = DateComponents() comps.setValue(value, for: Calendar._fromCalendarUnit(unit)) return nextDate(after:date, matching: comps, options: options) } /* This API returns a new NSDate object representing the date found which matches the given hour, minute, and second values. The general semantics follow those of the -enumerateDatesStartingAfterDate:... method above. To compute a sequence of results, use the -enumerateDatesStartingAfterDate:... method above, rather than looping and calling this method with the previous loop iteration's result. */ open func nextDate(after date: Date, matchingHour hourValue: Int, minute minuteValue: Int, second secondValue: Int, options: Options = []) -> Date? { var comps = DateComponents() comps.hour = hourValue comps.minute = minuteValue comps.second = secondValue return nextDate(after: date, matching: comps, options: options) } /* This API returns a new NSDate object representing the date calculated by setting a specific component to a given time, and trying to keep lower components the same. If the unit already has that value, this may result in a date which is the same as the given date. Changing a component's value often will require higher or coupled components to change as well. For example, setting the Weekday to Thursday usually will require the Day component to change its value, and possibly the Month and Year as well. If no such time exists, the next available time is returned (which could, for example, be in a different day, week, month, ... than the nominal target date). Setting a component to something which would be inconsistent forces other units to change; for example, setting the Weekday to Thursday probably shifts the Day and possibly Month and Year. The specific behaviors here are as yet unspecified; for example, if I change the weekday to Thursday, does that move forward to the next, backward to the previous, or to the nearest Thursday? A likely rule is that the algorithm will try to produce a result which is in the next-larger unit to the one given (there's a table of this mapping at the top of this document). So for the "set to Thursday" example, find the Thursday in the Week in which the given date resides (which could be a forwards or backwards move, and not necessarily the nearest Thursday). For forwards or backwards behavior, one can use the -nextDateAfterDate:matchingUnit:value:options: method above. */ open func date(bySettingUnit unit: Unit, value v: Int, of date: Date, options opts: Options = []) -> Date? { let currentValue = component(unit, from: date) if currentValue == v { return date } var targetComp = DateComponents() targetComp.setValue(v, for: Calendar._fromCalendarUnit(unit)) var result: Date? enumerateDates(startingAfter: date, matching: targetComp, options: .matchNextTime) { date, match, stop in result = date stop.pointee = true } return result } /* This API returns a new NSDate object representing the date calculated by setting hour, minute, and second to a given time. If no such time exists, the next available time is returned (which could, for example, be in a different day than the nominal target date). The intent is to return a date on the same day as the original date argument. This may result in a date which is earlier than the given date, of course. */ open func date(bySettingHour h: Int, minute m: Int, second s: Int, of date: Date, options opts: Options = []) -> Date? { if let range = range(of: .day, for: date) { var comps = DateComponents() comps.hour = h comps.minute = m comps.second = s var options: Options = .matchNextTime options.formUnion(opts.contains(.matchLast) ? .matchLast : .matchFirst) if opts.contains(.matchStrictly) { options.formUnion(.matchStrictly) } if let result = nextDate(after: range.start - 0.5, matching: comps, options: options) { if result.compare(range.start) == .orderedAscending { return nextDate(after: range.start, matching: comps, options: options) } return result } } return nil } /* This API returns YES if the date has all the matched components. Otherwise, it returns NO. It is useful to test the return value of the -nextDateAfterDate:matchingUnit:value:options:, to find out if the components were obeyed or if the method had to fudge the result value due to missing time. */ open func date(_ date: Date, matchesComponents components: DateComponents) -> Bool { let units: [Unit] = [.era, .year, .month, .day, .hour, .minute, .second, .weekday, .weekdayOrdinal, .quarter, .weekOfMonth, .weekOfYear, .yearForWeekOfYear, .nanosecond] var unitFlags: Unit = [] for unit in units { if components.value(for: Calendar._fromCalendarUnit(unit)) != NSDateComponentUndefined { unitFlags.formUnion(unit) } } if unitFlags == [] { if components.isLeapMonth != nil { let comp = self.components(.month, from: date) if let leap = comp.isLeapMonth { return leap } return false } } let comp = self.components(unitFlags, from: date) var compareComp = comp var tempComp = components tempComp.isLeapMonth = comp.isLeapMonth if let nanosecond = comp.value(for: .nanosecond) { if labs(numericCast(nanosecond - tempComp.value(for: .nanosecond)!)) > 500 { return false } else { compareComp.nanosecond = 0 tempComp.nanosecond = 0 } return tempComp == compareComp } return false } } /// MARK: Current calendar. internal class _NSCopyOnWriteCalendar: NSCalendar { private let lock = NSLock() private var needsLocking_isMutated: Bool private var needsLocking_backingCalendar: NSCalendar override var _cfObject: CFCalendar { copyBackingCalendarIfNeededWithMutation { _ in } return self.backingCalendar._cfObject } var backingCalendar: NSCalendar { lock.lock() let it = needsLocking_backingCalendar lock.unlock() return it } init(backingCalendar: NSCalendar) { self.needsLocking_isMutated = false self.needsLocking_backingCalendar = backingCalendar super.init() } public convenience required init?(coder aDecoder: NSCoder) { fatalError() // Encoding } override var classForCoder: AnyClass { return NSCalendar.self } override func encode(with aCoder: NSCoder) { backingCalendar.encode(with: aCoder) } override func copy(with zone: NSZone? = nil) -> Any { return backingCalendar.copy(with: zone) } // -- Mutating the current calendar private func copyBackingCalendarIfNeededWithMutation(_ block: (NSCalendar) -> Void) { lock.lock() if !needsLocking_isMutated { needsLocking_isMutated = true needsLocking_backingCalendar = needsLocking_backingCalendar.copy() as! NSCalendar } block(needsLocking_backingCalendar) lock.unlock() } override var firstWeekday: Int { get { return backingCalendar.firstWeekday } set { copyBackingCalendarIfNeededWithMutation { $0.firstWeekday = newValue } } } override var locale: Locale? { get { return backingCalendar.locale } set { copyBackingCalendarIfNeededWithMutation { $0.locale = newValue } } } override var timeZone: TimeZone { get { return backingCalendar.timeZone } set { copyBackingCalendarIfNeededWithMutation { $0.timeZone = newValue } } } override var minimumDaysInFirstWeek: Int { get { return backingCalendar.minimumDaysInFirstWeek } set { copyBackingCalendarIfNeededWithMutation { $0.minimumDaysInFirstWeek = newValue } } } override var gregorianStartDate: Date? { get { return backingCalendar.gregorianStartDate } set { copyBackingCalendarIfNeededWithMutation { $0.gregorianStartDate = newValue } } } override func isEqual(_ value: Any?) -> Bool { return backingCalendar.isEqual(value) } override var hash: Int { return backingCalendar.hashValue } // Delegation: override var calendarIdentifier: NSCalendar.Identifier { return backingCalendar.calendarIdentifier } override func minimumRange(of unit: NSCalendar.Unit) -> NSRange { return backingCalendar.minimumRange(of: unit) } override func maximumRange(of unit: NSCalendar.Unit) -> NSRange { return backingCalendar.maximumRange(of: unit) } override func range(of smaller: NSCalendar.Unit, in larger: NSCalendar.Unit, for date: Date) -> NSRange { return backingCalendar.range(of: smaller, in: larger, for: date) } override func ordinality(of smaller: NSCalendar.Unit, in larger: NSCalendar.Unit, for date: Date) -> Int { return backingCalendar.ordinality(of: smaller, in: larger, for: date) } override func range(of unit: NSCalendar.Unit, for date: Date) -> DateInterval? { return backingCalendar.range(of: unit, for: date) } override func date(from comps: DateComponents) -> Date? { return backingCalendar.date(from: comps) } override func component(_ unit: NSCalendar.Unit, from date: Date) -> Int { return backingCalendar.component(unit, from: date) } override func date(byAdding comps: DateComponents, to date: Date, options opts: NSCalendar.Options = []) -> Date? { return backingCalendar.date(byAdding: comps, to: date, options: opts) } override func components(_ unitFlags: NSCalendar.Unit, from startingDateComp: DateComponents, to resultDateComp: DateComponents, options: NSCalendar.Options = []) -> DateComponents { return backingCalendar.components(unitFlags, from: startingDateComp, to: resultDateComp, options: options) } override func components(_ unitFlags: Unit, from startingDate: Date, to resultDate: Date, options opts: Options = []) -> DateComponents { return backingCalendar.components(unitFlags, from: startingDate, to: resultDate, options: opts) } override func nextWeekendAfter(_ date: Date, options: NSCalendar.Options) -> DateInterval? { return backingCalendar.nextWeekendAfter(date, options: options) } override func isDateInWeekend(_ date: Date) -> Bool { return backingCalendar.isDateInWeekend(date) } override func enumerateDates(startingAfter start: Date, matching comps: DateComponents, options opts: NSCalendar.Options = [], using block: (Date?, Bool, UnsafeMutablePointer<ObjCBool>) -> Void) { return backingCalendar.enumerateDates(startingAfter: start, matching: comps, options: opts, using: block) } } #if !os(WASI) // This notification is posted through [NSNotificationCenter defaultCenter] // when the system day changes. Register with "nil" as the object of this // notification. If the computer/device is asleep when the day changed, // this will be posted on wakeup. You'll get just one of these if the // machine has been asleep for several days. The definition of "Day" is // relative to the current calendar ([NSCalendar currentCalendar]) of the // process and its locale and time zone. There are no guarantees that this // notification is received by observers in a "timely" manner, same as // with distributed notifications. extension NSNotification.Name { public static let NSCalendarDayChanged = NSNotification.Name(rawValue: "NSCalendarDayChangedNotification") } #endif extension NSCalendar: _SwiftBridgeable { typealias SwiftType = Calendar var _swiftObject: SwiftType { return Calendar(reference: self) } } extension Calendar: _NSBridgeable { typealias NSType = NSCalendar typealias CFType = CFCalendar var _nsObject: NSCalendar { return _bridgeToObjectiveC() } var _cfObject: CFCalendar { return _nsObject._cfObject } } extension CFCalendar : _NSBridgeable, _SwiftBridgeable { typealias NSType = NSCalendar internal var _nsObject: NSType { return unsafeBitCast(self, to: NSType.self) } internal var _swiftObject: Calendar { return _nsObject._swiftObject } } extension NSCalendar : _StructTypeBridgeable { public typealias _StructType = Calendar public func _bridgeToSwift() -> Calendar { return Calendar._unconditionallyBridgeFromObjectiveC(self) } } // CF Bridging: internal func _CFSwiftCalendarGetCalendarIdentifier(_ calendar: CFTypeRef) -> Unmanaged<CFTypeRef> { // It is tempting to just: // return Unmanaged.passUnretained(unsafeBitCast(calendar, to: NSCalendar.self).calendarIdentifier.rawValue._cfObject) // The problem is that Swift will then release the ._cfObject from under us. It needs to be retained, but Swift objects do not necessarily have a way to retain that CFObject to be alive for the caller because, outside of ObjC, there is no autorelease pool to save us from this. This is a problem with the fact that we're bridging a Get function; Copy functions of course just return +1 and live happily. // So, the solution here is to canonicalize to one of the CFString constants, which are immortal. If someone is using a nonstandard calendar identifier, well, this will currently explode :( TODO. let result: CFString switch unsafeBitCast(calendar, to: NSCalendar.self).calendarIdentifier { case .gregorian: result = kCFCalendarIdentifierGregorian case .buddhist: result = kCFCalendarIdentifierBuddhist case .chinese: result = kCFCalendarIdentifierChinese case .coptic: result = kCFCalendarIdentifierCoptic case .ethiopicAmeteMihret: result = kCFCalendarIdentifierEthiopicAmeteMihret case .ethiopicAmeteAlem: result = kCFCalendarIdentifierEthiopicAmeteAlem case .hebrew: result = kCFCalendarIdentifierHebrew case .ISO8601: result = kCFCalendarIdentifierISO8601 case .indian: result = kCFCalendarIdentifierIndian case .islamic: result = kCFCalendarIdentifierIslamic case .islamicCivil: result = kCFCalendarIdentifierIslamicCivil case .japanese: result = kCFCalendarIdentifierJapanese case .persian: result = kCFCalendarIdentifierPersian case .republicOfChina: result = kCFCalendarIdentifierRepublicOfChina case .islamicTabular: result = kCFCalendarIdentifierIslamicTabular case .islamicUmmAlQura: result = kCFCalendarIdentifierIslamicUmmAlQura default: fatalError("Calendars returning a non-system calendar identifier in Swift Foundation are not supported.") } return Unmanaged.passUnretained(result) } internal func _CFSwiftCalendarCopyLocale(_ calendar: CFTypeRef) -> Unmanaged<CFTypeRef>? { if let locale = unsafeBitCast(calendar, to: NSCalendar.self).locale { return Unmanaged.passRetained(locale._cfObject) } else { return nil } } internal func _CFSwiftCalendarSetLocale(_ calendar: CFTypeRef, _ locale: CFTypeRef?) { let calendar = unsafeBitCast(calendar, to: NSCalendar.self) if let locale = locale { calendar.locale = unsafeBitCast(locale, to: NSLocale.self)._swiftObject } else { calendar.locale = nil } } internal func _CFSwiftCalendarCopyTimeZone(_ calendar: CFTypeRef) -> Unmanaged<CFTypeRef> { return Unmanaged.passRetained(unsafeBitCast(calendar, to: NSCalendar.self).timeZone._cfObject) } internal func _CFSwiftCalendarSetTimeZone(_ calendar: CFTypeRef, _ timeZone: CFTypeRef) { let calendar = unsafeBitCast(calendar, to: NSCalendar.self) calendar.timeZone = unsafeBitCast(timeZone, to: NSTimeZone.self)._swiftObject } internal func _CFSwiftCalendarGetFirstWeekday(_ calendar: CFTypeRef) -> CFIndex { let calendar = unsafeBitCast(calendar, to: NSCalendar.self) return calendar.firstWeekday } internal func _CFSwiftCalendarSetFirstWeekday(_ calendar: CFTypeRef, _ firstWeekday: CFIndex) { let calendar = unsafeBitCast(calendar, to: NSCalendar.self) calendar.firstWeekday = firstWeekday } internal func _CFSwiftCalendarGetMinimumDaysInFirstWeek(_ calendar: CFTypeRef) -> CFIndex { let calendar = unsafeBitCast(calendar, to: NSCalendar.self) return calendar.minimumDaysInFirstWeek } internal func _CFSwiftCalendarSetMinimumDaysInFirstWeek(_ calendar: CFTypeRef, _ minimumDaysInFirstWeek: CFIndex) { let calendar = unsafeBitCast(calendar, to: NSCalendar.self) calendar.minimumDaysInFirstWeek = minimumDaysInFirstWeek } internal func _CFSwiftCalendarCopyGregorianStartDate(_ calendar: CFTypeRef) -> Unmanaged<CFTypeRef>? { if let date = unsafeBitCast(calendar, to: NSCalendar.self).gregorianStartDate { return Unmanaged.passRetained(date._cfObject) } else { return nil } } internal func _CFSwiftCalendarSetGregorianStartDate(_ calendar: CFTypeRef, _ date: CFTypeRef?) { let calendar = unsafeBitCast(calendar, to: NSCalendar.self) if let date = date { calendar.gregorianStartDate = unsafeBitCast(date, to: NSDate.self)._swiftObject } else { calendar.gregorianStartDate = nil } }
apache-2.0
30519cce279d6df11f2ffa341ca5f5c7
47.799608
880
0.667072
4.953028
false
false
false
false
Sherlouk/monzo-vapor
Tests/MonzoTests/AccountTests.swift
1
3941
import XCTest @testable import Monzo class AccountTests: XCTestCase { func testFetchPrepaidAccounts() { let client = MonzoClient(publicKey: "", privateKey: "", httpClient: MockResponder()) let user = client.createUser(userId: "", accessToken: "tokenPrepaid", refreshToken: nil) let assertAccounts: (([Account]) -> Void) = { accounts in XCTAssertEqual(accounts.count, 2) let firstAccount = accounts.first XCTAssertEqual(firstAccount?.user.accessToken, "tokenPrepaid") XCTAssertEqual(firstAccount?.id, "account_1") XCTAssertEqual(firstAccount?.type, .prepaid) XCTAssertEqual(firstAccount?.description, "Demo Account One") let secondAccount = accounts.last XCTAssertEqual(secondAccount?.user.accessToken, "tokenPrepaid") XCTAssertEqual(secondAccount?.id, "account_2") XCTAssertEqual(secondAccount?.type, .prepaid) XCTAssertEqual(secondAccount?.description, "Demo Account Two") } do { let accountsOne = try user.accounts() assertAccounts(accountsOne) let accountsTwo = try user.accounts(fetchCurrentAccounts: false) assertAccounts(accountsTwo) } catch { XCTFail() } } func testFetchCurrentAccounts() { let client = MonzoClient(publicKey: "", privateKey: "", httpClient: MockResponder()) let user = client.createUser(userId: "", accessToken: "tokenCurrent", refreshToken: nil) do { let accounts = try user.accounts(fetchCurrentAccounts: true) XCTAssertEqual(accounts.count, 1) let firstAccount = accounts.first XCTAssertEqual(firstAccount?.user.accessToken, "tokenCurrent") XCTAssertEqual(firstAccount?.id, "account_3") XCTAssertEqual(firstAccount?.type, .current) XCTAssertEqual(firstAccount?.description, "Demo Current Account One") } catch { XCTFail() } } func testAccountType() { XCTAssertEqual(Account.AccountType(rawValue: "uk_prepaid"), .prepaid) XCTAssertEqual(Account.AccountType(rawValue: "uk_retail"), .current) XCTAssertEqual(Account.AccountType(rawValue: "this is definitely not an account"), .unknown) } func testFetchPrepaidAccountsRequest() { let responder = MockResponder() let client = MonzoClient(publicKey: "public", privateKey: "private", httpClient: responder) let user = client.createUser(userId: "", accessToken: "prepaidToken", refreshToken: nil) let request = try? client.provider.createRequest(.listAccounts(user, false)) XCTAssertEqual(request?.uri.description, "https://api.monzo.com:443/accounts") XCTAssertEqual(request?.headers[.authorization], "Bearer prepaidToken") } func testFetchCurrentAccountsRequest() { let responder = MockResponder() let client = MonzoClient(publicKey: "public", privateKey: "private", httpClient: responder) let user = client.createUser(userId: "", accessToken: "currentToken", refreshToken: nil) let request = try? client.provider.createRequest(.listAccounts(user, true)) XCTAssertEqual(request?.uri.description, "https://api.monzo.com:443/accounts?account_type=uk_retail") XCTAssertEqual(request?.headers[.authorization], "Bearer currentToken") } static var allTests = [ ("testFetchPrepaidAccounts", testFetchPrepaidAccounts), ("testFetchCurrentAccounts", testFetchCurrentAccounts), ("testAccountType", testAccountType), ("testFetchPrepaidAccountsRequest", testFetchPrepaidAccountsRequest), ("testFetchCurrentAccountsRequest", testFetchCurrentAccountsRequest), ] }
mit
e524537b9e457324fa58fb3ae7bd9a6e
43.784091
109
0.647805
5.001269
false
true
false
false
payjp/payjp-ios
Sources/Networking/Models/Card.swift
1
3236
// // Card.swift // PAYJP // // Created by [email protected] on 10/3/16. // Copyright © 2016 PAY, Inc. All rights reserved. // // https://pay.jp/docs/api/#token-トークン // // import Foundation /// PAY.JP card object. /// For security reasons, the card number is masked and you can get only last4 character. /// The full documentations are following. /// cf. [https://pay.jp/docs/api/#cardオブジェクト](https://pay.jp/docs/api/#cardオブジェクト) @objcMembers @objc(PAYCard) public final class Card: NSObject, Decodable { public let identifer: String public let name: String? public let last4Number: String public let brand: String public let expirationMonth: UInt8 public let expirationYear: UInt16 public let fingerprint: String public let liveMode: Bool public let createdAt: Date public let threeDSecureStatus: PAYThreeDSecureStatus? public var rawValue: [String: Any]? // MARK: - Decodable private enum CodingKeys: String, CodingKey { case id case name case last4Number = "last4" case brand case expirationMonth = "exp_month" case expirationYear = "exp_year" case fingerprint case liveMode = "livemode" case createdAt = "created" case threeDSecureStatus = "three_d_secure_status" } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) identifer = try container.decode(String.self, forKey: .id) name = try container.decodeIfPresent(String.self, forKey: .name) last4Number = try container.decode(String.self, forKey: .last4Number) brand = try container.decode(String.self, forKey: .brand) expirationMonth = try container.decode(UInt8.self, forKey: .expirationMonth) expirationYear = try container.decode(UInt16.self, forKey: .expirationYear) fingerprint = try container.decode(String.self, forKey: .fingerprint) liveMode = try container.decode(Bool.self, forKey: .liveMode) createdAt = try container.decode(Date.self, forKey: .createdAt) if let tdsStatusRaw = try container.decodeIfPresent(String.self, forKey: .threeDSecureStatus) { threeDSecureStatus = ThreeDSecureStatus.find(rawValue: tdsStatusRaw) } else { threeDSecureStatus = nil } } public init(identifier: String, name: String?, last4Number: String, brand: String, expirationMonth: UInt8, expirationYear: UInt16, fingerprint: String, liveMode: Bool, createAt: Date, threeDSecureStatus: PAYThreeDSecureStatus?, rawValue: [String: Any]? = nil ) { self.identifer = identifier self.name = name self.last4Number = last4Number self.brand = brand self.expirationMonth = expirationMonth self.expirationYear = expirationYear self.fingerprint = fingerprint self.liveMode = liveMode self.createdAt = createAt self.threeDSecureStatus = threeDSecureStatus self.rawValue = rawValue } }
mit
029cf72220b996b90c553da21eb31f47
35.816092
103
0.646894
4.442441
false
false
false
false
tkareine/MiniFuture
Benchmark/main.swift
1
2370
import Foundation #if SWIFT_PACKAGE import MiniFuture #endif let numberOfIterations = 500 let numberOfFutureCompositions = 2000 func benchmarkFutures() { var fut: Future<Int> = Future.succeeded(0) for i in 0..<numberOfFutureCompositions { let futBegin = Future.async { .success(i) } let futEnd: Future<Int> = futBegin.flatMap { e0 in let promise = Future<Int>.promise() let futIn0: Future<Int> = Future.succeeded(i).flatMap { e1 in Future.async { .success(i) }.flatMap { e2 in Future.succeeded(e1 + e2) } } let futIn1: Future<Int> = Future.async { .success(i) }.flatMap { e1 in Future.succeeded(i).flatMap { e2 in Future.async { .success(e1 + e2) } } } promise.completeWith(futIn0.flatMap { e1 in return futIn1.flatMap { e2 in Future.succeeded(e0 + e1 + e2) } }) return promise } fut = fut.flatMap { _ in futEnd } } let _ = fut.get() } struct Measurement { let mean: Double let stddev: Double init(from samples: [Double]) { mean = Measurement.mean(samples) stddev = Measurement.stddev(samples, mean) } static func mean(_ samples: [Double]) -> Double { let sum = samples.reduce(0.0) { $0 + $1 } return sum / Double(samples.count) } static func variance(_ samples: [Double], _ mean: Double) -> Double { let total = samples.reduce(0.0) { acc, s in acc + pow(s - mean, 2.0) } return total / Double(samples.count) } static func stddev(_ samples: [Double], _ mean: Double) -> Double { return sqrt(variance(samples, mean)) } } func measure(_ block: () -> Void) -> Measurement { let processInfo = ProcessInfo.processInfo var samples: [Double] = [] for _ in 0..<numberOfIterations { let start = processInfo.systemUptime block() let end = processInfo.systemUptime samples.append((end - start) * 1000) } return Measurement(from: samples) } func formatMeasurement(_ label: String, withData m: Measurement) -> String { return String(format: "%@: %.f ms (± %.f ms)", label, m.mean, m.stddev) } print("iterations: \(numberOfIterations), futures composed: \(numberOfFutureCompositions)\n") print(formatMeasurement("warm up", withData: measure(benchmarkFutures))) print(formatMeasurement("measure", withData: measure(benchmarkFutures)))
mit
94bddec871ee59a7d7efecfa0d559471
25.322222
93
0.640777
3.583964
false
false
false
false
thefirstnikhil/hydrateapp
Hydrate/View Controllers/SettingsIntervalsTableViewController.swift
1
4125
// // SettingsIntervalsTableViewController.swift // Hydrate // // Created by Nikhil Kalra on 9/13/14. // Copyright (c) 2014 Nikhil Kalra. All rights reserved. // import UIKit class SettingsIntervalsTableViewController: UITableViewController { var times:[String] = [String]() var selected:[Bool]? = [Bool](count: 24, repeatedValue: false) var sender: SettingsTableViewController? 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() self.navigationItem.title = NSLocalizedString("Notification Intervals", comment: "Notification Intervals") let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = .MediumStyle dateFormatter.dateFormat = "HH" dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") let displayFormatter = NSDateFormatter() displayFormatter.dateFormat = "h a" for var i = 0; i < 24; ++i { let date = dateFormatter.dateFromString(String(i)) let string = displayFormatter.stringFromDate(date!) times.append(string) } tableView.reloadData() } override func viewWillDisappear(animated: Bool) { NSUserDefaults.standardUserDefaults().setObject(selected, forKey: waterNotificationIntervalsKey) NSUserDefaults.standardUserDefaults().synchronize() super.viewWillDisappear(animated) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) sender?.tableView.reloadData() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return times.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("intervalCells", forIndexPath: indexPath) as UITableViewCell // Configure the cell... cell.textLabel?.text = times[indexPath.row] if (indexPath.row < 24 && selected![indexPath.row] == true) { cell.accessoryType = .Checkmark } else { cell.accessoryType = .None } return cell } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return NSLocalizedString("Notification Intervals",comment: "Notification Intervals") } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) if (cell?.accessoryType == UITableViewCellAccessoryType.Checkmark) { cell?.accessoryType = UITableViewCellAccessoryType.None selected![indexPath.row] = false } else if (cell?.accessoryType == UITableViewCellAccessoryType.None) { cell?.accessoryType = UITableViewCellAccessoryType.Checkmark selected![indexPath.row] = true } tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
mit
bac566b5846918f15b83726ca37b8cac
34.560345
123
0.67297
5.619891
false
false
false
false
natecook1000/swift
test/IDE/complete_associated_types.swift
2
18562
// RUN: sed -n -e '1,/NO_ERRORS_UP_TO_HERE$/ p' %s > %t_no_errors.swift // RUN: %target-swift-frontend -typecheck -verify %t_no_errors.swift // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRUCT_AS_TYPE > %t.types.txt // RUN: %FileCheck %s -check-prefix=STRUCT_TYPE_COUNT < %t.types.txt // RUN: %FileCheck %s -check-prefix=STRUCT_TYPES < %t.types.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRUCT_AS_EXPR > %t.types.txt // RUN: %FileCheck %s -check-prefix=STRUCT_TYPES < %t.types.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRUCT_INSTANCE > %t.types.txt // RUN: %FileCheck %s -check-prefix=STRUCT_INSTANCE < %t.types.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSOCIATED_TYPES_UNQUAL_1 > %t.types.txt // RUN: %FileCheck %s -allow-deprecated-dag-overlap -check-prefix=ASSOCIATED_TYPES_UNQUAL < %t.types.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSOCIATED_TYPES_UNQUAL_2 > %t.types.txt // RUN: %FileCheck %s -allow-deprecated-dag-overlap -check-prefix=ASSOCIATED_TYPES_UNQUAL < %t.types.txt // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=BROKEN_CONFORMANCE_1 > %t.types.txt // RUN: %FileCheck %s -check-prefix=BROKEN_CONFORMANCE_1 < %t.types.txt // FIXME: extensions that introduce conformances? protocol FooBaseProtocolWithAssociatedTypes { associatedtype DefaultedTypeCommonA = Int associatedtype DefaultedTypeCommonB = Int associatedtype DefaultedTypeCommonC = Int associatedtype DefaultedTypeCommonD = Int associatedtype FooBaseDefaultedTypeA = Int associatedtype FooBaseDefaultedTypeB = Int associatedtype FooBaseDefaultedTypeC = Int associatedtype DeducedTypeCommonA associatedtype DeducedTypeCommonB associatedtype DeducedTypeCommonC associatedtype DeducedTypeCommonD func deduceCommonA() -> DeducedTypeCommonA func deduceCommonB() -> DeducedTypeCommonB func deduceCommonC() -> DeducedTypeCommonC func deduceCommonD() -> DeducedTypeCommonD associatedtype FooBaseDeducedTypeA associatedtype FooBaseDeducedTypeB associatedtype FooBaseDeducedTypeC associatedtype FooBaseDeducedTypeD func deduceFooBaseA() -> FooBaseDeducedTypeA func deduceFooBaseB() -> FooBaseDeducedTypeB func deduceFooBaseC() -> FooBaseDeducedTypeC func deduceFooBaseD() -> FooBaseDeducedTypeD } protocol FooProtocolWithAssociatedTypes : FooBaseProtocolWithAssociatedTypes { // From FooBase. associatedtype DefaultedTypeCommonA = Int associatedtype DefaultedTypeCommonB = Int associatedtype FooBaseDefaultedTypeB = Double associatedtype DeducedTypeCommonA associatedtype DeducedTypeCommonB func deduceCommonA() -> DeducedTypeCommonA func deduceCommonB() -> DeducedTypeCommonB func deduceFooBaseB() -> Int // New decls. associatedtype FooDefaultedType = Int associatedtype FooDeducedTypeB associatedtype FooDeducedTypeC associatedtype FooDeducedTypeD func deduceFooB() -> FooDeducedTypeB func deduceFooC() -> FooDeducedTypeC func deduceFooD() -> FooDeducedTypeD } protocol BarBaseProtocolWithAssociatedTypes { // From FooBase. associatedtype DefaultedTypeCommonA = Int associatedtype DefaultedTypeCommonC = Int associatedtype DeducedTypeCommonA associatedtype DeducedTypeCommonC func deduceCommonA() -> DeducedTypeCommonA func deduceCommonC() -> DeducedTypeCommonC func deduceFooBaseC() -> Int // From Foo. func deduceFooC() -> Int // New decls. associatedtype BarBaseDefaultedType = Int associatedtype BarBaseDeducedTypeC associatedtype BarBaseDeducedTypeD func deduceBarBaseC() -> BarBaseDeducedTypeC func deduceBarBaseD() -> BarBaseDeducedTypeD } protocol BarProtocolWithAssociatedTypes : BarBaseProtocolWithAssociatedTypes { // From FooBase. associatedtype DefaultedTypeCommonA = Int associatedtype DefaultedTypeCommonD = Int associatedtype DeducedTypeCommonA associatedtype DeducedTypeCommonD func deduceCommonA() -> DeducedTypeCommonA func deduceCommonD() -> DeducedTypeCommonD func deduceFooBaseD() -> Int // From Foo. func deduceFooD() -> Int // From BarBase. func deduceBarBaseD() -> Int // New decls. associatedtype BarDefaultedTypeA = Int associatedtype BarDeducedTypeD func deduceBarD() -> BarDeducedTypeD } struct StructWithAssociatedTypes : FooProtocolWithAssociatedTypes, BarProtocolWithAssociatedTypes { typealias FooBaseDefaultedTypeC = Double func deduceCommonA() -> Int { return 0 } func deduceCommonB() -> Int { return 0 } func deduceCommonC() -> Int { return 0 } func deduceCommonD() -> Int { return 0 } func deduceFooBaseA() -> Int { return 0 } func deduceFooBaseB() -> Int { return 0 } func deduceFooBaseC() -> Int { return 0 } func deduceFooBaseD() -> Int { return 0 } func deduceFooB() -> Int { return 0 } func deduceFooC() -> Int { return 0 } func deduceFooD() -> Int { return 0 } func deduceBarBaseC() -> Int { return 0 } func deduceBarBaseD() -> Int { return 0 } func deduceBarD() -> Int { return 0 } } class ClassWithAssociatedTypes : FooProtocolWithAssociatedTypes, BarProtocolWithAssociatedTypes { typealias FooBaseDefaultedTypeC = Double func deduceCommonA() -> Int { return 0 } func deduceCommonB() -> Int { return 0 } func deduceCommonC() -> Int { return 0 } func deduceCommonD() -> Int { return 0 } func deduceFooBaseA() -> Int { return 0 } func deduceFooBaseB() -> Int { return 0 } func deduceFooBaseC() -> Int { return 0 } func deduceFooBaseD() -> Int { return 0 } func deduceFooB() -> Int { return 0 } func deduceFooC() -> Int { return 0 } func deduceFooD() -> Int { return 0 } func deduceBarBaseC() -> Int { return 0 } func deduceBarBaseD() -> Int { return 0 } func deduceBarD() -> Int { return 0 } } // NO_ERRORS_UP_TO_HERE func testStruct1() { var x: StructWithAssociatedTypes#^STRUCT_AS_TYPE^# } func testStruct2() { StructWithAssociatedTypes#^STRUCT_AS_EXPR^# } func testStruct3(a: StructWithAssociatedTypes) { a.#^STRUCT_INSTANCE^# } // STRUCT_TYPE_COUNT: Begin completions, 25 items // STRUCT_INSTANCE: Begin completions, 15 items // STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceCommonA()[#Int#] // STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceCommonB()[#Int#] // STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceCommonC()[#Int#] // STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceCommonD()[#Int#] // STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceFooBaseA()[#Int#] // STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceFooBaseB()[#Int#] // STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceFooBaseC()[#Int#] // STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceFooBaseD()[#Int#] // STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceFooB()[#Int#] // STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceFooC()[#Int#] // STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceFooD()[#Int#] // STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceBarBaseC()[#Int#] // STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceBarBaseD()[#Int#] // STRUCT_INSTANCE-DAG: Decl[InstanceMethod]/CurrNominal: deduceBarD()[#Int#] // STRUCT_INSTANCE-DAG: Keyword[self]/CurrNominal: self[#StructWithAssociatedTypes#]; name=self // STRUCT_INSTANCE: End completions // STRUCT_TYPES: Begin completions // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .DefaultedTypeCommonA[#Int#]{{; name=.+$}} // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .DefaultedTypeCommonD[#Int#]{{; name=.+$}} // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .DeducedTypeCommonA[#Int#]{{; name=.+$}} // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .DeducedTypeCommonD[#Int#]{{; name=.+$}} // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .BarDefaultedTypeA[#Int#]{{; name=.+$}} // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .BarDeducedTypeD[#Int#]{{; name=.+$}} // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .DefaultedTypeCommonC[#Int#]{{; name=.+$}} // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .DeducedTypeCommonC[#Int#]{{; name=.+$}} // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .BarBaseDefaultedType[#Int#]{{; name=.+$}} // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .BarBaseDeducedTypeC[#Int#]{{; name=.+$}} // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .BarBaseDeducedTypeD[#Int#]{{; name=.+$}} // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .DefaultedTypeCommonB[#Int#]{{; name=.+$}} // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .FooBaseDefaultedTypeB[#Double#]{{; name=.+$}} // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .DeducedTypeCommonB[#Int#]{{; name=.+$}} // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .FooDefaultedType[#Int#]{{; name=.+$}} // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .FooDeducedTypeB[#Int#]{{; name=.+$}} // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .FooDeducedTypeC[#Int#]{{; name=.+$}} // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .FooDeducedTypeD[#Int#]{{; name=.+$}} // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .FooBaseDefaultedTypeA[#Int#]{{; name=.+$}} // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .FooBaseDeducedTypeA[#Int#]{{; name=.+$}} // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .FooBaseDeducedTypeB[#Int#]{{; name=.+$}} // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .FooBaseDeducedTypeC[#Int#]{{; name=.+$}} // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .FooBaseDeducedTypeD[#Int#]{{; name=.+$}} // STRUCT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .FooBaseDefaultedTypeC[#Double#]{{; name=.+$}} // STRUCT_TYPES: End completions class DerivedFromClassWithAssociatedTypes : ClassWithAssociatedTypes { func test() { #^ASSOCIATED_TYPES_UNQUAL_1^# } } class MoreDerivedFromClassWithAssociatedTypes : DerivedFromClassWithAssociatedTypes { func test() { #^ASSOCIATED_TYPES_UNQUAL_2^# } } // ASSOCIATED_TYPES_UNQUAL: Begin completions // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: DefaultedTypeCommonA[#Int#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: DefaultedTypeCommonD[#Int#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: DeducedTypeCommonA[#Int#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: DeducedTypeCommonD[#Int#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: BarDefaultedTypeA[#Int#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: BarDeducedTypeD[#Int#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: DefaultedTypeCommonC[#Int#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: DeducedTypeCommonC[#Int#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: BarBaseDefaultedType[#Int#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: BarBaseDeducedTypeC[#Int#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: BarBaseDeducedTypeD[#Int#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: DefaultedTypeCommonB[#Int#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: FooBaseDefaultedTypeB[#Double#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: DeducedTypeCommonB[#Int#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: FooDefaultedType[#Int#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: FooDeducedTypeB[#Int#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: FooDeducedTypeC[#Int#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: FooDeducedTypeD[#Int#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: FooBaseDefaultedTypeA[#Int#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: FooBaseDefaultedTypeB[#Double#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: FooBaseDeducedTypeA[#Int#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: FooBaseDeducedTypeB[#Int#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: FooBaseDeducedTypeC[#Int#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL-DAG: Decl[TypeAlias]/Super: FooBaseDeducedTypeD[#Int#]{{; name=.+$}} // ASSOCIATED_TYPES_UNQUAL: End completions struct StructWithBrokenConformance : FooProtocolWithAssociatedTypes { // Does not conform. } func testBrokenConformances1() { StructWithBrokenConformance.#^BROKEN_CONFORMANCE_1^# } // BROKEN_CONFORMANCE_1: Begin completions, 35 items // BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: DefaultedTypeCommonA[#StructWithBrokenConformance.DefaultedTypeCommonA#]; name=DefaultedTypeCommonA // BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: DefaultedTypeCommonB[#StructWithBrokenConformance.DefaultedTypeCommonB#]; name=DefaultedTypeCommonB // BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: FooBaseDefaultedTypeB[#StructWithBrokenConformance.FooBaseDefaultedTypeB#]; name=FooBaseDefaultedTypeB // BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: DeducedTypeCommonA[#StructWithBrokenConformance.DeducedTypeCommonA#]; name=DeducedTypeCommonA // BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: DeducedTypeCommonB[#StructWithBrokenConformance.DeducedTypeCommonB#]; name=DeducedTypeCommonB // BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceCommonA({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.DeducedTypeCommonA#]{{; name=.+$}} // BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceCommonB({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.DeducedTypeCommonB#]{{; name=.+$}} // BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceFooBaseB({#self: StructWithBrokenConformance#})[#() -> Int#]{{; name=.+$}} // BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: FooDefaultedType[#StructWithBrokenConformance.FooDefaultedType#]; name=FooDefaultedType // BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: FooDeducedTypeB[#StructWithBrokenConformance.FooDeducedTypeB#]; name=FooDeducedTypeB // BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: FooDeducedTypeC[#StructWithBrokenConformance.FooDeducedTypeC#]; name=FooDeducedTypeC // BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: FooDeducedTypeD[#StructWithBrokenConformance.FooDeducedTypeD#]; name=FooDeducedTypeD // BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceFooB({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.FooDeducedTypeB#]{{; name=.+$}} // BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceFooC({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.FooDeducedTypeC#]{{; name=.+$}} // BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceFooD({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.FooDeducedTypeD#]{{; name=.+$}} // BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: DefaultedTypeCommonC[#StructWithBrokenConformance.DefaultedTypeCommonC#]; name=DefaultedTypeCommonC // BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: DefaultedTypeCommonD[#StructWithBrokenConformance.DefaultedTypeCommonD#]; name=DefaultedTypeCommonD // BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: FooBaseDefaultedTypeA[#StructWithBrokenConformance.FooBaseDefaultedTypeA#]; name=FooBaseDefaultedTypeA // BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: FooBaseDefaultedTypeC[#StructWithBrokenConformance.FooBaseDefaultedTypeC#]; name=FooBaseDefaultedTypeC // BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: DeducedTypeCommonC[#StructWithBrokenConformance.DeducedTypeCommonC#]; name=DeducedTypeCommonC // BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: DeducedTypeCommonD[#StructWithBrokenConformance.DeducedTypeCommonD#]; name=DeducedTypeCommonD // BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceCommonA({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.DeducedTypeCommonA#]{{; name=.+$}} // BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceCommonB({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.DeducedTypeCommonB#]{{; name=.+$}} // BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceCommonC({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.DeducedTypeCommonC#]{{; name=.+$}} // BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceCommonD({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.DeducedTypeCommonD#]{{; name=.+$}} // BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: FooBaseDeducedTypeA[#StructWithBrokenConformance.FooBaseDeducedTypeA#]; name=FooBaseDeducedTypeA // BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: FooBaseDeducedTypeB[#StructWithBrokenConformance.FooBaseDeducedTypeB#]; name=FooBaseDeducedTypeB // BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: FooBaseDeducedTypeC[#StructWithBrokenConformance.FooBaseDeducedTypeC#]; name=FooBaseDeducedTypeC // BROKEN_CONFORMANCE_1-DAG: Decl[TypeAlias]/CurrNominal: FooBaseDeducedTypeD[#StructWithBrokenConformance.FooBaseDeducedTypeD#]; name=FooBaseDeducedTypeD // BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceFooBaseA({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.FooBaseDeducedTypeA#]{{; name=.+$}} // BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceFooBaseB({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.FooBaseDeducedTypeB#]{{; name=.+$}} // BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceFooBaseC({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.FooBaseDeducedTypeC#]{{; name=.+$}} // BROKEN_CONFORMANCE_1-DAG: Decl[InstanceMethod]/Super: deduceFooBaseD({#self: StructWithBrokenConformance#})[#() -> StructWithBrokenConformance.FooBaseDeducedTypeD#]{{; name=.+$}} // BROKEN_CONFORMANCE_1: End completions
apache-2.0
a44d45c72a198bfbd3832506b85ab6c5
60.059211
189
0.741084
3.776602
false
false
false
false
shitoudev/marathon
marathonKit/marathonKit.swift
1
3364
// // marathonKit.swift // marathon // // Created by zhenwen on 9/9/15. // Copyright © 2015 zhenwen. All rights reserved. // import UIKit import CoreLocation import MapKit public let appNormalColor = UIColor(hex: "#ee6e4a") //UIColor(hex: "#435E9F") //UIColor(hex: "#CD3200") /** 计算两个经纬度之间的距离米 */ public func distanceBetweenOrderBy(lat1: Double, lat2: Double, lng1: Double, lng2: Double) -> Double { let location1 = CLLocation(latitude: lat1, longitude: lng1) let location2 = CLLocation(latitude: lat2, longitude: lng2) let distance = location1.distanceFromLocation(location2) return distance } public func stringDistance(meters: Double) -> String { return String(format: "%.2f", arguments: [meters/1000]) } public func stringSecondCount(seconds: Int) -> String { var remainingSeconds = seconds let hours = remainingSeconds / 3600 remainingSeconds = remainingSeconds - hours * 3600; let minutes = remainingSeconds / 60 remainingSeconds = remainingSeconds - minutes * 60; if hours > 0 { return String(format: "%i:%02i:%02i", arguments: [hours, minutes, remainingSeconds]) } else if minutes > 0 { return String(format: "%02i:%02i", arguments: [minutes, remainingSeconds]) } else { return String(format: "00:%02i", arguments: [remainingSeconds]) } } public func stringAvgPace(meters: Double, seconds: Int) -> String { if meters == 0 || seconds == 0 { return "0" } let avgPaceSecMeters = Double(seconds) / meters let paceMin = Int((avgPaceSecMeters * 1000) / 60) let paceSec = Int((avgPaceSecMeters * 1000) - Double(paceMin * 60)) // return String(format: "%i:%02i %@", arguments: [paceMin, paceSec, "min/km"]) return String(format: "%i'%02i''", arguments: [paceMin, paceSec]) } public func isLocationOutOfChina(location: CLLocationCoordinate2D) -> Bool { if (location.longitude < 72.004 || location.longitude > 137.8347 || location.latitude < 0.8293 || location.latitude > 55.8271) { return true } return false } public func mapRegion(locations: [CLLocation]) -> MKCoordinateRegion { let firstLocation = locations.first! var minLat = firstLocation.coordinate.latitude var minLng = firstLocation.coordinate.longitude var maxLat = firstLocation.coordinate.latitude var maxLng = firstLocation.coordinate.longitude for location in locations { if (location.coordinate.latitude < minLat) { minLat = location.coordinate.latitude } if (location.coordinate.longitude < minLng) { minLng = location.coordinate.longitude } if (location.coordinate.latitude > maxLat) { maxLat = location.coordinate.latitude } if (location.coordinate.longitude > maxLng) { maxLng = location.coordinate.longitude } } let latitude = (minLat + maxLat) / 2.0 let longitude = (minLng + maxLng) / 2.0 let latitudeDelta = (maxLat - minLat) * 2.1 // 10% padding let longitudeDelta = (maxLng - minLng) * 2.1 // 10% padding let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: latitude, longitude: longitude), span: MKCoordinateSpan(latitudeDelta: latitudeDelta, longitudeDelta: longitudeDelta)) return region }
mit
2dd9a37a19ec41a7311c7702d442d616
34.136842
195
0.669164
3.963183
false
false
false
false
fgengine/quickly
Quickly/ViewControllers/Group/IQGroupViewController.swift
1
3914
// // Quickly // // MARK: IQGroupViewControllerAnimation public protocol IQGroupViewControllerAnimation : class { func animate( contentView: UIView, currentViewController: IQGroupViewController, targetViewController: IQGroupViewController, animated: Bool, complete: @escaping () -> Void ) } // MARK: IQGroupViewController public protocol IQGroupContainerViewController : IQViewController { var barView: QGroupbar? { set get } var barHeight: CGFloat { set get } var barHidden: Bool { set get } var barVisibility: CGFloat { set get } var viewControllers: [IQGroupViewController] { set get } var currentViewController: IQGroupViewController? { get } var animation: IQGroupViewControllerAnimation { get } var isAnimating: Bool { get } func set(barView: QGroupbar?, animated: Bool) func set(barHeight: CGFloat, animated: Bool) func set(barHidden: Bool, animated: Bool) func set(barVisibility: CGFloat, animated: Bool) func set(viewControllers: [IQGroupViewController], animated: Bool, completion: (() -> Swift.Void)?) func set(currentViewController: IQGroupViewController, animated: Bool, completion: (() -> Swift.Void)?) func didUpdate(viewController: IQGroupViewController, animated: Bool) } // MARK: IQGroupSlideViewController public protocol IQGroupViewController : IQContentOwnerViewController { var containerViewController: IQGroupContainerViewController? { get } var viewController: IQGroupContentViewController { get } var barHidden: Bool { set get } var barVisibility: CGFloat { set get } var barItem: QGroupbarItem? { set get } var animation: IQGroupViewControllerAnimation? { set get } func set(item: QGroupbarItem?, animated: Bool) } extension IQGroupViewController { public var containerViewController: IQGroupContainerViewController? { get { return self.parentViewController as? IQGroupContainerViewController } } public var barHidden: Bool { set(value) { self.containerViewController?.barHidden = value } get { return self.containerViewController?.barHidden ?? true } } public var barVisibility: CGFloat { set(value) { self.containerViewController?.barVisibility = value } get { return self.containerViewController?.barVisibility ?? 0 } } } // MARK: IQGroupContentViewController public protocol IQGroupContentViewController : IQContentViewController { var groupViewController: IQGroupViewController? { get } var groupbarHidden: Bool { set get } var groupbarVisibility: CGFloat { set get } var groupbarItem: QGroupbarItem? { set get } var groupAnimation: IQGroupViewControllerAnimation? { set get } func setGroupItem(_ item: QGroupbarItem, animated: Bool) } extension IQGroupContentViewController { public var groupViewController: IQGroupViewController? { get { return self.parentViewControllerOf() } } public var groupbarHidden: Bool { set(value) { self.groupViewController?.barHidden = value } get { return self.groupViewController?.barHidden ?? true } } public var groupbarVisibility: CGFloat { set(value) { self.groupViewController?.barVisibility = value } get { return self.groupViewController?.barVisibility ?? 0 } } public var groupbarItem: QGroupbarItem? { set(value) { self.groupViewController?.barItem = value } get { return self.groupViewController?.barItem } } public var groupAnimation: IQGroupViewControllerAnimation? { set(value) { self.groupViewController?.animation = value } get { return self.groupViewController?.animation } } public func setGroupItem(_ item: QGroupbarItem, animated: Bool) { guard let vc = self.groupViewController else { return } vc.set(item: item, animated: animated) } }
mit
75d405022a136265f1fea0c66b2d08de
32.452991
107
0.712059
4.755772
false
false
false
false
feistydog/FeistyDB
Sources/FeistyDB/Snapshot.swift
1
2899
// // Copyright (c) 2018 - 2020 Feisty Dog, LLC // // See https://github.com/feistydog/FeistyDB/blob/master/LICENSE.txt for license information // import Foundation import CSQLite /// An `sqlite3_snapshot *` object. /// /// - seealso: [Database Snapshot](https://www.sqlite.org/c3ref/snapshot.html) public typealias SQLiteSnapshot = UnsafeMutablePointer<sqlite3_snapshot> /// The state of a WAL mode database at a specific point in history. public final class Snapshot { /// The owning database public let database: Database /// The underlying `sqlite3_snapshot *` object let snapshot: SQLiteSnapshot /// A snapshot of the current state of a database schema. /// /// - note: If a read transaction is not already open one is opened automatically /// /// - parameter database: The owning database /// - parameter schema: The database schema to snapshot /// /// - throws: An error if the snapshot could not be recorded init(database: Database, schema: String) throws { self.database = database var snapshot: SQLiteSnapshot? = nil guard sqlite3_snapshot_get(database.db, schema, &snapshot) == SQLITE_OK else { throw SQLiteError("Error opening database snapshot", takingDescriptionFromDatabase: database.db) } self.snapshot = snapshot! } deinit { sqlite3_snapshot_free(snapshot) } } extension Snapshot: Comparable { public static func == (lhs: Snapshot, rhs: Snapshot) -> Bool { // precondition(lhs.database == rhs.database, "Cannot compare snapshots across databases") return sqlite3_snapshot_cmp(lhs.snapshot, rhs.snapshot) == 0 } public static func < (lhs: Snapshot, rhs: Snapshot) -> Bool { // precondition(lhs.database == rhs.database, "Cannot compare snapshots across databases") return sqlite3_snapshot_cmp(lhs.snapshot, rhs.snapshot) < 0 } } extension Database { /// Records a snapshot of the current state of a database schema. /// /// - parameter schema: The database schema to snapshot /// /// - throws: An error if the snapshot could not be recorded /// /// - seealso: [Record A Database Snapshot](https://www.sqlite.org/c3ref/snapshot_get.html) public func takeSnapshot(schema: String = "main") throws -> Snapshot { return try Snapshot(database: self, schema: schema) } /// Starts or upgrades a read transaction for a database schema to a specific snapshot. /// /// - parameter snapshot: The desired historical snapshot /// - parameter schema: The desired database schema /// /// - throws: An error if the snapshot could not be opened /// /// - seealso: [Start a read transaction on an historical snapshot](https://www.sqlite.org/c3ref/snapshot_open.html) public func openSnapshot(_ snapshot: Snapshot, schema: String = "main") throws { guard sqlite3_snapshot_open(db, schema, snapshot.snapshot) == SQLITE_OK else { throw SQLiteError("Error opening database snapshot", takingDescriptionFromDatabase: db) } } }
mit
2bd7192f2685a474a86698d97158bf0c
33.511905
117
0.723698
3.789542
false
false
false
false
arloistale/iOSThrive
Thrive/Thrive/JournalEntry.swift
1
3180
// // JournalEntry.swift // Thrive // // Created by Jonathan Lu on 1/27/16. // Copyright © 2016 UCSC OpenLab. All rights reserved. // import UIKit class JournalEntry: NSObject, NSCoding { // Mark: Paths static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("journalEntries") // MARK: Types enum MoodType: String { case Happy = "happyEmoticon" case Surprised = "surprisedEmoticon" case Neutral = "neutralEmoticon" case Confused = "confusedEmoticon" case Sad = "sadEmoticon" case Annoyed = "annoyedEmoticon" case What = "whatEmoticon" static let values = [Happy, Surprised, Neutral, Confused, Sad, Annoyed, What] static let colors = [ UIColor(colorLiteralRed: 0, green: 1, blue: 0, alpha: 1), UIColor(colorLiteralRed: 0, green: 1, blue: 1, alpha: 1), UIColor(colorLiteralRed: 0, green: 0, blue: 0, alpha: 1), UIColor(colorLiteralRed: 1, green: 0, blue: 1, alpha: 1), UIColor(colorLiteralRed: 0, green: 0, blue: 1, alpha: 1), UIColor(colorLiteralRed: 1, green: 0, blue: 0, alpha: 1), UIColor(colorLiteralRed: 1, green: 0.5, blue: 0.5, alpha: 1) ] } struct PropertyKey { static let dateKey = "date" static let messageKey = "message" static let photoKey = "photo" static let moodKey = "mood" } // MARK: Properties var date: NSDate var moodIndex: Int var message: String? var photo: UIImage? // MARK: Initialization init?(date: NSDate, moodIndex: Int, message: String?, photo: UIImage?) { self.date = date self.message = message self.moodIndex = moodIndex self.photo = photo super.init() if moodIndex < 0 || moodIndex >= MoodType.values.count { return nil } } // MARK: NSCoding Implementations func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(date, forKey: PropertyKey.dateKey) aCoder.encodeObject(photo, forKey: PropertyKey.photoKey) aCoder.encodeObject(message, forKey: PropertyKey.messageKey) aCoder.encodeInteger(moodIndex, forKey: PropertyKey.moodKey) } required convenience init?(coder aDecoder: NSCoder) { let message = aDecoder.decodeObjectForKey(PropertyKey.messageKey) as! String let photo = aDecoder.decodeObjectForKey(PropertyKey.photoKey) as? UIImage let date = aDecoder.decodeObjectForKey(PropertyKey.dateKey) as! NSDate let moodIndex = aDecoder.decodeIntegerForKey(PropertyKey.moodKey); self.init(date: date, moodIndex: moodIndex, message: message, photo: photo) } // MARK: Getters func getMoodImage() -> UIImage { return UIImage(named: MoodType.values[moodIndex].rawValue)!; } func getMoodColor() -> UIColor { return MoodType.colors[moodIndex]; } }
mit
9b3a110d9b9e48440b3e93f0bf4a8889
31.783505
123
0.623152
4.433752
false
false
false
false
Xinext/RemainderCalc
src/RemainderCalc/CommonUtility.swift
1
8548
// // CommonUtility.swift // import Foundation import UIKit /** - Image Utilty - Author: xinext HF - Copyright: xinext - Date: 2017/04/13 - Version: 1.0.1 */ class XIImage { /** Save image data to userdefault. - parameter key: image name - parameter image: UIImage */ static func SaveUserDefalt( key: String, image: UIImage) { let imageData = UIImagePNGRepresentation(image) // convert to Data from UIImage UserDefaults.standard.set(imageData, forKey: key) } /** Load image data from userdefault. - parameter key: image name */ static func LoadUserDefalt( key: String ) -> UIImage? { let imageData = UserDefaults.standard.data(forKey: key) return UIImage(data: imageData!) } /** Clear image data from userdefalt. */ static func ClearUserDefalt( key: String ) { UserDefaults.standard.removeObject(forKey: key) } static func SaveLibrary( name: String, image: UIImage) -> Bool { let libPath = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).last! let savePath = libPath.appendingPathComponent(name) let pngImageData = UIImagePNGRepresentation(image) do { try pngImageData!.write(to: savePath) } catch { return false } return true } static func LoadLibrary( name: String ) -> UIImage? { let libPath = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).last! let image = UIImage(contentsOfFile: libPath.path) return image } } /** - [ENG]MessageBox Utilty - [JPN]メセージボックスユーティリティー - Author: xinext HF - Copyright: xinext - Date: 2017/02/09 - Version: 1.0.1 */ class XIDialog { /** Displays a alert message dialog. - parameter pvc: ViewController Parent ViewController. - parameter msg: Display message. */ static func DispAlertMsg( pvc:UIViewController, msg: String ){ let titleText = NSLocalizedString("STR_ALERT", comment: "ALERT") let alertController: UIAlertController = UIAlertController(title: titleText, message: msg, preferredStyle: .alert) let actionOK = UIAlertAction(title: "OK", style: .default){ (action) -> Void in } alertController.addAction(actionOK) pvc.present(alertController, animated: true, completion: nil) } /** Displays a Confirmation dialog. - parameter pvc: ViewController Parent ViewController. - parameter msg: Display message. */ static func DispConfirmationMsg( pvc:UIViewController, msg: String, handler proc: (() -> Swift.Void)? = nil ) { let titleText = NSLocalizedString("STR_CONFIRMATION", comment: "Confirmation") let alertController: UIAlertController = UIAlertController(title: titleText, message: msg, preferredStyle: .alert) let actionYes = UIAlertAction(title: NSLocalizedString("STR_YES", comment: "Yes"), style: .destructive, handler:{(action:UIAlertAction!) in proc!()}) alertController.addAction(actionYes) let actionNo = UIAlertAction(title: NSLocalizedString("STR_NO", comment: "No"), style: .cancel) alertController.addAction(actionNo) pvc.present(alertController, animated: true, completion: nil) } /** Displays a selection dialog for navigating to the application setting page. - parameter pvc: ViewController Parent ViewController. - parameter msg: Display message. */ static func DispSelectSettingPage( pvc:UIViewController, msg: String, cancelHandler: (() -> Swift.Void)? = nil ){ let titleText = NSLocalizedString("STR_ALERT", comment: "ALERT") let alertController: UIAlertController = UIAlertController(title: titleText, message: msg, preferredStyle: .alert) // Create action and added. // Cancel let cancelAction:UIAlertAction = UIAlertAction(title: NSLocalizedString("STR_CANCEL", comment: "Cancel"), style: UIAlertActionStyle.cancel, handler:{(action:UIAlertAction!) in cancelHandler!() }) // To Setting page let defaultAction:UIAlertAction = UIAlertAction(title: NSLocalizedString("STR_TO_SETTING_PAGE", comment: "To settings"), style: UIAlertActionStyle.default, handler:{ (action:UIAlertAction!) -> Void in let url = NSURL(string:UIApplicationOpenSettingsURLString) if #available(iOS 10.0, *) { UIApplication.shared.open(url! as URL,options: [:], completionHandler: nil ) } else { UIApplication.shared.openURL(url! as URL) } }) alertController.addAction(cancelAction) alertController.addAction(defaultAction) pvc.present(alertController, animated: true, completion: nil) } } /** - UIColorへ16進数にてRGB指定できる機能を拡張 */ extension UIColor { class func hexStr ( hexStr : NSString, alpha : CGFloat) -> UIColor { let alpha = alpha var hexStr = hexStr hexStr = hexStr.replacingOccurrences(of: "#", with: "") as NSString let scanner = Scanner(string: hexStr as String) var color: UInt32 = 0 if scanner.scanHexInt32(&color) { let r = CGFloat((color & 0xFF0000) >> 16) / 255.0 let g = CGFloat((color & 0x00FF00) >> 8) / 255.0 let b = CGFloat(color & 0x0000FF) / 255.0 return UIColor(red:r,green:g,blue:b,alpha:alpha) } else { print("invalid hex string") return UIColor.white; } } } /** - UIImageへ画像サイズ調整機能を拡張 */ extension UIImage{ func ResizeUIImage(width : CGFloat, height : CGFloat)-> UIImage!{ UIGraphicsBeginImageContext(CGSize(width: width, height: height)) self.draw(in: CGRect(x: 0, y: 0, width: width, height: height)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } } /** - 最前面のUIViewController取得機能を拡張 */ extension UIApplication { class func GetTopViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? { if let navigationController = controller as? UINavigationController { return GetTopViewController(controller: navigationController.visibleViewController) } if let tabController = controller as? UITabBarController { if let selected = tabController.selectedViewController { return GetTopViewController(controller: selected) } } if let presented = controller?.presentedViewController { return GetTopViewController(controller: presented) } return controller } } /** - UIViewの枠設定機能を拡張 */ extension UIView { // 枠線の色 @IBInspectable var borderColor: UIColor? { get { return layer.borderColor.map { UIColor(cgColor: $0) } } set { layer.borderColor = newValue?.cgColor } } // 枠線のWidth @IBInspectable var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } // 角丸設定 @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } }
mit
115e2587b96489e15d7fc3f661f5769e
32.576
142
0.570646
5.130807
false
false
false
false
team-supercharge/boa
lib/boa/module/templates/swift/Wireframe.swift
1
1968
// // <%= @prefixed_module %>Wireframe.swift // <%= @project %> // // Created by <%= @author %> on <%= @date %>. // // import Foundation import UIKit class <%= @prefixed_module %>Wireframe: NSObject { weak var rootWireframe: RootWireframe? weak var presenter: <%= @prefixed_module %>Presenter? weak var viewController: <%= @prefixed_module %>ViewController? var parameters: Any? func presentSelfFromViewController(viewController: UIViewController) { // save reference self.viewController = <%= @prefixed_module %>ViewController(nibName: "<%= @prefixed_module %>ViewController", bundle: nil) // view <-> presenter self.presenter?.userInterface = self.viewController self.viewController?.eventHandler = self.presenter // present controller // *** present self with RootViewController } class func presentFromViewController(_ viewController: UIViewController, _ parameters: Any? = nil) { let wireframe = <%= @prefixed_module %>Wireframe() let presenter = <%= @prefixed_module %>Presenter() let interactor = <%= @prefixed_module %>Interactor() let dataManager = <%= @prefixed_module %>DataManager() let view = <%= @prefixed_module %>ViewController(nibName: "<%= @prefixed_module %>ViewController", bundle: nil) presenter.wireframe = wireframe presenter.interactor = interactor presenter.userInterface = view view.eventHandler = presenter wireframe.presenter = presenter wireframe.viewController = view wireframe.parameters = parameters interactor.presenter = presenter interactor.dataManager = dataManager // Present View if let nav = viewController.navigationController { nav.pushViewController(view, animated: true) } else { viewController.present(view, animated: true, completion: nil) } } }
mit
ae6174878f5a0a2c7b175a313d0f142d
31.262295
130
0.645833
5.125
false
false
false
false
idelfonsog2/tumblr-app
tumblr-app/TMDetailBlogViewController.swift
1
2482
// // TMDetailBlogViewController.swift // tumblr-app // // Created by Idelfonso on 10/19/16. // Copyright © 2016 Idelfonso. All rights reserved. // import UIKit import OAuthSwift class TMDetailBlogViewController: UIViewController { //MARK: Properties var blog: TMBlog? var oauth1swift: OAuth1Swift? = nil var session = TMClient.sharedInstance() //MARK: IBOutlets @IBOutlet weak var blogNameLabel: UILabel! @IBOutlet weak var followButton: UIButton! //MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() oauth1swift = TMClient.sharedInstance().oauth1swift as! OAuth1Swift? } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: IBActions @IBAction func followUser(_ sender: AnyObject) { //Decompose blog url string let usersBlogURL = self.getBlogURL(url: (blog?.url)!) //Query Params for /user/foloww let parameters = [ ParameterKeys.URL: usersBlogURL, ParameterKeys.ApiKey: ParameterValues.ApiKey ] //POST request to /user/follow let _ = oauth1swift?.client.request(session.tumblrURL(Methods.FollowUser), method: .POST, parameters: parameters, headers: nil, success: { (data, error) in DispatchQueue.main.async { self.displayAlert("Following user") } }, failure: { error in print(error) self.displayAlert("Fail to Follow") }) } @IBAction func dismissViewController(_ sender: AnyObject) { self.dismiss(animated: true, completion: nil) } //MARK: Alert func displayAlert(_ text: String) { let alert = UIAlertController(title: "Result", message: text, preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: nil) alert.addAction(okAction) self.present(alert, animated: true, completion: nil) } //Decompose the URL from search results func getBlogURL(url: String) -> String { let scheme = URL(string: url)?.scheme let host = URL(string: url)?.host return "\(scheme!)://\(host!)" } }
mit
aeb330a08b1880109beb31c02fe694f5
25.967391
146
0.583636
4.734733
false
false
false
false
sarvex/SwiftRecepies
HomeKit/Managing the User’s Home in HomeKit/Managing the User’s Home in HomeKit/AddHomeViewController.swift
1
2210
// // AddHomeViewController.swift // Managing the User’s Home in HomeKit // // Created by Vandad Nahavandipoor on 7/24/14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // // These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook // If you use these solutions in your apps, you can give attribution to // Vandad Nahavandipoor for his work. Feel free to visit my blog // at http://vandadnp.wordpress.com for daily tips and tricks in Swift // and Objective-C and various other programming languages. // // You can purchase "iOS 8 Swift Programming Cookbook" from // the following URL: // http://shop.oreilly.com/product/0636920034254.do // // If you have any questions, you can contact me directly // at [email protected] // Similarly, if you find an error in these sample codes, simply // report them to O'Reilly at the following URL: // http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254 import UIKit import HomeKit class AddHomeViewController: UIViewController { @IBOutlet weak var textField: UITextField! var homeManager: HMHomeManager! func displayAlertWithTitle(title: String, message: String){ let controller = UIAlertController(title: title, message: message, preferredStyle: .Alert) controller.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(controller, animated: true, completion: nil) } @IBAction func addHome(){ if count(textField.text) == 0{ displayAlertWithTitle("Home name", message: "Please enter the home name") return } homeManager.addHomeWithName(textField.text, completionHandler: {[weak self] (home: HMHome!, error: NSError!) in let strongSelf = self! if error != nil{ strongSelf.displayAlertWithTitle("Error happened", message: "\(error)") } else { strongSelf.navigationController!.popViewControllerAnimated(true) } }) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) textField.becomeFirstResponder() } }
isc
2b565573f4ee4edae29f7842361eeb1c
28.44
83
0.679348
4.506122
false
false
false
false
BennyKJohnson/OpenCloudKit
Sources/CKFetchErrorDictionary.swift
1
3524
// // CKFetchErrorDictionary.swift // OpenCloudKit // // Created by Benjamin Johnson on 15/07/2016. // // import Foundation protocol CKFetchErrorDictionaryIdentifier { init?(dictionary: [String: Any]) static var identifierKey: String { get } } extension CKRecordZoneID: CKFetchErrorDictionaryIdentifier { @nonobjc static let identifierKey = "zoneID" } // TODO: Fix error handling struct CKErrorDictionary { let reason: String let serverErrorCode: String let retryAfter: NSNumber? let redirectURL: String? let uuid: String init?(dictionary: [String: Any]) { guard let uuid = dictionary["uuid"] as? String, let reason = dictionary[CKRecordFetchErrorDictionary.reasonKey] as? String, let serverErrorCode = dictionary[CKRecordFetchErrorDictionary.serverErrorCodeKey] as? String else { return nil } self.uuid = uuid self.reason = reason self.serverErrorCode = serverErrorCode self.retryAfter = (dictionary[CKRecordFetchErrorDictionary.retryAfterKey] as? NSNumber) self.redirectURL = dictionary[CKRecordFetchErrorDictionary.redirectURLKey] as? String } func error() -> NSError { let errorCode = CKErrorCode.errorCode(serverError: serverErrorCode)! var userInfo: NSErrorUserInfoType = [NSLocalizedDescriptionKey: reason.bridge() as Any, "serverErrorCode": serverErrorCode.bridge() as Any] if let redirectURL = redirectURL { userInfo[CKErrorRedirectURLKey] = redirectURL.bridge() } if let retryAfter = retryAfter { userInfo[CKErrorRetryAfterKey] = retryAfter as NSNumber } return NSError(domain: CKErrorDomain, code: errorCode.rawValue, userInfo: userInfo) } } struct CKFetchErrorDictionary<T: CKFetchErrorDictionaryIdentifier> { let identifier: T let reason: String let serverErrorCode: String let retryAfter: NSNumber? let redirectURL: String? init?(dictionary: [String: Any]) { guard let identifier = T(dictionary: dictionary[T.identifierKey] as? [String: Any] ?? [:]), let reason = dictionary[CKRecordFetchErrorDictionary.reasonKey] as? String, let serverErrorCode = dictionary[CKRecordFetchErrorDictionary.serverErrorCodeKey] as? String else { return nil } self.identifier = identifier self.reason = reason self.serverErrorCode = serverErrorCode self.retryAfter = (dictionary[CKRecordFetchErrorDictionary.retryAfterKey] as? NSNumber) self.redirectURL = dictionary[CKRecordFetchErrorDictionary.redirectURLKey] as? String } func error() -> NSError { let errorCode = CKErrorCode.errorCode(serverError: serverErrorCode)! var userInfo: NSErrorUserInfoType = [NSLocalizedDescriptionKey: reason.bridge() as Any, "serverErrorCode": serverErrorCode.bridge() as Any] if let redirectURL = redirectURL { userInfo[CKErrorRedirectURLKey] = redirectURL.bridge() } if let retryAfter = retryAfter { userInfo[CKErrorRetryAfterKey] = retryAfter as NSNumber } return NSError(domain: CKErrorDomain, code: errorCode.rawValue, userInfo: userInfo) } }
mit
3f60557182ad79fd071671d086a4ff4b
30.464286
147
0.643019
5.129549
false
false
false
false
jizhouli/local-weather-app-iOS
proj1-weather/ViewController.swift
1
7424
// // ViewController.swift // proj1-weather // // Created by 小拿 on 15/3/8. // Copyright (c) 2015年 Justin. All rights reserved. // import UIKit import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate { let locationManager: CLLocationManager = CLLocationManager() @IBOutlet weak var location: UILabel! @IBOutlet weak var icon: UIImageView! @IBOutlet weak var temperature: UILabel! @IBOutlet weak var loadingIndicator: UIActivityIndicatorView! @IBOutlet weak var loadingMessage: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // 加载背景图 let background = UIImage(named: "background.png") self.view.backgroundColor = UIColor(patternImage: background!) self.loadingIndicator.startAnimating() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest if (ios8()) { locationManager.requestAlwaysAuthorization() } locationManager.startUpdatingLocation() } func ios8() -> Bool { return UIDevice.currentDevice().systemVersion == "8.1" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { var location: CLLocation = locations[locations.count-1] as CLLocation println("debug info in locationManager1") if (location.horizontalAccuracy > 0) { // 获取经纬度 println(location.coordinate.latitude) println(location.coordinate.longitude) // 根据经纬度查询天气接口 self.updateWeatherInfo(location.coordinate.latitude, longitude: location.coordinate.longitude) // 关闭地理位置获取 locationManager.stopUpdatingLocation() } } func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { println("错误信息:\(error)") self.loadingMessage.text = "地理位置信息获取失败!-\(error)" } // 封装天气接口调用 func updateWeatherInfo(latitude: CLLocationDegrees, longitude: CLLocationDegrees) { // 获取AFNetworking的实例 let manager = AFHTTPRequestOperationManager() // 天气接口URL let url = "http://api.openweathermap.org/data/2.5/weather" // 初始化URL参数 let params = ["lat": latitude, "lon": longitude, "cnt": 0] manager.GET(url, parameters: params, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in println("JSON: " + responseObject.description!) //根据天气信息更新UI self.updateUISucess(responseObject as NSDictionary!) }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in println("Error: " + error.localizedDescription) } ) } func updateUISucess(jsonResult: NSDictionary!) { // 关闭进程控件 self.loadingIndicator.stopAnimating() self.loadingIndicator.hidden = true self.loadingMessage.text = nil if let tempResult = jsonResult["main"]?["temp"]? as? Double { // 设置温度 var temperature: Double if (jsonResult["sys"]?["country"]? as String == "US") { temperature = round(((tempResult - 273.15) * 1.8) + 32) } else { // temperature = round(tempResult - 273.15) } self.temperature.text = "\(temperature)℃" self.temperature.font = UIFont.boldSystemFontOfSize(60) // 设置城市名称 var name = jsonResult["name"]? as String self.location.text = "\(name)" self.location.font = UIFont.boldSystemFontOfSize(25) // 设置图标 var condition = (jsonResult["weather"]? as NSArray)[0]["id"] as Int var sunrise = jsonResult["sys"]?["sunrise"]? as Double var sunset = jsonResult["sys"]?["sunset"]? as Double var nightTime = false var now = NSDate().timeIntervalSince1970 if (now < sunrise || now > sunset) { nightTime = true } self.updateWeatherIcon(condition, nightTime: nightTime) } else { // self.loadingMessage.text = "天气信息获取成功,但解析失败!" } } func updateWeatherIcon(condition: Int, nightTime: Bool) { // Thunderstorm if (condition < 300) { if nightTime { self.icon.image = UIImage(named: "tstorm1_night") } else { self.icon.image = UIImage(named: "tstorm1") } } // Drizzle else if (condition < 500) { self.icon.image = UIImage(named: "light_rain") } // Rain / Freezing rain / Shower rain else if (condition < 600) { self.icon.image = UIImage(named: "shower3") } // Snow else if (condition < 700) { self.icon.image = UIImage(named: "snow4") } // Fog / Mist / Haze / etc. else if (condition < 771) { if nightTime { self.icon.image = UIImage(named: "fog_night") } else { self.icon.image = UIImage(named: "fog") } } // Tornado / Squalls else if (condition < 800) { self.icon.image = UIImage(named: "tstorm3") } // Sky is clear else if (condition == 800) { if (nightTime){ self.icon.image = UIImage(named: "sunny_night") } else { self.icon.image = UIImage(named: "sunny") } } // few / scattered / broken clouds else if (condition < 804) { if (nightTime){ self.icon.image = UIImage(named: "cloudy2_night") } else{ self.icon.image = UIImage(named: "cloudy2") } } // overcast clouds else if (condition == 804) { self.icon.image = UIImage(named: "overcast") } // Extreme else if ((condition >= 900 && condition < 903) || (condition > 904 && condition < 1000)) { self.icon.image = UIImage(named: "tstorm3") } // Cold else if (condition == 903) { self.icon.image = UIImage(named: "snow5") } // Hot else if (condition == 904) { self.icon.image = UIImage(named: "sunny") } // Weather condition is not available else { self.icon.image = UIImage(named: "dunno") } } }
mit
3f3f765056b8a0db8e345340f0e003b3
30.561404
106
0.532935
4.942308
false
false
false
false
goyuanfang/SXSwiftWeibo
103 - swiftWeibo/103 - swiftWeibo/Classes/UI/Home/SXRefreshControl.swift
1
5542
// // SXRefreshControl.swift // 103 - swiftWeibo // // Created by 董 尚先 on 15/3/9. // Copyright (c) 2015年 shangxianDante. All rights reserved. // import UIKit class SXRefreshControl: UIRefreshControl { lazy var refreshV : RefreshView = { /// 显示箭头,不转 return RefreshView.refreshView(isLoading: false) }() override func willMoveToWindow(newWindow: UIWindow?) { refreshV.frame = self.bounds } /// 添加到父控件添加观察者 override func awakeFromNib() { self.addSubview(refreshV) self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.New, context: nil) } /// 销毁观察者 deinit{ println("SXRefreshControl 888") self.removeObserver(self, forKeyPath: "frame") } /// 正在加载动画效果 var isLoading = false /// 旋转提示图标记 var isRotateTip = false override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { if self.frame.origin.y > 0{ return } // $$$$$ /// 如果正在刷新,并且也正在动画,直接返回性能压力减小 if refreshing && !isLoading{ refreshV.showLoading() isLoading = true return } if self.frame.origin.y < -50 && !isRotateTip { isRotateTip = true refreshV.rotateTipIcon(isRotateTip) }else if self.frame.origin.y > -50 && isRotateTip { isRotateTip = false refreshV.rotateTipIcon(isRotateTip) } } /// 结束刷新 override func endRefreshing() { super.endRefreshing() /// 停止动画 refreshV.stopLoading() /// 修正标记 isLoading = false } } class RefreshView: UIView { class func refreshView(isLoading:Bool = false) -> RefreshView { let v = NSBundle.mainBundle().loadNibNamed("RefreshView", owner: nil, options: nil).last as! RefreshView /// 两个都调用此方法 // $$$$$ v.tipView.hidden = isLoading v.loadingView.hidden = !isLoading return v } /// 提示视图 @IBOutlet weak var tipView: UIView! /// 提示图标 @IBOutlet weak var tipIcon: UIImageView! /// 加载视图 @IBOutlet weak var loadingView: UIView! /// 加载图标 @IBOutlet weak var loadingIcon: UIImageView! func showLoading(){ tipView.hidden = true loadingView.hidden = false /// 添加动画 loadingAnimation() } /// 加载动画 func loadingAnimation(){ let animate = CABasicAnimation(keyPath: "transform.rotation") animate.toValue = 2 * M_PI animate.repeatCount = MAXFLOAT animate.duration = 0.5 /// 将动画添加到图层 loadingIcon.layer.addAnimation(animate, forKey: nil) } /// 停止加载动画 func stopLoading(){ loadingIcon.layer.removeAllAnimations() tipView.hidden = false loadingView.hidden = true } /// 旋转提示图标 // $$$$$ func rotateTipIcon(clockWise: Bool) { // 旋转都是就近原则,如果转半圈,会找近路 var angel = CGFloat(M_PI + 0.01) if clockWise { angel = CGFloat(M_PI - 0.01) } weak var weakSelf = self UIView.animateWithDuration(0.5, animations: { () -> Void in // 旋转提示图标 180 weakSelf!.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, angel) }) } /// MARK: - 上拉刷新部分代码 weak var parentView :UITableView? /// 给parentView添加观察者 func addPullupOberserver(parentView:UITableView,pullupLoadData:()->()){ self.parentView = parentView self.parentView = parentView self.PullupLoadData = pullupLoadData self.parentView!.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil) } deinit{ println("RefreshView 888") // parentView!.removeObserver(self, forKeyPath: "contentOffset") } /// 上啦加载数据标记 var isPullupLoading = false /// 上啦刷新的闭包 var PullupLoadData:(()->())? override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { /// 界面首次加载时,这里不显示上啦 if self.frame.origin.y == 0{ return } if (parentView!.bounds.size.height + parentView!.contentOffset.y) > CGRectGetMaxY(self.frame){ // $$$$$ /// 保证上啦只有一次是有效的 if !isPullupLoading{ isPullupLoading = true showLoading() /// 如果有闭包就执行闭包 if PullupLoadData != nil{ PullupLoadData!() } } } } }
mit
c31a2804d27da564743a860c6564e779
24.1133
156
0.540996
4.724745
false
false
false
false
RubyNative/RubyKit
Dir.swift
2
6388
// // Dir.swift // SwiftRuby // // Created by John Holdsworth on 28/09/2015. // Copyright © 2015 John Holdsworth. All rights reserved. // // $Id: //depot/SwiftRuby/Dir.swift#15 $ // // Repo: https://github.com/RubyNative/SwiftRuby // // See: http://ruby-doc.org/core-2.2.3/Dir.html // import Darwin open class Dir: RubyObject, array_like { let dirpath: String var unixDIR: UnsafeMutablePointer<DIR>? // Dir[ string [, string ...] ] → array init?(dirname: string_like, file: StaticString = #file, line: UInt = #line) { dirpath = dirname.to_s unixDIR = opendir(dirpath) super.init() if unixDIR == nil { SRError("opendir '\(dirpath.to_s)' failed", file: file, line: line) return nil } } // MARK: Class Methods open class func new(_ string: string_like, file: StaticString = #file, line: UInt = #line) -> Dir? { return Dir(dirname: string, file: file, line: line) } open class func open(_ string: string_like, file: StaticString = #file, line: UInt = #line) -> Dir? { return new(string, file: file, line: line) } open class func chdir(_ string: string_like, file: StaticString = #file, line: UInt = #line) -> Bool { return unixOK("Dir.chdir '\(string.to_s)", Darwin.chdir(string.to_s), file: file, line: line) } open class func chroot(_ string: string_like, file: StaticString = #file, line: UInt = #line) -> Bool { return unixOK("Dir.chroot '\(string.to_s)", Darwin.chroot(string.to_s), file: file, line: line) } open class func delete(_ string: string_like, file: StaticString = #file, line: UInt = #line) -> Bool { return unixOK("Dir.rmdir '\(string.to_s)", Darwin.rmdir(string.to_s), file: file, line: line) } open class func entries(_ dirname: string_like, file: StaticString = #file, line: UInt = #line) -> [String] { var out = [String]() foreach(dirname) { (name) in out.append(name) } return out } open class func exist(_ dirname: string_like, file: StaticString = #file, line: UInt = #line) -> Bool { return File.exist(dirname, file: file, line: line) } open class func exists(_ dirname: string_like, file: StaticString = #file, line: UInt = #line) -> Bool { return exist(dirname, file: file, line: line) } open class func foreach(_ dirname: string_like, _ block: (String) -> ()) { if let dir = Dir(dirname: dirname, file: #file, line: #line) { dir.each { (name) in block(name) } } } open class var getwd: String? { var cwd = [Int8](repeating: 0, count: Int(PATH_MAX)) if !unixOK("Dir.getwd", Darwin.getcwd(&cwd, cwd.count) != nil ? 0 : 1, file: #file, line: #line) { return nil } return String(validatingUTF8: cwd) } open class func glob(_ pattern: string_like, _ flags: Int32 = 0, file: StaticString = #file, line: UInt = #line) -> [String]? { return pattern.to_s.withCString { var pglob = glob_t() if (unixOK("Dir.glob", Darwin.glob($0, flags, nil, &pglob), file: file, line: line)) { defer { globfree(&pglob) } return (0..<Int(pglob.gl_matchc)).map { String(cString: U(U(pglob.gl_pathv)[$0])) } } return nil } } open class func home(_ user: string_like? = nil, file: StaticString = #file, line: UInt = #line) -> String? { var user = user?.to_s var buff = [Int8](repeating: 0, count: Int(PATH_MAX)) var ret: UnsafeMutablePointer<passwd>? var info = passwd() if user == nil || user == "" { if !unixOK("Dir.getpwuid", getpwuid_r(geteuid(), &info, &buff, buff.count, &ret), file: file, line: line) { return nil } user = String(validatingUTF8: info.pw_name) } if !unixOK("Dir.getpwnam \(user!.to_s)", getpwnam_r(user!, &info, &buff, buff.count, &ret), file: file, line: line) { return nil } return String(validatingUTF8: info.pw_dir) } open class func mkdir(_ string: string_like, _ mode: Int = 0o755, file: StaticString = #file, line: UInt = #line) -> Bool { return unixOK("Dir.mkdir '\(string.to_s)", Darwin.mkdir(string.to_s, mode_t(mode)), file: file, line: line) } open class var pwd: String? { return getwd } open class func rmdir(_ string: string_like, file: StaticString = #file, line: UInt = #line) -> Bool { return delete(string, file: file, line: line) } open class func unlink(_ string: string_like, file: StaticString = #file, line: UInt = #line) -> Bool { return delete(string, file: file, line: line) } // MARK: Instance methods @discardableResult open func close(_ file: StaticString = #file, line: UInt = #line) -> Bool { let ok = unixOK("Dir.closedir '\(dirpath)'", closedir(unixDIR), file: file, line: line) unixDIR = nil return ok } @discardableResult open func each(_ block: (String) -> ()) -> Dir { while let name = read() { block(name) } return self } open var fileno: Int { return Int(dirfd(unixDIR)) } open var inspect: String { return dirpath } open var path: String { return dirpath } open var pos: Int { return Int(telldir(unixDIR)) } open func read() -> String? { let ent = readdir(unixDIR) if ent != nil { return withUnsafeMutablePointer (to: &ent!.pointee.d_name) { String(validatingUTF8: UnsafeMutableRawPointer($0).assumingMemoryBound(to: CChar.self)) } } return nil } open func rewind() { Darwin.rewinddir(unixDIR) } open func seek(_ pos: Int) { seekdir(unixDIR, pos) } open var tell: Int { return pos } open var to_a: [String] { var out = [String]() each { (entry) in out .append(entry) } return out } open var to_path: String { return dirpath } deinit { if unixDIR != nil { close() } } }
mit
bcffd21c9cb7ffc4a7eeda93f88bf141
29.260664
131
0.554424
3.636105
false
false
false
false
universeiscool/MediaPickerController
MediaPickerController/PhotoCollectionViewCell.swift
1
3198
// // PhotoCollectionViewCell.swift // MediaPickerController // // Created by Malte Schonvogel on 23.11.15. // Copyright © 2015 universeiscool UG (haftungsbeschränkt). All rights reserved. // import UIKit import Photos final class PhotoCollectionViewCell: UICollectionViewCell { let kSelectedBorderColor = UIColor(red: 0, green: 155/255, blue: 255/255, alpha: 1).CGColor let kDisabledBorderColor = UIColor.grayColor().CGColor var image: UIImage? let checkedIcon = UIImage(named: "AssetsPickerChecked") lazy var imageView:UIImageView = { let view = UIImageView(frame: self.contentView.bounds) view.contentMode = UIViewContentMode.ScaleAspectFill view.clipsToBounds = true view.layer.borderColor = self.kSelectedBorderColor view.layer.borderWidth = 0 return view }() override var selected: Bool { get { return super.selected } set { let hasChanged = selected != newValue super.selected = newValue if UIView.areAnimationsEnabled() && hasChanged { UIView.animateWithDuration(NSTimeInterval(0.1), animations: { () -> Void in self.updateSelected(newValue) // Scale all views down a little self.transform = CGAffineTransformMakeScale(0.95, 0.95) }) { (finished: Bool) -> Void in UIView.animateWithDuration(NSTimeInterval(0.1), animations: { () -> Void in // And then scale them back upp again to give a bounce effect self.transform = CGAffineTransformMakeScale(1.0, 1.0) }, completion: nil) } } else { self.updateSelected(newValue) } } } var enabled = true { didSet { updateEnabled(enabled) } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.blackColor() contentView.addSubview(imageView) opaque = true isAccessibilityElement = true accessibilityTraits = UIAccessibilityTraitImage } override func layoutSubviews() { super.layoutSubviews() imageView.frame = contentView.bounds } func bind(image:UIImage?) { imageView.image = image updateSelected(selected) updateEnabled(enabled) } override func prepareForReuse() { super.prepareForReuse() imageView.image = nil enabled = true } private func updateSelected(selected:Bool) { imageView.alpha = selected ? 0.85 : 1.0 imageView.layer.borderWidth = selected ? 4 : 0 } private func updateEnabled(enabled:Bool) { imageView.layer.borderColor = enabled ? kSelectedBorderColor : kDisabledBorderColor imageView.layer.borderWidth = enabled ? 0 : 4 imageView.alpha = enabled ? 1.0 : 0.85 } }
mit
a8487d8032ee3a0fb66cc354691e255b
28.878505
99
0.588548
5.064976
false
false
false
false
LDlalala/LDZBLiving
LDZBLiving/LDZBLiving/Classes/tools/LDNetworkTool.swift
1
978
// // LDNetworkTool.swift // LDZBLiving // // Created by 李丹 on 17/8/10. // Copyright © 2017年 LD. All rights reserved. // import UIKit import Alamofire enum MethodType { case get case post } class LDNetworkTool { class func requestData(_ type : MethodType , URLString : String ,parameters : [String : Any]? = nil , finishedCallback : @escaping (_ result : Any) -> Void) { // 获取网络请求方式 let method = type == .get ? HTTPMethod.get : HTTPMethod.post // 请求数据 Alamofire.request(URLString, method: method, parameters: parameters).validate(contentType: ["text/plain"]).responseJSON { (response) in // 3.获取结果 guard let result = response.result.value else { print(response.result.error!) return } // 4.将结果回调出去 finishedCallback(result) } } }
mit
72dafed6748b5eeb035e8aea235041df
24
162
0.566486
4.342723
false
false
false
false
ztyjr888/WeChat
WeChat/Plugins/Chat/WeChatChatRecordIndicatorView.swift
1
5426
// // WeChatChatRecordIndicatorView.swift // WeChat // // Created by Smile on 16/3/29. // Copyright © 2016年 [email protected]. All rights reserved. // import UIKit let talkMessage:String = "手指上滑,取消发送" let talkCancelMessage:String = "松开手指,取消发送" let talkButtonDefaultMessage:String = "按住 说话" let talkButtonHightedMessage:String = "松开结束" let shortTalkMessage:String = "说话时间太短" //时间太短view class WeChatChatRecordShortView:WeChatChatRecordIndicatorNormalView { init(frame: CGRect) { super.init(frame: frame, text: shortTalkMessage, image: UIImage(named: "chatTooShort")!) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //录音取消view class WeChatChatRecordIndicatorCancelView: WeChatChatRecordIndicatorNormalView { init(frame: CGRect) { super.init(frame: frame, text: talkCancelMessage,textColor:UIColor.whiteColor(),image: UIImage(named: "chatCancel")!) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class WeChatChatRecordIndicatorView: WeChatChatRecordIndicatorNormalView { let images:[UIImage] init(frame: CGRect) { self.images = [UIImage(named: "record_animate_01")!, UIImage(named: "record_animate_02")!, UIImage(named: "record_animate_03")!, UIImage(named: "record_animate_04")!, UIImage(named: "record_animate_05")!, UIImage(named: "record_animate_06")!, UIImage(named: "record_animate_07")!, UIImage(named: "record_animate_08")!, UIImage(named: "record_animate_09")!] super.init(frame: frame,text:talkMessage,image: images[0]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARKS: 显示文本 func showText(text: String, textColor: UIColor = UIColor.blackColor()) { textLabel.textColor = textColor textLabel.text = text } func updateLevelMetra(levelMetra: Float) { if levelMetra > -20 { showMetraLevel(8) } else if levelMetra > -25 { showMetraLevel(7) }else if levelMetra > -30 { showMetraLevel(6) } else if levelMetra > -35 { showMetraLevel(5) } else if levelMetra > -40 { showMetraLevel(4) } else if levelMetra > -45 { showMetraLevel(3) } else if levelMetra > -50 { showMetraLevel(2) } else if levelMetra > -55 { showMetraLevel(1) } else if levelMetra > -60 { showMetraLevel(0) } } func showMetraLevel(level: Int) { if level > images.count { return } performSelectorOnMainThread("showIndicatorImage:", withObject: NSNumber(integer: level), waitUntilDone: false) } func showIndicatorImage(level: NSNumber) { imageView.image = images[level.integerValue] } } class WeChatChatRecordIndicatorNormalView: UIView { let imageView: UIImageView let textLabel: UILabel init(frame: CGRect,text:String,textColor:UIColor = UIColor.whiteColor(),image:UIImage) { textLabel = UILabel() textLabel.textAlignment = .Center textLabel.font = UIFont.systemFontOfSize(13.0) textLabel.text = text textLabel.textColor = textColor imageView = UIImageView(frame: CGRectZero) imageView.image = image super.init(frame: frame) self.backgroundColor = UIColor(patternImage: UIImage(named: "bg")!) self.alpha = 0.6 // 增加毛玻璃效果 let visualView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) visualView.frame = self.bounds visualView.layer.cornerRadius = 10.0 self.layer.cornerRadius = 10.0 visualView.layer.masksToBounds = true addSubview(visualView) addSubview(imageView) addSubview(textLabel) imageView.translatesAutoresizingMaskIntoConstraints = false textLabel.translatesAutoresizingMaskIntoConstraints = false self.addConstraint(NSLayoutConstraint(item: imageView, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: imageView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: -15)) self.addConstraint(NSLayoutConstraint(item: textLabel, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: textLabel, attribute: .Top, relatedBy: .Equal, toItem: imageView, attribute: .Bottom, multiplier: 1, constant: 10)) self.addConstraint(NSLayoutConstraint(item: textLabel, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: 0)) translatesAutoresizingMaskIntoConstraints = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
9c7cfbc8b8ac02ebc30aba8e0b3b0772
34.264901
168
0.637934
4.301292
false
false
false
false
Yanze/TTFFCamp
TTFFCamp/Models/Database.swift
1
1524
// // Database.swift // TTFFCamp // // Created by Jimmy Nguyen on 3/10/16. // Copyright © 2016 The Taylor Family Foundation. All rights reserved. // import Foundation class Database { // get the full path to the Documents folder static func documentsDirectory() -> String { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) return paths[0] } // get the full path to file of project static func dataFilePath(schema: String) -> String { return "\(Database.documentsDirectory())/\(schema)" } static func save(arrayOfObjects: [AnyObject], toSchema: String, forKey: String) { let data = NSMutableData() let archiver = NSKeyedArchiver(forWritingWithMutableData: data) archiver.encodeObject(arrayOfObjects, forKey: "\(forKey)") archiver.finishEncoding() data.writeToFile(Database.dataFilePath(toSchema), atomically: true) //print("saved data", data) } static func all() -> [Plant] { var plants = [Plant]() let path = Database.dataFilePath(Plant.schema) if NSFileManager.defaultManager().fileExistsAtPath(path) { if let data = NSData(contentsOfFile: path) { let unarchiver = NSKeyedUnarchiver(forReadingWithData: data) plants = unarchiver.decodeObjectForKey(Plant.key) as! [Plant] unarchiver.finishDecoding() } } return plants } }
mit
17fe263585f25084c700d7ed3979977d
31.425532
98
0.634931
4.960912
false
false
false
false
sfurlani/addsumfun
Add Sum Fun/Add Sum Fun/ResultsViewController.swift
1
1637
// // ResultsViewController.swift // Add Sum Fun // // Created by SFurlani on 8/27/15. // Copyright © 2015 Dig-It! Games. All rights reserved. // import UIKit class ResultsViewController: UITableViewController { @IBOutlet weak var mainMenu: UIButton! @IBOutlet weak var newGame: UIButton! enum ReuseIdentifiers: String { case AnswerCell = "answerCell" } var gameData: GameType! override func viewDidLoad() { super.viewDidLoad() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return gameData?.answers.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(ReuseIdentifiers.AnswerCell.rawValue, forIndexPath: indexPath) // Configure the cell... let answer = gameData.answers[indexPath.row] cell.textLabel?.text = "\(answer.equation.lhs) + \(answer.equation.rhs) = \(answer.equation.result)" cell.detailTextLabel?.text = "\(answer.entered)" cell.detailTextLabel?.textColor = answer.isCorrect() ? UIColor.greenColor() : UIColor.redColor() cell.imageView?.image = UIImage(named: answer.isCorrect() ? "correct" : "incorrect" ) cell.imageView?.tintColor = answer.isCorrect() ? UIColor.greenColor() : UIColor.redColor() return cell } }
mit
aba0c86b59cc9bf9db04d419a29838ec
29.867925
125
0.669315
4.742029
false
false
false
false
romansorochak/ParallaxHeader
Exmple/BlurRoundIconParallaxVC.swift
1
2513
// // RoundIconParallaxVC.swift // ParallaxHeader // // Created by Roman Sorochak on 7/3/17. // Copyright © 2017 MagicLab. All rights reserved. // import UIKit class BlurRoundIconParallaxVC: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! weak var parallaxHeaderView: UIView? override func viewDidLoad() { super.viewDidLoad() setupParallaxHeader() } //MARK: private private func setupParallaxHeader() { let image = UIImage(named: "profile") let imageView = UIImageView() imageView.image = image imageView.contentMode = .scaleAspectFill parallaxHeaderView = imageView //setup bur view imageView.blurView.setup(style: UIBlurEffect.Style.dark, alpha: 1).enable() imageView.blurView.alpha = 0 tableView.parallaxHeader.view = imageView tableView.parallaxHeader.height = 400 tableView.parallaxHeader.minimumHeight = 120 tableView.parallaxHeader.mode = .centerFill tableView.parallaxHeader.parallaxHeaderDidScrollHandler = { parallaxHeader in //update alpha of blur view on top of image view parallaxHeader.view.blurView.alpha = 1 - parallaxHeader.progress } let roundIcon = UIImageView( frame: CGRect(x: 0, y: 0, width: 100, height: 100) ) roundIcon.image = image roundIcon.layer.borderColor = UIColor.white.cgColor roundIcon.layer.borderWidth = 2 roundIcon.layer.cornerRadius = roundIcon.frame.width / 2 roundIcon.clipsToBounds = true //add round image view to blur content view //do not use vibrancyContentView to prevent vibrant effect imageView.blurView.blurContentView?.addSubview(roundIcon) //add constraints using SnpaKit library roundIcon.snp.makeConstraints { make in make.center.equalToSuperview() make.width.height.equalTo(100) } } //MARK: table view data source/delegate func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.text = "some row text" return cell } }
mit
cb7d9130a7ed2f348364f2a37528f02e
29.634146
100
0.638933
5.095335
false
false
false
false
programmerC/JNews
JNews/SpringView.swift
1
2986
// // SpringView.swift // JNews // // Created by ChenKaijie on 16/7/28. // Copyright © 2016年 com.ckj. All rights reserved. // import UIKit import SnapKit class SpringView: UIView { var centerView: UIView? var bottomButton: UIButton? init(timeType: TimeType) { super.init(frame: CGRectMake(0, 0, WIDTH, HEIGHT)) if timeType == TimeType.Day { self.backgroundColor = UIColor.RGBColor(189, green: 189, blue: 189, alpha: 1) } else { self.backgroundColor = UIColor.blackColor() } centerView = UIView.init(frame: CGRectMake(15, HEIGHT, WIDTH - 30, 422*(WIDTH - 30)/(HEIGHT - 245))) centerView?.backgroundColor = UIColor.whiteColor() self.addSubview(centerView!) bottomButton = UIButton(frame: CGRectZero) bottomButton?.setImage(UIImage(named: "BackButton"), forState: .Normal) self.addSubview(bottomButton!) configuration() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configuration() { let gesture = UITapGestureRecognizer(target: self, action: #selector(SpringView.tapHandle(_:))) gesture.numberOfTapsRequired = 1 gesture.numberOfTouchesRequired = 1 self.addGestureRecognizer(gesture) bottomButton?.layer.borderWidth = 1 bottomButton?.layer.borderColor = UIColor.whiteColor().CGColor bottomButton?.layer.cornerRadius = 14.0 bottomButton?.layer.masksToBounds = true bottomButton?.snp_makeConstraints(closure: { (make) in make.bottom.equalTo(self.snp_bottom).offset(-16) make.centerX.equalTo(self) make.width.equalTo(28) make.height.equalTo(28) }) bottomButton?.addTarget(self, action: #selector(SpringView.dismiss), forControlEvents: .TouchUpInside) } //MARK: - TapGesture func tapHandle(sender: UITapGestureRecognizer) { self.dismiss() } //MARK: - Custom Method func show() { CurrentWindow.addSubview(self) UIView.animateWithDuration(0.8, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 8.0, options: .AllowUserInteraction, animations: { self.centerView?.frame.origin.y = 100 }) { (true) in self.centerView?.frame.origin.y = 100 } /* * usingSpringWithDamping 参数从0.0-1.0,数值越小,弹簧效果越明显 * initialSpringVelocity 表示初始速度,数值越大一开始移动越快 */ } func dismiss() { self.centerView?.frame.origin.y = 100 UIView.animateWithDuration(0.6, animations: { self.alpha = 0 self.centerView?.frame.origin.y = HEIGHT }) { (true) in self.alpha = 0 self.removeFromSuperview() } } }
gpl-3.0
01b87af61a1b8d4c4eba35ed5a5c0d4c
32.147727
152
0.607131
4.406344
false
false
false
false
socialbanks/ios-wallet
SocialWallet/UserLocalData.swift
1
4128
// // UserData.swift // SocialWallet // // Created by Mauricio de Oliveira on 5/9/15. // Copyright (c) 2015 SocialBanks. All rights reserved. // import Foundation import Security class UserLocalData: NSObject { var id:String var secret:String? var bt:BTBIP32Key? required init?(parseId: String) { self.id = parseId let defaults:NSUserDefaults = NSUserDefaults.standardUserDefaults() self.secret = defaults.objectForKey("secret") as? String if self.secret != nil { var secretString:NSString = self.secret! as NSString self.bt = BTBIP32Key(secret: secretString.hexToData(), andPubKey: nil, andChain: nil, andPath: nil) } } required init?(parseId: String, words:String) { self.id = parseId let secret:NSData? = BTBIP39.sharedInstance().toEntropy(words) if(secret == nil) { self.bt = nil return } var secretString:NSString = secret!.description as NSString secretString = secretString.stringByReplacingOccurrencesOfString(" ", withString: "") secretString = secretString.stringByReplacingOccurrencesOfString("<", withString: "") secretString = secretString.stringByReplacingOccurrencesOfString(">", withString: "") self.secret = secretString as String let defaults:NSUserDefaults = NSUserDefaults.standardUserDefaults() defaults.setObject(secretString, forKey: "secret") defaults.synchronize() self.bt = BTBIP32Key(secret: secret, andPubKey: nil, andChain: nil, andPath: nil) } func generatePrivateAddress() { // Random NSDATA let seed:NSMutableData = NSMutableData(length: 256)! SecRandomCopyBytes(kSecRandomDefault, 256, UnsafeMutablePointer<UInt8>(seed.mutableBytes)) self.bt = BTBIP32Key(seed: NSData(data:seed)) let secretData:NSData = self.bt!.secret var secretString:NSString = secretData.description as NSString secretString = secretString.stringByReplacingOccurrencesOfString(" ", withString: "") secretString = secretString.stringByReplacingOccurrencesOfString("<", withString: "") secretString = secretString.stringByReplacingOccurrencesOfString(">", withString: "") self.secret = secretString as String let defaults:NSUserDefaults = NSUserDefaults.standardUserDefaults() defaults.setObject(secretString, forKey: "secret") defaults.synchronize() } func generatePrivateAddressWithSecret() { var secretString:NSString = self.secret! as NSString let defaults:NSUserDefaults = NSUserDefaults.standardUserDefaults() defaults.setObject(secretString, forKey: "secret") defaults.synchronize() self.bt = BTBIP32Key(secret: secretString.hexToData(), andPubKey: nil, andChain: nil, andPath: nil) } func redeemPrivateAddress(words:String) { let secret:NSData? = BTBIP39.sharedInstance().toEntropy(words) if(secret == nil) { self.bt = nil return } var secretString:NSString = secret!.description as NSString secretString = secretString.stringByReplacingOccurrencesOfString(" ", withString: "") secretString = secretString.stringByReplacingOccurrencesOfString("<", withString: "") secretString = secretString.stringByReplacingOccurrencesOfString(">", withString: "") self.secret = secretString as String let defaults:NSUserDefaults = NSUserDefaults.standardUserDefaults() defaults.setObject(secretString, forKey: "secret") defaults.synchronize() self.bt = BTBIP32Key(secret: secret, andPubKey: nil, andChain: nil, andPath: nil) } func getWords() -> String? { return BTBIP39.sharedInstance().toMnemonic(self.bt?.secret) } func getPublicKey() -> String { return bt!.address } func verify() -> Bool { return self.bt != nil } }
mit
b7d4359df7838b3f9d25c0be31efcaf3
36.198198
111
0.652132
5.003636
false
false
false
false
Shaquu/SwiftProjectsPub
WorldCapitals/WorldCapitals/ViewController.swift
1
3825
// // ViewController.swift // WorldCapitals // // Created by Tadeusz Wyrzykowski on 03.11.2016. // Copyright © 2016 Tadeusz Wyrzykowski. All rights reserved. // import UIKit class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet var imageOne: UIImageView! @IBOutlet var labelOne: UILabel! @IBOutlet var imageTwo: UIImageView! @IBOutlet var labelTwo: UILabel! @IBOutlet var message: UILabel! var data = [["Pick a Flag", "USA", "Italy", "China", "England"], ["Pick a Capital", "Bejing", "Rome", "Washington, DC", "London"]] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. imageOne.image = nil imageTwo.image = nil labelOne.text = "" labelTwo.text = "" message.text = "Match the Flags to the Capitals." } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfComponents(in pickerView: UIPickerView) -> Int { return data.count } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return data[component].count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return data[component][row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let itemOne = data[0][pickerView.selectedRow(inComponent: 0)] let itemTwo = data[1][pickerView.selectedRow(inComponent: 1)] let correctMessage = "The Capital of \(itemOne) is \(itemTwo)." let messageDefault = "Match the Flags to the Capitals." switch itemOne { case "USA": imageOne.image = #imageLiteral(resourceName: "usa") labelOne.text = itemOne case "Italy": imageOne.image = #imageLiteral(resourceName: "italy") labelOne.text = itemOne case "China": imageOne.image = #imageLiteral(resourceName: "china") labelOne.text = itemOne case "England": imageOne.image = #imageLiteral(resourceName: "england") labelOne.text = itemOne default: imageOne.image = nil labelOne.text = "" } var matched: Bool = false switch itemTwo { case "Bejing": imageTwo.image = #imageLiteral(resourceName: "beijing") labelTwo.text = itemTwo if itemOne == "China" { matched = true } case "Rome": imageTwo.image = #imageLiteral(resourceName: "rome") labelTwo.text = itemTwo if itemOne == "Italy" { matched = true } case "London": imageTwo.image = #imageLiteral(resourceName: "london") labelTwo.text = itemTwo if itemOne == "England" { matched = true } case "Washington, DC": imageTwo.image = #imageLiteral(resourceName: "washington") labelTwo.text = itemTwo if itemOne == "USA" { matched = true } default: imageTwo.image = nil labelTwo.text = "" } if matched { message.text = correctMessage message.textColor = UIColor.green } else { message.text = messageDefault message.textColor = UIColor.black } } }
gpl-3.0
fd064e3230101aa3f53f693a66235d70
29.83871
134
0.560931
4.852792
false
false
false
false
VivaReal/Compose
Example/Compose_ExampleTests/TestDetail.swift
1
1162
// // TestDetail.swift // Compose_Example // // Created by Bruno Bilescky on 25/10/16. // Copyright © 2016 VivaReal. All rights reserved. // import XCTest import Compose @testable import Compose_Example class TestDetail: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testExample() { var state = DetailViewState(photos: [], rooms: 0, area: 0, parkingSpaces: 0, bathrooms: 0, desc: nil, descriptionExpanded: false) var units = ComposeDetailView(with: state, expandCallback: {}) XCTAssert(units.count == 4) state.description = "Uhuuu" units = ComposeDetailView(with: state, expandCallback: {}) XCTAssert(units.count == 7) state.descriptionExpanded = true units = ComposeDetailView(with: state, expandCallback: {}) XCTAssert(units.count == 6) } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
mit
c4b4a13f2b311ad4b81337ec563adda4
25.386364
137
0.607235
4.268382
false
true
false
false
k0nserv/SwiftTracer
Pods/SwiftTracer-Core/Sources/Math/Vector.swift
1
2379
// // Vector.swift // SwiftTracer // // Created by Hugo Tunius on 09/08/15. // Copyright © 2015 Hugo Tunius. All rights reserved. // #if os(Linux) import Glibc #else import Darwin.C #endif public struct Vector : Equatable { public let x: Double public let y: Double public let z: Double public init(x: Double, y: Double, z: Double) { self.x = x self.y = y self.z = z } public func dot(other: Vector) -> Double { return x * other.x + y * other.y + z * other.z } public func cross(other: Vector) -> Vector { let x0 = y * other.z - z * other.y let y0 = z * other.x - x * other.z let z0 = x * other.y - y * other.x return Vector(x: x0, y: y0, z: z0) } public func length() -> Double { return sqrt(dot(self)) } public func normalize() -> Vector { let l = length() if l == 0 { return Vector(x: 0.0, y: 0.0, z: 0.0) } return Vector(x: (x / l), y: (y / l), z: (z / l)) } public func reflect(normal: Vector) -> Vector { return self - normal * 2 * self.dot(normal) } func fuzzyEquals(other: Vector) -> Bool { var result = true result = result && abs(x - other.x) < 0.001 result = result && abs(y - other.y) < 0.001 result = result && abs(z - other.z) < 0.001 return result } } public func ==(left: Vector, right: Vector) -> Bool { return left.x == right.x && left.y == right.y && left.z == right.z } public func -(left: Vector, right: Vector) -> Vector { return newVector(left: left, right: right) { $0 - $1 } } public func +(left: Vector, right: Vector) -> Vector { return newVector(left: left, right: right) { $0 + $1 } } public func *(left: Vector, right: Vector) -> Vector { return newVector(left: left, right: right) { $0 * $1 } } public prefix func -(left: Vector) -> Vector { return left * -1 } public func *(left: Vector, right: Double) -> Vector { return Vector(x: left.x * right, y: left.y * right, z: left.z * right) } private func newVector(left left: Vector, right: Vector, closure: (Double, Double) -> Double) -> Vector { return Vector(x: closure(left.x, right.x), y: closure(left.y, right.y), z: closure(left.z, right.z)) }
mit
45ac2408e6142b6201de6828996207db
22.544554
105
0.546678
3.204852
false
false
false
false
frodoking/GithubIOSClient
Github/Core/Common/Views/ViewPagerIndicator/ViewPagerIndicator.swift
1
9344
// // ViewPagerIndicator.swift // ViewPagerIndicator // // Created by Sai on 15/4/28. // Copyright (c) 2015年 Sai. All rights reserved. // import UIKit //@IBDesignable public class ViewPagerIndicator: UIControl { public enum IndicatorDirection{ case Top,Bottom } public var indicatorDirection: IndicatorDirection = .Bottom @IBInspectable public var indicatorHeight: CGFloat = 2.0 var indicatorIndex = -1 @IBInspectable public var animationDuration: CGFloat = 0.2 @IBInspectable public var autoAdjustSelectionIndicatorWidth: Bool = false//下横线是否适应文字大小 var isTransitioning = false//是否在移动 public var bouncySelectionIndicator = true//选择器动画是否支持bouncy效果 public var colors = Dictionary<String,UIColor>() public var titleFont :UIFont = UIFont.systemFontOfSize(17){ didSet{ self.layoutIfNeeded() } } public var titles = NSMutableArray(){ willSet(newTitles){ //先移除后添加 removeButtons() titles.addObjectsFromArray(newTitles as [AnyObject]) } didSet{ addButtons() } } var buttons = NSMutableArray() var selectionIndicator: UIView!//选中标识 var bottomLine: UIView!//底部横线 @IBInspectable public var showBottomLine: Bool = true{ didSet{ bottomLine.hidden = !showBottomLine } } public var delegate: ViewPagerIndicatorDelegate? public var count:Int { get{ return titles.count } } override public init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! commonInit() } func commonInit(){ selectionIndicator = UIView() bottomLine = UIView() self.addSubview(selectionIndicator) self.addSubview(bottomLine) } override public func layoutSubviews() { super.layoutSubviews() //设置默认选择哪个item if buttons.count == 0{ indicatorIndex = -1 } else if indicatorIndex < 0{ indicatorIndex = 0 } //button位置调整 for (var index = 0;index < buttons.count; index++ ){ let left = roundf((Float(self.bounds.size.width)/Float(self.buttons.count)) * Float(index)) let width = roundf(Float(self.bounds.size.width)/Float(self.buttons.count)) let button = buttons[index] as! UIButton button.frame = CGRectMake(CGFloat(left), 0, CGFloat(width),self.bounds.size.height) button.titleEdgeInsets = UIEdgeInsetsMake(0, 0, -4, 0) button.titleLabel?.font = titleFont button.setTitleColor(titleColorForState(UIControlState.Normal),forState: UIControlState.Normal) button.setTitleColor(titleColorForState(UIControlState.Selected),forState: UIControlState.Selected) if (index == indicatorIndex){ button.selected = true } } selectionIndicator.frame = selectionIndicatorRect() bottomLine.frame = bottomLineRect() selectionIndicator.backgroundColor = self.tintColor bottomLine.backgroundColor = self.tintColor self.sendSubviewToBack(selectionIndicator) } override public func willMoveToSuperview(newSuperview: UIView?) { super.willMoveToSuperview(newSuperview) self.layoutIfNeeded() } //底线Rect func bottomLineRect() ->CGRect{ //控件底部横线 var frame = CGRectMake(0, 0, self.frame.size.width, 0.5) if(indicatorDirection == .Top){ frame.origin.y = 0 } else{ frame.origin.y = self.frame.size.height } return frame } //获取指示器的Rect func selectionIndicatorRect() ->CGRect{ var frame = CGRect() let button = selectedButton() if indicatorIndex < 0 {return frame} let title = titles[indicatorIndex] as? NSString if title?.length<=0 || button == nil {return frame} if(indicatorDirection == .Top){ frame.origin.y = 0 } else{ frame.origin.y = button!.frame.size.height - indicatorHeight } //底部指示器如果宽度适应内容 if(autoAdjustSelectionIndicatorWidth){ var attributes:[String : AnyObject]! let attributedString = button?.attributedTitleForState(UIControlState.Selected) attributes = attributedString?.attributesAtIndex(0, effectiveRange: nil) frame.size = CGSizeMake(title!.sizeWithAttributes(attributes).width, indicatorHeight) //计算指示器x坐标 frame.origin.x = (button!.frame.size.width * CGFloat(indicatorIndex)) + (button!.frame.width - frame.size.width)/2 } else{//如果不是适应内容则宽度平分控件 frame.size = CGSizeMake(button!.frame.size.width, indicatorHeight) frame.origin.x = button!.frame.size.width * CGFloat(indicatorIndex) } return frame } //设置选中哪一个 public func setSelectedIndex(index: Int){ setSelected(true,index: index) } public func getSelectIndex() ->Int{ return indicatorIndex } //设置选中哪一个 func setSelected(selected: Bool, index: Int){ if(isTransitioning || indicatorIndex == index){return} disableAllButtonsSelection() enableAllButtonsInteraction(false) let duration:CGFloat = indicatorIndex < 0 ? 0 : animationDuration indicatorIndex = index isTransitioning = true delegate?.indicatorChange(indicatorIndex)//通知代理 let button = buttons[index] as! UIButton button.selected = true let damping: CGFloat = !bouncySelectionIndicator ? 0 : 0.6 let velocity: CGFloat = !bouncySelectionIndicator ? 0 : 0.5 //底部滑条的动画效果 UIView.animateWithDuration(NSTimeInterval(duration), delay: 0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { () -> Void in self.selectionIndicator.frame = self.selectionIndicatorRect() }) { (_) -> Void in self.enableAllButtonsInteraction(true) button.userInteractionEnabled = false button.selected = true self.isTransitioning = false } sendActionsForControlEvents(UIControlEvents.ValueChanged) self.layoutIfNeeded() } //选中的button func selectedButton() ->UIButton?{ if(indicatorIndex >= 0 && buttons.count > 0){ return buttons[indicatorIndex] as? UIButton } return nil } func addButtons(){ for( var i = 0; i < titles.count; i++ ) { let button = UIButton() button.addTarget(self, action: "didSelectedButton:", forControlEvents: .TouchUpInside) button.exclusiveTouch = true//禁止多个按钮同时被按下 button.tag = i button.setTitle(titles[i] as? String, forState: UIControlState.Normal) // button.setTitle(titles[i] as? String, forState: UIControlState.Highlighted) // button.setTitle(titles[i] as? String, forState: UIControlState.Selected) // button.setTitle(titles[i] as? String, forState: UIControlState.Disabled) self.addSubview(button) buttons.addObject(button) } selectionIndicator.frame = selectionIndicatorRect() } func removeButtons(){ if(isTransitioning){return} for button in buttons{ button.removeFromSuperview() } buttons.removeAllObjects() titles.removeAllObjects() } func didSelectedButton(sender: UIButton){ sender.highlighted = false sender.selected = true setSelectedIndex(sender.tag) } func titleColorForState(state: UIControlState) ->UIColor{ if let color = colors[String(state.rawValue)]{ return color } switch(state){ case UIControlState.Normal: return UIColor.darkGrayColor() case UIControlState.Highlighted,UIControlState.Selected: return self.tintColor case UIControlState.Disabled: return UIColor.lightGrayColor() default: return self.tintColor } } public func setTitleColorForState(color: UIColor, state: UIControlState){ colors.updateValue(color, forKey: String(state.rawValue)) } func disableAllButtonsSelection(){ for button in buttons { (button as! UIButton).selected = false } } func enableAllButtonsInteraction(enable: Bool){ for button in buttons { (button as! UIButton).userInteractionEnabled = enable } } } @objc public protocol ViewPagerIndicatorDelegate{ //返回当前选中第几个 func indicatorChange(indicatorIndex: Int) }
apache-2.0
99f4730baa93db23fe825ee9cab4a822
33.234848
219
0.620602
4.957762
false
false
false
false
alsotoes/MCS_programmingLanguages
swift/FunctionsClasses&Structures.playground/Contents.swift
1
1765
//: # Functions func addNumbers(a:Int, b:Int) -> Int{ return a + b } addNumbers(a: 2, b: 3) //: We can ommit the name of the parameters we calling a function using the "_" keyword func addNumbers2(_ a:Int, _ b:Int) -> Int{ return a + b } addNumbers2(2, 3) //: ### Multiple return values //: Return multiple values is possible thanks to Tuples func addByOne(a:Int, b:Int) -> (Int, Int){ return (a + 1, b + 1) } let res = addByOne(a: 2, b: 8) res.0 res.1 //: ### Send multiple parameters using Verdict Parameters func sendMultiple(_ val:Double...){ for num in val{ print(num) } } sendMultiple(12.5, 8.3, 4.5) //: ### Use In-Out Parameter to send parameters by reference func addNumbers3(a: inout Int, b: inout Int){ a += 1 b += 1 } var a = 3 var b = 4 addNumbers3(a: &a, b: &b) print("a: \(a), b: \(b)") //: # Classes class RectanglueClass { var width:Int var height = 0 init (w:Int, height:Int){ width = w; self.height = height } func area() -> Int { return width * height } } //: A class is a ref type, soy you can have a let instance and still modify its properties let obj = RectanglueClass(w: 3, height: 4) obj.width = 4 obj.area() //: # Structures //: Are almost as equal as classes, the have some differences like automatically-generated memberwise initializer struct RectanglueStructure { var width:Int var height = 0 var squere:Int{ get{ return self.height } set(value){ self.height = value self.width = value } } func area() -> Int { return width * height } } var str = RectanglueStructure(width: 2, height: 5) str.squere = 3 str.area()
gpl-3.0
9c3eadde3b22018bb1eb6cde084cc1ea
20.802469
113
0.592635
3.336484
false
false
false
false
nsagora/validation-kit
Sources/Async Constraints/ConditionedAsyncConstraint.swift
1
3399
import Foundation /** A structrure that links an `AsyncPredicate` to an `Error` that describes why the predicate evaluation has failed. */ public class ConditionedAsyncConstraint<T>: AsyncConstraint { public typealias InputType = T private var predicate: AnyAsyncPredicate<InputType> private var errorBuilder: (InputType) -> Error var conditions = [AnyAsyncConstraint<T>]() /** Create a new `ConditionedAsyncConstraint` instance - parameter predicate: An `AsyncPredicate` to describes the evaluation rule. - parameter error: An `Error` that describes why the evaluation has failed. */ public init<P: AsyncPredicate>(predicate: P, error: Error) where P.InputType == InputType { self.predicate = predicate.erase() self.errorBuilder = { _ in return error } } /** Create a new `ConditionedAsyncConstraint` instance - parameter predicate: An `AsyncPredicate` to describes the evaluation rule. - parameter error: An generic closure that dynamically builds an `Error` to describe why the evaluation has failed. */ public init<P: AsyncPredicate>(predicate: P, error: @escaping (InputType) -> Error) where P.InputType == InputType { self.predicate = predicate.erase() self.errorBuilder = error } /** Add a condition `AsyncConstraint`. - parameter constraint: `Constraint` */ public func add<C: AsyncConstraint>(condition: C) where C.InputType == InputType { conditions.append(condition.erase()) } /** Asynchronous evaluates the input on the `Predicate`. - parameter input: The input to be validated. - parameter queue: The queue on which the completion handler is executed. - parameter completionHandler: The completion handler to call when the evaluation is complete. It takes a `Bool` parameter: - parameter result: `.success` if the input is valid, `.failure` containing the `Summary` of the failing `Constraint`s otherwise. */ public func evaluate(with input: InputType, queue: DispatchQueue, completionHandler: @escaping (_ result: ValidationResult) -> Void) { if (!hasConditions()) { return continueEvaluate(with: input, queue: queue, completionHandler: completionHandler) } let predicateSet = AsyncConstraintSet(constraints: conditions) predicateSet.evaluateAll(input: input, queue: queue) { result in if result.isSuccessful { return self.continueEvaluate(with: input, queue: queue, completionHandler: completionHandler) } completionHandler(result) } } private func hasConditions() -> Bool { return conditions.count > 0 } private func continueEvaluate(with input: InputType, queue: DispatchQueue, completionHandler: @escaping (_ result: ValidationResult) -> Void) { predicate.evaluate(with: input, queue: queue) { matches in if matches { completionHandler(.success) } else { let error = self.errorBuilder(input) let summary = ValidationResult.Summary(errors: [error]) completionHandler(.failure(summary)) } } } }
apache-2.0
2832100a7cc296e1cd0865c826097917
36.766667
147
0.641071
5.118976
false
false
false
false
onthetall/OTTLocationManager
OTTLocationManager-Demo/ViewController.swift
1
3415
// // ViewController.swift // LocationManager // // Created by impressly on 12/3/15. // Copyright © 2015 OTT. All rights reserved. // import UIKit import AddressBook class ViewController: UIViewController { var locationManager = OTTLocationManager() @IBAction func didTapRefresh(sender: AnyObject) { refresh() } @IBOutlet weak var mapView: MKMapView! // search var selectedPin: MKPlacemark? var resultSearchController: UISearchController! override func viewDidLoad() { super.viewDidLoad() setupSearch() self.mapView.showsUserLocation = true self.locationManager.delegate = self refresh() } func setupSearch() { let locationSearchTable = storyboard!.instantiateViewControllerWithIdentifier("LocationSearchTable") as! OTTLocationSearchTable // init resultSearchController resultSearchController = UISearchController(searchResultsController: locationSearchTable) resultSearchController.searchResultsUpdater = locationSearchTable // config searchbar let searchBar = resultSearchController!.searchBar searchBar.sizeToFit() searchBar.placeholder = "Enter location" // searchbar/navigation bar setup navigationItem.titleView = searchBar resultSearchController.hidesNavigationBarDuringPresentation = false resultSearchController.dimsBackgroundDuringPresentation = true definesPresentationContext = true locationSearchTable.delegate = self } func refresh() { locationManager.start() } func zoomToCoord(coord: CLLocationCoordinate2D) { // Zoom Level Math: // http://troybrant.net/blog/2010/01/set-the-zoom-level-of-an-mkmapview/ // http://blogs.bing.com/maps/2006/02/25/map-control-zoom-levels-gt-resolution let ZOOM_LEVEL_12 = 0.344 // degrees/meters math.... let region = MKCoordinateRegion(center: coord, span: MKCoordinateSpanMake(ZOOM_LEVEL_12, ZOOM_LEVEL_12)) self.mapView.setRegion(region, animated: true) } } extension ViewController : OTTLocationSearchTableDelegate { func didSelect(annotation: MKAnnotation) { mapView.removeAnnotations(mapView.annotations) // reset mapView.addAnnotation(annotation) zoomToCoord(annotation.coordinate) } } extension ViewController : OTTLocationManagerDelegate { func didUpdateLatLon(locationManager: OTTLocationManager, lat: Double, lon: Double) { print("lat: \(lat), lon: \(lon)") let curCoord = CLLocationCoordinate2DMake(lat, lon) zoomToCoord(curCoord) } func didUpdateCityDistrict(locationManager: OTTLocationManager, fullAddress: String?, zhFullAddress: String?, district: String?, city: String?, country: String?) { print("current location: \(fullAddress)") } // func alertNoResults() { // // alert no results // let alertVC = UIAlertController(title: "Geocode", message: "No results found", preferredStyle: UIAlertControllerStyle.Alert) // let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil) // alertVC.addAction(action) // // presentViewController(alertVC, animated: true, completion: nil) // } }
mit
54b981d1d10c062b025fc8453b84674f
32.470588
167
0.673989
4.969432
false
false
false
false
ben-ng/swift
test/SILGen/super_init_refcounting.swift
1
3697
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s class Foo { init() {} init(_ x: Foo) {} init(_ x: Int) {} } class Bar: Foo { // CHECK-LABEL: sil hidden @_TFC22super_init_refcounting3Barc // CHECK: [[SELF_VAR:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <Bar> // CHECK: [[PB:%.*]] = project_box [[SELF_VAR]] // CHECK: [[SELF_MUI:%.*]] = mark_uninitialized [derivedself] [[PB]] // CHECK: [[ORIG_SELF:%.*]] = load_borrow [[SELF_MUI]] // CHECK-NOT: copy_value [[ORIG_SELF]] // CHECK: [[ORIG_SELF_UP:%.*]] = upcast [[ORIG_SELF]] // CHECK-NOT: copy_value [[ORIG_SELF_UP]] // CHECK: [[SUPER_INIT:%[0-9]+]] = function_ref @_TFC22super_init_refcounting3FoocfT_S0_ : $@convention(method) (@owned Foo) -> @owned Foo // CHECK: [[NEW_SELF:%.*]] = apply [[SUPER_INIT]]([[ORIG_SELF_UP]]) // CHECK: [[NEW_SELF_DOWN:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK: store [[NEW_SELF_DOWN]] to [init] [[SELF_MUI]] override init() { super.init() } } extension Foo { // CHECK-LABEL: sil hidden @_TFC22super_init_refcounting3Fooc // CHECK: [[SELF_VAR:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <Foo> // CHECK: [[PB:%.*]] = project_box [[SELF_VAR]] // CHECK: [[SELF_MUI:%.*]] = mark_uninitialized [delegatingself] [[PB]] // CHECK: [[ORIG_SELF:%.*]] = load_borrow [[SELF_MUI]] // CHECK-NOT: copy_value [[ORIG_SELF]] // CHECK: [[SUPER_INIT:%.*]] = class_method // CHECK: [[NEW_SELF:%.*]] = apply [[SUPER_INIT]]([[ORIG_SELF]]) // CHECK: store [[NEW_SELF]] to [init] [[SELF_MUI]] convenience init(x: Int) { self.init() } } class Zim: Foo { var foo = Foo() // CHECK-LABEL: sil hidden @_TFC22super_init_refcounting3Zimc // CHECK-NOT: copy_value // CHECK-NOT: destroy_value // CHECK: function_ref @_TFC22super_init_refcounting3FoocfT_S0_ : $@convention(method) (@owned Foo) -> @owned Foo } class Zang: Foo { var foo: Foo override init() { foo = Foo() super.init() } // CHECK-LABEL: sil hidden @_TFC22super_init_refcounting4Zangc // CHECK-NOT: copy_value // CHECK-NOT: destroy_value // CHECK: function_ref @_TFC22super_init_refcounting3FoocfT_S0_ : $@convention(method) (@owned Foo) -> @owned Foo } class Bad: Foo { // Invalid code, but it's not diagnosed till DI. We at least shouldn't // crash on it. override init() { super.init(self) } } class Good: Foo { let x: Int // CHECK-LABEL: sil hidden @_TFC22super_init_refcounting4Goodc // CHECK: [[SELF_BOX:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <Good> // CHECK: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK: [[SELF:%.*]] = mark_uninitialized [derivedself] [[PB]] // CHECK: store %0 to [init] [[SELF]] // CHECK: [[SELF_OBJ:%.*]] = load_borrow [[SELF]] // CHECK: [[X_ADDR:%.*]] = ref_element_addr [[SELF_OBJ]] : $Good, #Good.x // CHECK: assign {{.*}} to [[X_ADDR]] : $*Int // CHECK: [[SELF_OBJ:%.*]] = load_borrow [[SELF]] : $*Good // CHECK: [[SUPER_OBJ:%.*]] = upcast [[SELF_OBJ]] : $Good to $Foo // CHECK: [[SUPER_INIT:%.*]] = function_ref @_TFC22super_init_refcounting3FoocfSiS0_ : $@convention(method) (Int, @owned Foo) -> @owned Foo // CHECK: [[SELF_OBJ:%.*]] = load_borrow [[SELF]] // CHECK: [[X_ADDR:%.*]] = ref_element_addr [[SELF_OBJ]] : $Good, #Good.x // CHECK: [[X:%.*]] = load [trivial] [[X_ADDR]] : $*Int // CHECK: apply [[SUPER_INIT]]([[X]], [[SUPER_OBJ]]) override init() { x = 10 super.init(x) } }
apache-2.0
15bc96a1882a418acfae5076dd7105be
38.688172
149
0.535085
3.190147
false
false
false
false
NativeMobile/CoachKit
Example/CoachKit/PeerConnectionViewController.swift
1
1827
// // PeerConnectionViewController.swift // CoachKitDemo // // Created by Keith Coughtrey on 27/06/15. // Copyright © 2015 Keith Coughtrey. All rights reserved. // import Foundation import UIKit import CoachKit public class PeerConnectionViewController : UIViewController, UICollectionViewDataSource { public var manager: CoachingManager? //TODO: Make this private? @IBOutlet weak var peerCollectionView: UICollectionView! override public func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) NotificationCenter.default.addObserver(self, selector: #selector(classChanged), name: NSNotification.Name(CoachKitConstants.classChangeNotificationName), object: nil) } override public func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) NotificationCenter.default.removeObserver(self) } func classChanged(notification: Notification) { peerCollectionView.reloadData() } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let manager = manager { return manager.classPeers.count } else { return 0 } } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PeerCell", for: indexPath) as! PeerCell let peerWithStatus = manager!.classPeers[indexPath.row] cell.peerName.text = peerWithStatus.peer.displayName; cell.peerStatus.text = peerWithStatus.state; return cell; } }
mit
c3b07132677666118f4e613371a1bc0c
34.803922
174
0.720153
5.232092
false
false
false
false
Decybel07/L10n-swift
Source/Extensions/Number+Localizable.swift
1
4662
// // Number+Localizable.swift // L10n_swift // // Created by Adrian Bobrowski on 16/06/2019. // Copyright © 2019 Adrian Bobrowski (Decybel07), [email protected]. All rights reserved. // import Foundation // MARK: - NSNumberRepresentable public protocol NSNumberRepresentable { func asNSNumber() -> NSNumber } // MARK: - NumericLocalizable public protocol NumericLocalizable: Localizable { /** Returns a localized `self` description. - parameter instance: The instance of `L10n` used for localization. - parameter closure: A closure used to configure the `NumberFormatter`. - returns: A localized `self` description. */ func l10n(_ instance: L10n, closure: (_ formatter: NumberFormatter) -> Void) -> String } extension NumericLocalizable { /** Returns a localized `self` description. - parameter instance: The instance of `L10n` used for localization. */ public func l10n(_ instance: L10n) -> String { return self.l10n(instance) { _ in } } /** Returns a localized `self` description. - parameter closure: A closure used to configure the `NumberFormatter`. - returns: A localized `self` description. */ func l10n(closure: (_ formatter: NumberFormatter) -> Void) -> String { return self.l10n(.shared, closure: closure) } } extension NumericLocalizable where Self: NSNumberRepresentable { public func l10n(_ instance: L10n = .shared, closure: (_ formatter: NumberFormatter) -> Void) -> String { return self.asNSNumber().l10n(instance, closure: closure) } } // MARK: - IntegerLocalizable public protocol IntegerLocalizable: NumericLocalizable {} extension IntegerLocalizable { /** Returns a localized `self` description with leading zeros. - parameter instance: The instance of L10n used for localization. - parameter minIntegerDigits: The minimal number of integer digits. - returns: A localized `self` description with leading zeros. */ public func l10n(_ instance: L10n = .shared, minIntegerDigits: Int) -> String { return self.l10n(instance) { formatter in formatter.minimumIntegerDigits = minIntegerDigits } } } // MARK: - FloatingPointLocalizable public protocol FloatingPointLocalizable: NumericLocalizable {} extension FloatingPointLocalizable { /** Returns a localized `self` description with defined number of `fractionDigits`. - parameter instance: The instance of `L10n` used for localization. - parameter fractionDigits: The number of fraction digits. - returns: A localized `self` description with defined number of `fractionDigits`. */ public func l10n(_ instance: L10n = .shared, fractionDigits: Int) -> String { return self.l10n(instance) { formatter in formatter.minimumIntegerDigits = 1 formatter.minimumFractionDigits = fractionDigits formatter.maximumFractionDigits = fractionDigits } } } // MARK: - Numbers extension Int8: NSNumberRepresentable, IntegerLocalizable { public func asNSNumber() -> NSNumber { return self as NSNumber } } extension UInt8: NSNumberRepresentable, IntegerLocalizable { public func asNSNumber() -> NSNumber { return self as NSNumber } } extension Int16: NSNumberRepresentable, IntegerLocalizable { public func asNSNumber() -> NSNumber { return self as NSNumber } } extension UInt16: NSNumberRepresentable, IntegerLocalizable { public func asNSNumber() -> NSNumber { return self as NSNumber } } extension Int32: NSNumberRepresentable, IntegerLocalizable { public func asNSNumber() -> NSNumber { return self as NSNumber } } extension UInt32: NSNumberRepresentable, IntegerLocalizable { public func asNSNumber() -> NSNumber { return self as NSNumber } } extension Int64: NSNumberRepresentable, IntegerLocalizable { public func asNSNumber() -> NSNumber { return self as NSNumber } } extension Int: NSNumberRepresentable, IntegerLocalizable { public func asNSNumber() -> NSNumber { return self as NSNumber } } extension UInt: NSNumberRepresentable, IntegerLocalizable { public func asNSNumber() -> NSNumber { return self as NSNumber } } extension Float: NSNumberRepresentable, FloatingPointLocalizable { public func asNSNumber() -> NSNumber { return self as NSNumber } } extension Double: NSNumberRepresentable, FloatingPointLocalizable { public func asNSNumber() -> NSNumber { return self as NSNumber } }
mit
6dd9986fbae8d41c3eebbf65c6207d91
24.60989
109
0.688908
4.624008
false
false
false
false
omniprog/SwiftZSTD
Sources/ZSTDDictionaryBuilder.swift
1
2213
// // ZSTDDictionaryBuilder.swift // // Created by Anatoli on 12/06/16. // Copyright © 2016 Anatoli Peredera. All rights reserved. // import Foundation /** * Exceptions thrown by the dictionary builder. */ public enum ZDICTError : Error { case libraryError(errMsg : String) case unknownError } /** * Build a dictionary from samples identified by an array of Data instances. * * The target dictionary size is 100th of the total sample size as * recommended by documentation. * * - parameter fromSamples : array of Data instances to use to build a dictionary * - returns: Data instance containing the dictionary generated */ public func buildDictionary(fromSamples : [Data]) throws -> Data { var samples = Data() var totalSampleSize : Int = 0; var sampleSizes = [Int]() for sample in fromSamples { samples.append(sample) totalSampleSize += sample.count sampleSizes.append(sample.count) } // print ("totalSampleSize: \(totalSampleSize)") var retVal = Data(count: totalSampleSize / 100) return try samples.withUnsafeBytes{ (pSamples : UnsafeRawBufferPointer) -> Data in let count: Int = retVal.count retVal.count = try retVal.withUnsafeMutableBytes{ (pDict : UnsafeMutableRawBufferPointer) -> Int in let actualDictSize = ZDICT_trainFromBuffer(pDict.baseAddress, count, pSamples.baseAddress, &sampleSizes, UInt32(Int32(sampleSizes.count))) if ZDICT_isError(actualDictSize) != 0 { if let errStr = getDictionaryErrorString(actualDictSize) { throw ZDICTError.libraryError(errMsg: errStr) } else { throw ZDICTError.unknownError } } return actualDictSize } return retVal } } /** * A helper to obtain error string. */ fileprivate func getDictionaryErrorString(_ rc : Int) -> String? { if (ZDICT_isError(rc) != 0) { if let err = ZDICT_getErrorName(rc) { return String(bytesNoCopy: UnsafeMutableRawPointer(mutating: err), length: Int(strlen(err)), encoding: String.Encoding.ascii, freeWhenDone: false) } } return nil }
bsd-3-clause
9cc7b7a19f956ef5cb999170b1904b68
31.529412
158
0.656872
4.303502
false
false
false
false
thewisecity/declarehome-ios
CookedApp/TableViewControllers/AlertCategoriesTableViewController.swift
1
2861
// // AlertCategoriesTableViewController.swift // CookedApp // // Created by Dexter Lohnes on 10/20/15. // Copyright © 2015 The Wise City. All rights reserved. // import UIKit class AlertCategoriesTableViewController: PFQueryTableViewController { var delegate: AlertCategoriesTableViewDelegate? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.paginationEnabled = true self.objectsPerPage = 25 } init() { super.init(style: .Plain, className: AlertCategory.className) } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func queryForTable() -> PFQuery { let query = PFQuery(className: self.parseClassName!) // query.orderByDescending("createdAt") return query } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? { let cellIdentifier = "CategoryCell" var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? AlertCategoryCell if cell == nil { cell = AlertCategoryCell(style: .Default, reuseIdentifier: cellIdentifier) } return cell } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if let category = objectAtIndexPath(indexPath) as? AlertCategory { // cell?.textLabel?.text = category.description if let theCell = cell as? AlertCategoryCell { theCell.category = category } } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let selectedCategory = objectAtIndexPath(indexPath) as? AlertCategory delegate?.chooseAlertCategory(selectedCategory) } // 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?) { super.prepareForSegue(segue, sender: sender) // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. // if let selectedGroup = sender as? Group{ // if let destinationController = segue.destinationViewController as? GroupDetailsViewController { // destinationController.group = selectedGroup // } // } } }
gpl-3.0
a85717ee2bee9b3c4d17868d14c513ee
33.047619
138
0.646853
5.629921
false
false
false
false
marinehero/SwiftTask
SwiftTask/SwiftTask.swift
4
29952
// // SwiftTask.swift // SwiftTask // // Created by Yasuhiro Inami on 2014/08/21. // Copyright (c) 2014年 Yasuhiro Inami. All rights reserved. // // Required for use in the playground Sources folder import ObjectiveC // NOTE: nested type inside generic Task class is not allowed in Swift 1.1 public enum TaskState: String, CustomStringConvertible { case Paused = "Paused" case Running = "Running" case Fulfilled = "Fulfilled" case Rejected = "Rejected" case Cancelled = "Cancelled" public var description: String { return self.rawValue } } // NOTE: use class instead of struct to pass reference to `_initClosure` to set `pause`/`resume`/`cancel` closures public class TaskConfiguration { public var pause: (Void -> Void)? public var resume: (Void -> Void)? public var cancel: (Void -> Void)? /// useful to terminate immediate-infinite-sequence while performing `initClosure` public var isFinished : Bool { return self._isFinished.rawValue } private var _isFinished = _Atomic(false) internal func finish() { // // Cancel anyway on task finished (fulfilled/rejected/cancelled). // // NOTE: // ReactKit uses this closure to call `upstreamSignal.cancel()` // and let it know `configure.isFinished = true` while performing its `initClosure`. // self.cancel?() self.pause = nil self.resume = nil self.cancel = nil self._isFinished.rawValue = true } } public class Task<Progress, Value, Error>: Cancellable, CustomStringConvertible { public typealias ProgressTuple = (oldProgress: Progress?, newProgress: Progress) public typealias ErrorInfo = (error: Error?, isCancelled: Bool) public typealias ProgressHandler = (Progress -> Void) public typealias FulfillHandler = (Value -> Void) public typealias RejectHandler = (Error -> Void) public typealias Configuration = TaskConfiguration public typealias PromiseInitClosure = (fulfill: FulfillHandler, reject: RejectHandler) -> Void public typealias InitClosure = (progress: ProgressHandler, fulfill: FulfillHandler, reject: RejectHandler, configure: TaskConfiguration) -> Void internal typealias _Machine = _StateMachine<Progress, Value, Error> internal typealias _InitClosure = (machine: _Machine, progress: ProgressHandler, fulfill: FulfillHandler, _reject: _RejectInfoHandler, configure: TaskConfiguration) -> Void internal typealias _ProgressTupleHandler = (ProgressTuple -> Void) internal typealias _RejectInfoHandler = (ErrorInfo -> Void) internal let _machine: _Machine // store initial parameters for cloning task when using `try()` internal let _weakified: Bool internal let _paused: Bool internal var _initClosure: _InitClosure! // retained throughout task's lifetime public var state: TaskState { return self._machine.state.rawValue } /// progress value (NOTE: always nil when `weakified = true`) public var progress: Progress? { return self._machine.progress.rawValue } /// fulfilled value public var value: Value? { return self._machine.value.rawValue } /// rejected/cancelled tuple info public var errorInfo: ErrorInfo? { return self._machine.errorInfo.rawValue } public var name: String = "DefaultTask" public var description: String { var valueString: String? switch (self.state) { case .Fulfilled: valueString = "value=\(self.value!)" case .Rejected, .Cancelled: valueString = "errorInfo=\(self.errorInfo!)" default: valueString = "progress=\(self.progress)" } return "<\(self.name); state=\(self.state.rawValue); \(valueString!))>" } /// /// Creates a new task. /// /// - e.g. Task<P, V, E>(weakified: false, paused: false) { progress, fulfill, reject, configure in ... } /// /// - parameter weakified: Weakifies progress/fulfill/reject handlers to let player (inner asynchronous implementation inside `initClosure`) NOT CAPTURE this created new task. Normally, `weakified = false` should be set to gain "player -> task" retaining, so that task will be automatically deinited when player is deinited. If `weakified = true`, task must be manually retained somewhere else, or it will be immediately deinited. /// /// - parameter paused: Flag to invoke `initClosure` immediately or not. If `paused = true`, task's initial state will be `.Paused` and needs to `resume()` in order to start `.Running`. If `paused = false`, `initClosure` will be invoked immediately. /// /// - parameter initClosure: e.g. { progress, fulfill, reject, configure in ... }. `fulfill(value)` and `reject(error)` handlers must be called inside this closure, where calling `progress(progressValue)` handler is optional. Also as options, `configure.pause`/`configure.resume`/`configure.cancel` closures can be set to gain control from outside e.g. `task.pause()`/`task.resume()`/`task.cancel()`. When using `configure`, make sure to use weak modifier when appropriate to avoid "task -> player" retaining which often causes retain cycle. /// /// - returns: New task. /// public init(weakified: Bool, paused: Bool, initClosure: InitClosure) { self._weakified = weakified self._paused = paused self._machine = _Machine(weakified: weakified, paused: paused) let _initClosure: _InitClosure = { _, progress, fulfill, _reject, configure in // NOTE: don't expose rejectHandler with ErrorInfo (isCancelled) for public init initClosure(progress: progress, fulfill: fulfill, reject: { error in _reject(ErrorInfo(error: Optional(error), isCancelled: false)) }, configure: configure) } self.setup(weakified: weakified, paused: paused, _initClosure: _initClosure) } /// /// creates a new task without weakifying progress/fulfill/reject handlers /// /// - e.g. Task<P, V, E>(paused: false) { progress, fulfill, reject, configure in ... } /// public convenience init(paused: Bool, initClosure: InitClosure) { self.init(weakified: false, paused: paused, initClosure: initClosure) } /// /// creates a new task without weakifying progress/fulfill/reject handlers (non-paused) /// /// - e.g. Task<P, V, E> { progress, fulfill, reject, configure in ... } /// public convenience init(initClosure: InitClosure) { self.init(weakified: false, paused: false, initClosure: initClosure) } /// /// creates fulfilled task (non-paused) /// /// - e.g. Task<P, V, E>(value: someValue) /// public convenience init(value: Value) { self.init(initClosure: { progress, fulfill, reject, configure in fulfill(value) }) self.name = "FulfilledTask" } /// /// creates rejected task (non-paused) /// /// - e.g. Task<P, V, E>(error: someError) /// public convenience init(error: Error) { self.init(initClosure: { progress, fulfill, reject, configure in reject(error) }) self.name = "RejectedTask" } /// /// creates promise-like task which only allows fulfill & reject (no progress & configure) /// /// - e.g. Task<Any, Value, Error> { fulfill, reject in ... } /// public convenience init(promiseInitClosure: PromiseInitClosure) { self.init(initClosure: { progress, fulfill, reject, configure in promiseInitClosure(fulfill: fulfill, reject: { error in reject(error) }) }) } /// internal-init for accessing `machine` inside `_initClosure` /// (NOTE: _initClosure has _RejectInfoHandler as argument) internal init(weakified: Bool = false, paused: Bool = false, _initClosure: _InitClosure) { self._weakified = weakified self._paused = paused self._machine = _Machine(weakified: weakified, paused: paused) self.setup(weakified: weakified, paused: paused, _initClosure: _initClosure) } // NOTE: don't use `internal init` for this setup method, or this will be a designated initializer internal func setup(weakified weakified: Bool, paused: Bool, _initClosure: _InitClosure) { // #if DEBUG // let addr = String(format: "%p", unsafeAddressOf(self)) // NSLog("[init] \(self.name) \(addr)") // #endif self._initClosure = _initClosure // will be invoked on 1st resume (only once) self._machine.initResumeClosure.rawValue = { [weak self] in // strongify `self` on 1st resume if let self_ = self { var progressHandler: ProgressHandler var fulfillHandler: FulfillHandler var rejectInfoHandler: _RejectInfoHandler if weakified { // // NOTE: // When `weakified = true`, // each handler will NOT capture `self_` (strongSelf on 1st resume) // so it will immediately deinit if not retained in somewhere else. // progressHandler = { [weak self_] (progress: Progress) in if let self_ = self_ { self_._machine.handleProgress(progress) } } fulfillHandler = { [weak self_] (value: Value) in if let self_ = self_ { self_._machine.handleFulfill(value) } } rejectInfoHandler = { [weak self_] (errorInfo: ErrorInfo) in if let self_ = self_ { self_._machine.handleRejectInfo(errorInfo) } } } else { // // NOTE: // When `weakified = false`, // each handler will capture `self_` (strongSelf on 1st resume) // so that it will live until fulfilled/rejected. // progressHandler = { (progress: Progress) in self_._machine.handleProgress(progress) } fulfillHandler = { (value: Value) in self_._machine.handleFulfill(value) } rejectInfoHandler = { (errorInfo: ErrorInfo) in self_._machine.handleRejectInfo(errorInfo) } } _initClosure(machine: self_._machine, progress: progressHandler, fulfill: fulfillHandler, _reject: rejectInfoHandler, configure: self_._machine.configuration) } } if !paused { self.resume() } } deinit { // #if DEBUG // let addr = String(format: "%p", unsafeAddressOf(self)) // NSLog("[deinit] \(self.name) \(addr)") // #endif // cancel in case machine is still running self._cancel(nil) } /// Sets task name (method chainable) public func name(name: String) -> Self { self.name = name return self } /// Creates cloned task. public func clone() -> Task { let clonedTask = Task(weakified: self._weakified, paused: self._paused, _initClosure: self._initClosure) clonedTask.name = "\(self.name)-clone" return clonedTask } /// Returns new task that is retryable for `maxTryCount-1` times. public func `try`(maxTryCount: Int) -> Task { if maxTryCount < 2 { return self } return Task { machine, progress, fulfill, _reject, configure in let task = self.progress { _, progressValue in progress(progressValue) }.failure { [unowned self] _ -> Task in return self.clone().`try`(maxTryCount-1) // clone & try recursively } task.progress { _, progressValue in progress(progressValue) // also receive progresses from clone-try-task }.success { value -> Void in fulfill(value) }.failure { errorInfo -> Void in _reject(errorInfo) } configure.pause = { self.pause() task.pause() } configure.resume = { self.resume() task.resume() } configure.cancel = { task.cancel() // cancel downstream first self.cancel() } }.name("\(self.name)-try(\(maxTryCount))") } /// /// Add progress handler delivered from `initClosure`'s `progress()` argument. /// /// - e.g. task.progress { oldProgress, newProgress in ... } /// /// NOTE: `oldProgress` is always nil when `weakified = true` /// public func progress(progressClosure: ProgressTuple -> Void) -> Task { var dummyCanceller: Canceller? = nil return self.progress(&dummyCanceller, progressClosure) } public func progress<C: Canceller>(inout canceller: C?, _ progressClosure: ProgressTuple -> Void) -> Task { var token: _HandlerToken? = nil self._machine.addProgressTupleHandler(&token, progressClosure) canceller = C { [weak self] in self?._machine.removeProgressTupleHandler(token) } return self } /// /// then (fulfilled & rejected) + closure returning **value** /// (a.k.a. `map` in functional programming term) /// /// - e.g. task.then { value, errorInfo -> NextValueType in ... } /// public func then<Value2>(thenClosure: (Value?, ErrorInfo?) -> Value2) -> Task<Progress, Value2, Error> { var dummyCanceller: Canceller? = nil return self.then(&dummyCanceller, thenClosure) } public func then<Value2, C: Canceller>(inout canceller: C?, _ thenClosure: (Value?, ErrorInfo?) -> Value2) -> Task<Progress, Value2, Error> { return self.then(&canceller) { (value, errorInfo) -> Task<Progress, Value2, Error> in return Task<Progress, Value2, Error>(value: thenClosure(value, errorInfo)) } } /// /// then (fulfilled & rejected) + closure returning **task** /// (a.k.a. `flatMap` in functional programming term) /// /// - e.g. task.then { value, errorInfo -> NextTaskType in ... } /// public func then<Progress2, Value2, Error2>(thenClosure: (Value?, ErrorInfo?) -> Task<Progress2, Value2, Error2>) -> Task<Progress2, Value2, Error2> { var dummyCanceller: Canceller? = nil return self.then(&dummyCanceller, thenClosure) } // // NOTE: then-canceller is a shorthand of `task.cancel(nil)`, i.e. these two are the same: // // - `let canceller = Canceller(); task1.then(&canceller) {...}; canceller.cancel();` // - `let task2 = task1.then {...}; task2.cancel();` // public func then<Progress2, Value2, Error2, C: Canceller>(inout canceller: C?, _ thenClosure: (Value?, ErrorInfo?) -> Task<Progress2, Value2, Error2>) -> Task<Progress2, Value2, Error2> { return Task<Progress2, Value2, Error2> { [unowned self, weak canceller] newMachine, progress, fulfill, _reject, configure in // // NOTE: // We split `self` (Task) and `self.machine` (StateMachine) separately to // let `completionHandler` retain `selfMachine` instead of `self` // so that `selfMachine`'s `completionHandlers` can be invoked even though `self` is deinited. // This is especially important for ReactKit's `deinitSignal` behavior. // let selfMachine = self._machine self._then(&canceller) { let innerTask = thenClosure(selfMachine.value.rawValue, selfMachine.errorInfo.rawValue) _bindInnerTask(innerTask, newMachine, progress, fulfill, _reject, configure) } }.name("\(self.name)-then") } /// invokes `completionHandler` "now" or "in the future" private func _then<C: Canceller>(inout canceller: C?, _ completionHandler: Void -> Void) { switch self.state { case .Fulfilled, .Rejected, .Cancelled: completionHandler() default: var token: _HandlerToken? = nil self._machine.addCompletionHandler(&token, completionHandler) canceller = C { [weak self] in self?._machine.removeCompletionHandler(token) } } } /// /// success (fulfilled) + closure returning **value** /// /// - e.g. task.success { value -> NextValueType in ... } /// public func success<Value2>(successClosure: Value -> Value2) -> Task<Progress, Value2, Error> { var dummyCanceller: Canceller? = nil return self.success(&dummyCanceller, successClosure) } public func success<Value2, C: Canceller>(inout canceller: C?, _ successClosure: Value -> Value2) -> Task<Progress, Value2, Error> { return self.success(&canceller) { (value: Value) -> Task<Progress, Value2, Error> in return Task<Progress, Value2, Error>(value: successClosure(value)) } } /// /// success (fulfilled) + closure returning **task** /// /// - e.g. task.success { value -> NextTaskType in ... } /// public func success<Progress2, Value2, Error2>(successClosure: Value -> Task<Progress2, Value2, Error2>) -> Task<Progress2, Value2, Error> { var dummyCanceller: Canceller? = nil return self.success(&dummyCanceller, successClosure) } public func success<Progress2, Value2, Error2, C: Canceller>(inout canceller: C?, _ successClosure: Value -> Task<Progress2, Value2, Error2>) -> Task<Progress2, Value2, Error> { return Task<Progress2, Value2, Error> { [unowned self] newMachine, progress, fulfill, _reject, configure in let selfMachine = self._machine // NOTE: using `self._then()` + `selfMachine` instead of `self.then()` will reduce Task allocation self._then(&canceller) { if let value = selfMachine.value.rawValue { let innerTask = successClosure(value) _bindInnerTask(innerTask, newMachine, progress, fulfill, _reject, configure) } else if let errorInfo = selfMachine.errorInfo.rawValue { _reject(errorInfo) } } }.name("\(self.name)-success") } /// /// failure (rejected or cancelled) + closure returning **value** /// /// - e.g. task.failure { errorInfo -> NextValueType in ... } /// - e.g. task.failure { error, isCancelled -> NextValueType in ... } /// public func failure(failureClosure: ErrorInfo -> Value) -> Task { var dummyCanceller: Canceller? = nil return self.failure(&dummyCanceller, failureClosure) } public func failure<C: Canceller>(inout canceller: C?, _ failureClosure: ErrorInfo -> Value) -> Task { return self.failure(&canceller) { (errorInfo: ErrorInfo) -> Task in return Task(value: failureClosure(errorInfo)) } } /// /// failure (rejected or cancelled) + closure returning **task** /// /// - e.g. task.failure { errorInfo -> NextTaskType in ... } /// - e.g. task.failure { error, isCancelled -> NextTaskType in ... } /// public func failure<Progress2, Error2>(failureClosure: ErrorInfo -> Task<Progress2, Value, Error2>) -> Task<Progress2, Value, Error2> { var dummyCanceller: Canceller? = nil return self.failure(&dummyCanceller, failureClosure) } public func failure<Progress2, Error2, C: Canceller>(inout canceller: C?, _ failureClosure: ErrorInfo -> Task<Progress2, Value, Error2>) -> Task<Progress2, Value, Error2> { return Task<Progress2, Value, Error2> { [unowned self] newMachine, progress, fulfill, _reject, configure in let selfMachine = self._machine self._then(&canceller) { if let value = selfMachine.value.rawValue { fulfill(value) } else if let errorInfo = selfMachine.errorInfo.rawValue { let innerTask = failureClosure(errorInfo) _bindInnerTask(innerTask, newMachine, progress, fulfill, _reject, configure) } } }.name("\(self.name)-failure") } public func pause() -> Bool { return self._machine.handlePause() } public func resume() -> Bool { return self._machine.handleResume() } // // NOTE: // To conform to `Cancellable`, this method is needed in replace of: // - `public func cancel(error: Error? = nil) -> Bool` // - `public func cancel(_ error: Error? = nil) -> Bool` (segfault in Swift 1.2) // public func cancel() -> Bool { return self.cancel(error: nil) } public func cancel(error error: Error?) -> Bool { return self._cancel(error) } internal func _cancel(error: Error? = nil) -> Bool { return self._machine.handleCancel(error) } } // MARK: - Helper internal func _bindInnerTask<Progress2, Value2, Error, Error2>( innerTask: Task<Progress2, Value2, Error2>, _ newMachine: _StateMachine<Progress2, Value2, Error>, _ progress: Task<Progress2, Value2, Error>.ProgressHandler, _ fulfill: Task<Progress2, Value2, Error>.FulfillHandler, _ _reject: Task<Progress2, Value2, Error>._RejectInfoHandler, _ configure: TaskConfiguration ) { switch innerTask.state { case .Fulfilled: fulfill(innerTask.value!) return case .Rejected, .Cancelled: let (error2, isCancelled) = innerTask.errorInfo! // NOTE: innerTask's `error2` will be treated as `nil` if not same type as outerTask's `Error` type _reject((error2 as? Error, isCancelled)) return default: break } innerTask.progress { _, progressValue in progress(progressValue) }.then { (value: Value2?, errorInfo2: Task<Progress2, Value2, Error2>.ErrorInfo?) -> Void in if let value = value { fulfill(value) } else if let errorInfo2 = errorInfo2 { let (error2, isCancelled) = errorInfo2 // NOTE: innerTask's `error2` will be treated as `nil` if not same type as outerTask's `Error` type _reject((error2 as? Error, isCancelled)) } } configure.pause = { innerTask.pause(); return } configure.resume = { innerTask.resume(); return } configure.cancel = { innerTask.cancel(); return } // pause/cancel innerTask if descendant task is already paused/cancelled if newMachine.state.rawValue == .Paused { innerTask.pause() } else if newMachine.state.rawValue == .Cancelled { innerTask.cancel() } } // MARK: - Multiple Tasks extension Task { public typealias BulkProgress = (completedCount: Int, totalCount: Int) public class func all(tasks: [Task]) -> Task<BulkProgress, [Value], Error> { return Task<BulkProgress, [Value], Error> { machine, progress, fulfill, _reject, configure in var completedCount = 0 let totalCount = tasks.count let lock = _RecursiveLock() for task in tasks { task.success { (value: Value) -> Void in lock.lock() completedCount++ let progressTuple = BulkProgress(completedCount: completedCount, totalCount: totalCount) progress(progressTuple) if completedCount == totalCount { var values: [Value] = Array() for task in tasks { values.append(task.value!) } fulfill(values) } lock.unlock() }.failure { (errorInfo: ErrorInfo) -> Void in lock.lock() _reject(errorInfo) for task in tasks { task.cancel() } lock.unlock() } } configure.pause = { self.pauseAll(tasks); return } configure.resume = { self.resumeAll(tasks); return } configure.cancel = { self.cancelAll(tasks); return } }.name("Task.all") } public class func any(tasks: [Task]) -> Task { return Task<Progress, Value, Error> { machine, progress, fulfill, _reject, configure in var completedCount = 0 var rejectedCount = 0 let totalCount = tasks.count let lock = _RecursiveLock() for task in tasks { task.success { (value: Value) -> Void in lock.lock() completedCount++ if completedCount == 1 { fulfill(value) self.cancelAll(tasks) } lock.unlock() }.failure { (errorInfo: ErrorInfo) -> Void in lock.lock() rejectedCount++ if rejectedCount == totalCount { let isAnyCancelled = (tasks.filter { task in task.state == .Cancelled }.count > 0) let errorInfo = ErrorInfo(error: nil, isCancelled: isAnyCancelled) // NOTE: Task.any error returns nil (spec) _reject(errorInfo) } lock.unlock() } } configure.pause = { self.pauseAll(tasks); return } configure.resume = { self.resumeAll(tasks); return } configure.cancel = { self.cancelAll(tasks); return } }.name("Task.any") } /// Returns new task which performs all given tasks and stores only fulfilled values. /// This new task will NEVER be internally rejected. public class func some(tasks: [Task]) -> Task<BulkProgress, [Value], Error> { return Task<BulkProgress, [Value], Error> { machine, progress, fulfill, _reject, configure in var completedCount = 0 let totalCount = tasks.count let lock = _RecursiveLock() for task in tasks { task.then { (value: Value?, errorInfo: ErrorInfo?) -> Void in lock.lock() completedCount++ let progressTuple = BulkProgress(completedCount: completedCount, totalCount: totalCount) progress(progressTuple) if completedCount == totalCount { var values: [Value] = Array() for task in tasks { if task.state == .Fulfilled { values.append(task.value!) } } fulfill(values) } lock.unlock() } } configure.pause = { self.pauseAll(tasks); return } configure.resume = { self.resumeAll(tasks); return } configure.cancel = { self.cancelAll(tasks); return } }.name("Task.some") } public class func cancelAll(tasks: [Task]) { for task in tasks { task._cancel() } } public class func pauseAll(tasks: [Task]) { for task in tasks { task.pause() } } public class func resumeAll(tasks: [Task]) { for task in tasks { task.resume() } } } //-------------------------------------------------- // MARK: - Custom Operators // + - * / % = < > ! & | ^ ~ . //-------------------------------------------------- infix operator ~ { associativity left } /// abbreviation for `try()` /// e.g. (task ~ 3).then { ... } public func ~ <P, V, E>(task: Task<P, V, E>, tryCount: Int) -> Task<P, V, E> { return task.`try`(tryCount) }
mit
2474729ec7b4b99701e53e322f1ba192
36.114002
545
0.546277
4.828309
false
true
false
false
liuxianghong/GreenBaby
工程/greenbaby/greenbaby/ViewController/Forum/ForumPublishTableViewController.swift
1
9141
// // ForumPublishTableViewController.swift // greenbaby // // Created by 刘向宏 on 15/12/18. // Copyright © 2015年 刘向宏. All rights reserved. // import UIKit class ForumPublishTableViewController: UITableViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate { @IBOutlet weak var contentTextView : UITextView! @IBOutlet weak var titleTextField : UITextField! @IBOutlet weak var imageButton1 : UIButton! @IBOutlet weak var imageButton2 : UIButton! @IBOutlet weak var imageButton3 : UIButton! var groupId : AnyObject! var imageIndex = 1 var imageNameArray : Array<String> = [] 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() contentTextView.layer.borderWidth = 1/2 contentTextView.layer.borderColor = UIColor.lightGrayColor().CGColor contentTextView.layer.cornerRadius = 4; contentTextView.layer.masksToBounds = true; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func imageButtonClick(sender : UIButton){ if sender.tag != imageIndex{ return } let actionVC = UIAlertController(title: "", message: "添加图片", preferredStyle: .ActionSheet) let actionNew = UIAlertAction(title: "拍照", style: .Default, handler: { (UIAlertAction) -> Void in if UIImagePickerController.isSourceTypeAvailable(.Camera){ self.showImagePickVC(.Camera) } }) let actionAdd = UIAlertAction(title: "相册", style: .Default, handler: { (UIAlertAction) -> Void in if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){ self.showImagePickVC(.PhotoLibrary) } }) let actionCancel = UIAlertAction(title: "取消", style: .Cancel, handler: { (UIAlertAction) -> Void in }) actionVC.addAction(actionNew) actionVC.addAction(actionAdd) actionVC.addAction(actionCancel) self.presentViewController(actionVC, animated: true, completion: { () -> Void in }) } @IBAction func publishClick(){ let hud = MBProgressHUD.showHUDAddedTo(self.view.window, animated: true) if self.titleTextField.text!.isEmpty { hud.mode = .Text hud.detailsLabelText = "请输入标题" hud.hide(true, afterDelay: 1.5) return } if self.contentTextView.text!.isEmpty { hud.mode = .Text hud.detailsLabelText = "请输入内容" hud.hide(true, afterDelay: 1.5) return } let userId = NSUserDefaults.standardUserDefaults().objectForKey("userId") let dicP : Dictionary<String,AnyObject> = ["groupId" : groupId,"userId" : userId!,"title": self.titleTextField.text!,"content": self.contentTextView.text!,"location" : UserInfo.CurrentUser().city!,"images" : imageNameArray] ForumRequest.PostForumThreadWithParameters(dicP, success: { (object) -> Void in print(object) let dicd:NSDictionary = object as! NSDictionary let state:Int = dicd["state"] as! Int if state == 0{ hud.mode = .Text hud.detailsLabelText = "发布成功" hud.hide(true, afterDelay: 1.5) self.navigationController?.popViewControllerAnimated(true) }else{ hud.mode = .Text hud.detailsLabelText = dicd["description"] as! String hud.hide(true, afterDelay: 1.5) } }, failure: { (error : NSError!) -> Void in hud.mode = .Text hud.detailsLabelText = error.domain hud.hide(true, afterDelay: 1.5) }) } func showImagePickVC(sourceType: UIImagePickerControllerSourceType){ let imagePickerController:UIImagePickerController = UIImagePickerController() imagePickerController.delegate = self; imagePickerController.allowsEditing = true; imagePickerController.sourceType = sourceType; self.presentViewController(imagePickerController, animated: true) { () -> Void in } } func upDateImageButton(image : UIImage){ if imageIndex == 1{ imageButton1.setBackgroundImage(image, forState: .Normal) imageButton2.hidden = false }else if imageIndex == 2{ imageButton2.setBackgroundImage(image, forState: .Normal) imageButton3.hidden = false } else if imageIndex == 3{ imageButton3.setBackgroundImage(image, forState: .Normal) } imageIndex++ } // MARK: - UIImagePickerControllerDelegate func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { picker.dismissViewControllerAnimated(true) { () -> Void in let hud = MBProgressHUD.showHUDAddedTo(self.view.window, animated: true) hud.labelText = "正在上传" let image:UIImage = info[UIImagePickerControllerEditedImage] as! UIImage [FileRequest .UploadImage(image, success: { (object) -> Void in print(object) let dic:NSDictionary = object as! NSDictionary let state:Int = dic["state"] as! Int if state == 0{ let dicdata:NSDictionary = dic["data"] as! NSDictionary let imageName = dicdata["name"] as! String self.imageNameArray.append(imageName) self.upDateImageButton(image) hud.labelText = "上传成功"; } else{ hud.labelText = "上传失败"; } hud.mode = .Text hud.hide(true, afterDelay: 1.5) }, failure: { (error) -> Void in print(error) hud.mode = .Text hud.labelText = error.domain; hud.hide(true, afterDelay: 1.5) })] } } // MARK: - Table view data source // override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // // #warning Incomplete implementation, return the number of sections // return 1 // } // // override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // // #warning Incomplete implementation, return the number of rows // return 0 // } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
lgpl-3.0
4a927eca8c66c327539317cd9717e043
38.025862
231
0.619726
5.307151
false
false
false
false
acrocat/EverLayout
Source/Model/ELConstraintContext.swift
1
3620
// EverLayout // // Copyright (c) 2017 Dale Webster // // 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 struct ELConstraintContext { private static let INDEPENDANT_ATTRIBUTES : [NSLayoutAttribute] = [ .width , .height ] private static let PERSPECTIVE_INSET_ATTRIBUTES : [NSLayoutAttribute] = [ .right , .bottom , .width , .height , .rightMargin ] private static let PERSPECTIVE_OFFSET_ATTRIBUTES : [NSLayoutAttribute] = [ .left , .top , .width , .height ] var _target : UIView var _leftSideAttribute : NSLayoutAttribute var _relation : NSLayoutRelation var _comparableView : UIView? var _rightSideAttribute : NSLayoutAttribute? var _constant : ELConstraintConstant var _multiplier : ELConstraintMultiplier var target : UIView { return self._target } var leftSideAttribute : NSLayoutAttribute { return self._leftSideAttribute } var relation : NSLayoutRelation { return self._relation } var comparableView : UIView? { if self._comparableView == nil && self.rightSideAttribute != .notAnAttribute { return self.target.superview } return self._comparableView } var rightSideAttribute : NSLayoutAttribute? { if ELConstraintContext.INDEPENDANT_ATTRIBUTES.contains(self.leftSideAttribute) && self._comparableView == nil { return .notAnAttribute } return self._rightSideAttribute } var constant : ELConstraintConstant { let sign = self._constant.sign var value = self._constant.value // If the constant is to inset and we are using a 'perspective inset' attribute, or offset and we are using 'perspective offset' attributes // then we should inverse the constant. Same if it is just a negative value if (ELConstraintContext.PERSPECTIVE_INSET_ATTRIBUTES.contains(self.leftSideAttribute) && sign == .inset) || (ELConstraintContext.PERSPECTIVE_OFFSET_ATTRIBUTES.contains(self.leftSideAttribute) && sign == .offset) || (sign == .negative) { value *= -1 } return ELConstraintConstant(value: value, sign: sign) } var multiplier : ELConstraintMultiplier { let sign = self._multiplier.sign var value = self._multiplier.value if sign == .divide { value = 1 / value } return ELConstraintMultiplier(value: value, sign: sign) } }
mit
de5d6435a1e5664b86f1775edc8ea10a
37.105263
222
0.668785
4.670968
false
false
false
false
wayfair/brickkit-ios
Tests/Utils/DataSources.swift
1
11152
// // FakeCollectionViewDataSource.swift // BrickApp // // Created by Ruben Cagnie on 5/20/16. // Copyright © 2016 Wayfair. All rights reserved. // import UIKit @testable import BrickKit class SectionsCollectionViewDataSource: NSObject, UICollectionViewDataSource { let sections: [Int] init(sections: [Int]) { self.sections = sections } func numberOfSections(in collectionView: UICollectionView) -> Int { return sections.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return sections[section] } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return UICollectionViewCell() } } class SectionsLayoutDataSource: NSObject, BrickLayoutDataSource { let widthRatios: [[CGFloat]] let heights: [[CGFloat]] let edgeInsets: [UIEdgeInsets] let insets: [CGFloat] let types: [[BrickLayoutType]] init(widthRatios: [[CGFloat]] = [[1]], heights: [[CGFloat]] = [[0]], edgeInsets: [UIEdgeInsets] = [.zero], insets: [CGFloat] = [0], types: [[BrickLayoutType]] = [[.brick]]) { self.widthRatios = widthRatios self.heights = heights self.edgeInsets = edgeInsets self.insets = insets self.types = types } func brickLayout(_ layout: BrickLayout, widthRatioForItemAtIndexPath indexPath: IndexPath) -> CGFloat { let sectionWidthRatios = widthRatios[indexPath.section] if sectionWidthRatios.count <= indexPath.item { return sectionWidthRatios.last ?? 0 } else { return sectionWidthRatios[indexPath.item] } } func brickLayout(_ layout: BrickLayout, widthForItemAt indexPath: IndexPath, totalWidth: CGFloat, widthRatio: CGFloat, startingAt origin: CGFloat) -> CGFloat { let ratio: CGFloat let sectionWidthRatios = widthRatios[indexPath.section] if sectionWidthRatios.count <= indexPath.item { ratio = sectionWidthRatios.last ?? 0 } else { ratio = sectionWidthRatios[indexPath.item] } return BrickUtils.calculateWidth(for: ratio, widthRatio: widthRatio, totalWidth: totalWidth, inset: self.brickLayout(layout, insetFor: indexPath.section)) } func brickLayout(_ layout: BrickLayout, estimatedHeightForItemAt indexPath: IndexPath, containedIn width: CGFloat) -> CGFloat { let sectionHeights = heights[indexPath.section] if sectionHeights.count <= indexPath.item { return sectionHeights.last ?? 0 } else { return sectionHeights[indexPath.item] } } func brickLayout(_ layout: BrickLayout, edgeInsetsFor section: Int) -> UIEdgeInsets { if edgeInsets.count <= section { return edgeInsets.last ?? .zero } else { return edgeInsets[section] } } func brickLayout(_ layout: BrickLayout, insetFor section: Int) -> CGFloat { if insets.count <= section { return insets.last ?? 0 } else { return insets[section] } } func brickLayout(_ layout: BrickLayout, brickLayoutTypeForItemAt indexPath: IndexPath) -> BrickLayoutType { let sectionTypes = types[indexPath.section] if sectionTypes.count <= indexPath.item { return sectionTypes.last ?? .brick } else { return sectionTypes[indexPath.item] } } func brickLayout(_ layout: BrickLayout, identifierFor indexPath: IndexPath) -> String { return "" } func brickLayout(_ layout: BrickLayout, indexPathFor section: Int) -> IndexPath? { for (sectionIndex, type) in types.enumerated() { for (itemIndex, t) in type.enumerated() { switch t { case .section(let sIndex): if sIndex == section { return IndexPath(item: itemIndex, section: sectionIndex) } default: break } } } return nil } func brickLayout(_ layout: BrickLayout, prefetchAttributeIndexPathsFor section: Int) -> [IndexPath] { return [] } } class FixedBrickLayoutSectionDataSource: NSObject, BrickLayoutSectionDataSource { var widthRatios: [CGFloat] var heights: [CGFloat] var edgeInsets: UIEdgeInsets var inset: CGFloat var widthRatio: CGFloat = 1 var frameOfInterest: CGRect = CGRect(x: 0, y: 0, width: 320, height: CGFloat.infinity) // Infinite frame height var downStreamIndexPaths: [IndexPath] = [] init(widthRatios: [CGFloat], heights: [CGFloat], edgeInsets: UIEdgeInsets, inset: CGFloat) { self.widthRatios = widthRatios self.heights = heights self.edgeInsets = edgeInsets self.inset = inset } func edgeInsets(in skeleton: BrickLayoutSection) -> UIEdgeInsets { return edgeInsets } func inset(in skeleton: BrickLayoutSection) -> CGFloat { return inset } func width(for index: Int, totalWidth: CGFloat, startingAt origin: CGFloat, in skeleton: BrickLayoutSection) -> CGFloat { return BrickUtils.calculateWidth(for: widthRatios[index], widthRatio: widthRatio, totalWidth: totalWidth, inset: inset) } func widthRatio(for index: Int, in skeleton: BrickLayoutSection) -> CGFloat { return widthRatios[index] } func prepareForSizeCalculation(for attributes: BrickLayoutAttributes, containedIn width: CGFloat, origin: CGPoint, invalidate: Bool, in section: BrickLayoutSection, updatedAttributes: OnAttributesUpdatedHandler?) { } func size(for attributes: BrickLayoutAttributes, containedIn width: CGFloat, in section: BrickLayoutSection) -> CGSize { return CGSize(width: width, height: heights[attributes.indexPath.item]) } func identifier(for index: Int, in skeleton: BrickLayoutSection) -> String { return "\(index)" } func zIndex(for index: Int, in skeleton: BrickLayoutSection) -> Int { return 0 } var zIndexBehavior: BrickLayoutZIndexBehavior { return .bottomUp } func isEstimate(for attributes: BrickLayoutAttributes, in section: BrickLayoutSection) -> Bool { return true } func downStreamIndexPaths(in section: BrickLayoutSection) -> [IndexPath] { return downStreamIndexPaths } func isAlignRowHeights(in section: BrickLayoutSection) -> Bool { return false } func aligment(in section: BrickLayoutSection) -> BrickAlignment { return BrickAlignment(horizontal: .left, vertical: .top) } func prefetchIndexPaths(in section: BrickLayoutSection) -> [IndexPath] { return [] } var scrollDirection: UICollectionView.ScrollDirection = .vertical } class FixedBrickLayoutDataSource: NSObject, BrickLayoutDataSource { let widthRatio: CGFloat let height: CGFloat let edgeInsets: UIEdgeInsets let inset: CGFloat let type: BrickLayoutType init(widthRatio: CGFloat = 1, height: CGFloat = 0, edgeInsets: UIEdgeInsets = .zero, inset: CGFloat = 0, type: BrickLayoutType = .brick) { self.widthRatio = widthRatio self.height = height self.edgeInsets = edgeInsets self.inset = inset self.type = type } func brickLayout(_ layout: BrickLayout, widthForItemAt indexPath: IndexPath, totalWidth: CGFloat, widthRatio: CGFloat, startingAt origin: CGFloat) -> CGFloat { return BrickUtils.calculateWidth(for: self.widthRatio, widthRatio: widthRatio, totalWidth: totalWidth, inset: inset) } func brickLayout(_ layout: BrickLayout, estimatedHeightForItemAt indexPath: IndexPath, containedIn width: CGFloat) -> CGFloat { return height } func brickLayout(_ layout: BrickLayout, edgeInsetsFor section: Int) -> UIEdgeInsets { return edgeInsets } func brickLayout(_ layout: BrickLayout, insetFor section: Int) -> CGFloat { return inset } func brickLayout(_ layout: BrickLayout, brickLayoutTypeForItemAt indexPath: IndexPath) -> BrickLayoutType { return type } func brickLayout(_ layout: BrickLayout, isBrickHiddenAtIndexPath indexPath: IndexPath) -> Bool { return false } func brickLayout(_ layout: BrickLayout, identifierFor indexPath: IndexPath) -> String { return "" } func brickLayout(_ layout: BrickLayout, prefetchAttributeIndexPathsFor section: Int) -> [IndexPath] { return [] } } class FixedCardLayoutBehaviorDataSource: CardLayoutBehaviorDataSource { let height: CGFloat? init(height: CGFloat?) { self.height = height } func cardLayoutBehavior(_ behavior: CardLayoutBehavior, smallHeightForItemAt indexPath: IndexPath, with identifier: String, in collectionViewLayout: UICollectionViewLayout) -> CGFloat? { return height } } class FixedOffsetLayoutBehaviorDataSource: OffsetLayoutBehaviorDataSource { var originOffset: CGSize? var sizeOffset: CGSize? var indexPaths: [IndexPath]? init(originOffset: CGSize?, sizeOffset: CGSize?, indexPaths: [IndexPath]? = nil) { self.originOffset = originOffset self.sizeOffset = sizeOffset self.indexPaths = indexPaths } func offsetLayoutBehaviorWithOrigin(_ behavior: OffsetLayoutBehavior, originOffsetForItemAtIndexPath indexPath: IndexPath, withIdentifier identifier: String, inCollectionViewLayout collectionViewLayout: UICollectionViewLayout) -> CGSize? { if let indexPaths = self.indexPaths { if !indexPaths.contains(indexPath) { return nil } } return originOffset } func offsetLayoutBehavior(_ behavior: OffsetLayoutBehavior, sizeOffsetForItemAtIndexPath indexPath: IndexPath, withIdentifier identifier: String, inCollectionViewLayout collectionViewLayout: UICollectionViewLayout) -> CGSize? { if let indexPaths = self.indexPaths { if !indexPaths.contains(indexPath) { return nil } } return sizeOffset } } class FixedMultipleOffsetLayoutBehaviorDataSource: OffsetLayoutBehaviorDataSource { var originOffsets: [String: CGSize]? var sizeOffsets: [String: CGSize]? init(originOffsets: [String: CGSize]?, sizeOffsets: [String: CGSize]?) { self.originOffsets = originOffsets self.sizeOffsets = sizeOffsets } func offsetLayoutBehaviorWithOrigin(_ behavior: OffsetLayoutBehavior, originOffsetForItemAtIndexPath indexPath: IndexPath, withIdentifier identifier: String, inCollectionViewLayout collectionViewLayout: UICollectionViewLayout) -> CGSize? { return originOffsets?[identifier] } func offsetLayoutBehavior(_ behavior: OffsetLayoutBehavior, sizeOffsetForItemAtIndexPath indexPath: IndexPath, withIdentifier identifier: String, inCollectionViewLayout collectionViewLayout: UICollectionViewLayout) -> CGSize? { return sizeOffsets?[identifier] } }
apache-2.0
c106f49c831d68d741ca3f72e3b8768c
34.512739
243
0.67689
5.073248
false
false
false
false
whiteshadow-gr/HatForIOS
HAT/Objects/Fitbit/HATFitbitStatsLifetimeInformation.swift
1
1313
/** * Copyright (C) 2018 HAT Data Exchange Ltd * * SPDX-License-Identifier: MPL2 * * This file is part of the Hub of All Things project (HAT). * * 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/ */ // MARK: Struct public struct HATFitbitStatsLifetimeInformation: HATObject { // MARK: - Coding Keys /** The JSON fields used by the hat The Fields are the following: * `steps` in JSON is `steps` * `floors` in JSON is `floors` * `distance` in JSON is `distance` * `activeScore` in JSON is `activeScore` * `caloriesOut` in JSON is `caloriesOut` */ private enum CodingKeys: String, CodingKey { case steps case floors case distance case activeScore case caloriesOut } // MARK: - Variables /// The lifetime steps taken public var steps: Int = 0 /// The lifetime floors climbed public var floors: Int = 0 /// The lifetime distance public var distance: Float = 0 /// The lifetime active score public var activeScore: Int = 0 /// The lifetime calories burnt public var caloriesOut: Int = 0 }
mpl-2.0
30bb9ec0a1a9025a122e2c5171fadce7
25.26
70
0.626047
4.07764
false
false
false
false
wanghdnku/Whisper
Pods/KRProgressHUD/KRProgressHUD/Classes/KRProgressHUD.swift
1
18128
// // KRProgressHUD.swift // KRProgressHUD // // Copyright © 2016年 Krimpedance. All rights reserved. // import UIKit /** Type of KRProgressHUD's background view. - **Clear:** `UIColor.clearColor`. - **White:** `UIColor(white: 1, alpho: 0.2)`. - **Black:** `UIColor(white: 0, alpho: 0.2)`. Default type. */ public enum KRProgressHUDMaskType { case clear, white, black } /** Style of KRProgressHUD. - **Black:** HUD's backgroundColor is `.blackColor()`. HUD's text color is `.whiteColor()`. - **White:** HUD's backgroundColor is `.whiteColor()`. HUD's text color is `.blackColor()`. Default style. - **BlackColor:** same `.Black` and confirmation glyphs become original color. - **WhiteColor:** same `.Black` and confirmation glyphs become original color. */ public enum KRProgressHUDStyle { case black, white, blackColor, whiteColor } /** KRActivityIndicatorView style. (KRProgressHUD uses only large style.) - **Black:** the color is `.blackColor()`. Default style. - **White:** the color is `.blackColor()`. - **Color(startColor, endColor):** the color is a gradation to `endColor` from `startColor`. */ public enum KRProgressHUDActivityIndicatorStyle { case black, white, color(UIColor, UIColor) } /** * KRProgressHUD is a beautiful and easy-to-use progress HUD. */ public final class KRProgressHUD { fileprivate static let view = KRProgressHUD() class func sharedView() -> KRProgressHUD { return view } fileprivate let window = UIWindow(frame: UIScreen.main.bounds) fileprivate let progressHUDView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) fileprivate let iconView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50)) fileprivate let activityIndicatorView = KRActivityIndicatorView(position: CGPoint.zero, activityIndicatorStyle: .largeBlack) fileprivate let drawView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50)) fileprivate let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 150, height: 20)) fileprivate var tmpWindow: UIWindow? fileprivate var maskType: KRProgressHUDMaskType { willSet { switch newValue { case .clear: window.rootViewController?.view.backgroundColor = UIColor.clear case .white: window.rootViewController?.view.backgroundColor = UIColor(white: 1, alpha: 0.2) case .black: window.rootViewController?.view.backgroundColor = UIColor(white: 0, alpha: 0.2) } } } fileprivate var progressHUDStyle: KRProgressHUDStyle { willSet { switch newValue { case .black, .blackColor: progressHUDView.backgroundColor = UIColor.black messageLabel.textColor = UIColor.white case .white, .whiteColor: progressHUDView.backgroundColor = UIColor.white messageLabel.textColor = UIColor.black } } } fileprivate var activityIndicatorStyle: KRProgressHUDActivityIndicatorStyle { willSet { switch newValue { case .black: activityIndicatorView.activityIndicatorViewStyle = .largeBlack case .white: activityIndicatorView.activityIndicatorViewStyle = .largeWhite case let .color(sc, ec): activityIndicatorView.activityIndicatorViewStyle = .largeColor(sc, ec) } } } fileprivate var defaultStyle: KRProgressHUDStyle = .white { willSet { progressHUDStyle = newValue } } fileprivate var defaultMaskType: KRProgressHUDMaskType = .black { willSet { maskType = newValue } } fileprivate var defaultActivityIndicatorStyle: KRProgressHUDActivityIndicatorStyle = .black { willSet { activityIndicatorStyle = newValue } } fileprivate var defaultMessageFont = UIFont(name: "HiraginoSans-W3", size: 13) ?? UIFont.systemFont(ofSize: 13) { willSet { messageLabel.font = newValue } } fileprivate var defaultPosition: CGPoint = { let screenFrame = UIScreen.main.bounds return CGPoint(x: screenFrame.width/2, y: screenFrame.height/2) }() { willSet { progressHUDView.center = newValue } } public static var isVisible: Bool { return sharedView().window.alpha == 0 ? false : true } fileprivate init() { maskType = .black progressHUDStyle = .white activityIndicatorStyle = .black configureProgressHUDView() } fileprivate func configureProgressHUDView() { let rootViewController = KRProgressHUDViewController() window.rootViewController = rootViewController window.windowLevel = UIWindowLevelNormal window.alpha = 0 progressHUDView.center = defaultPosition progressHUDView.backgroundColor = UIColor.white progressHUDView.layer.cornerRadius = 10 progressHUDView.autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin] window.rootViewController?.view.addSubview(progressHUDView) iconView.backgroundColor = UIColor.clear iconView.center = CGPoint(x: 50, y: 50) progressHUDView.addSubview(iconView) activityIndicatorView.isHidden = false iconView.addSubview(activityIndicatorView) drawView.backgroundColor = UIColor.clear drawView.isHidden = true iconView.addSubview(drawView) messageLabel.center = CGPoint(x: 150/2, y: 90) messageLabel.backgroundColor = UIColor.clear messageLabel.font = defaultMessageFont messageLabel.textAlignment = .center messageLabel.adjustsFontSizeToFitWidth = true messageLabel.minimumScaleFactor = 0.5 messageLabel.text = nil messageLabel.isHidden = true progressHUDView.addSubview(messageLabel) } } /** * KRProgressHUD Setter -------------------------- */ extension KRProgressHUD { /// Set default mask type. /// - parameter type: `KRProgressHUDMaskType` public class func set(maskType type: KRProgressHUDMaskType) { KRProgressHUD.sharedView().defaultMaskType = type } /// Set default HUD style /// - parameter style: `KRProgressHUDStyle` public class func set(_ style: KRProgressHUDStyle) { KRProgressHUD.sharedView().defaultStyle = style } /// Set default KRActivityIndicatorView style. /// - parameter style: `KRProgresHUDActivityIndicatorStyle` public class func set(activityIndicatorStyle style: KRProgressHUDActivityIndicatorStyle) { KRProgressHUD.sharedView().defaultActivityIndicatorStyle = style } /// Set default HUD text font. /// - parameter font: text font public class func set(_ font: UIFont) { KRProgressHUD.sharedView().defaultMessageFont = font } /// Set default HUD center's position. /// - parameter position: center position public class func set(centerPosition position: CGPoint) { KRProgressHUD.sharedView().defaultPosition = position } } /** * KRProgressHUD Show & Dismiss -------------------------- */ extension KRProgressHUD { /** Showing HUD with some args. You can appoint only the args which You want to appoint. (Args is reflected only this time.) - parameter progressHUDStyle: KRProgressHUDStyle - parameter maskType: KRProgressHUDMaskType - parameter activityIndicatorStyle: KRProgressHUDActivityIndicatorStyle - parameter font: HUD's message font - parameter message: HUD's message - parameter image: image that Alternative to confirmation glyph. - parameter completion: completion handler. - returns: No return value. */ public class func show( progressHUDStyle progressStyle: KRProgressHUDStyle? = nil, maskType type: KRProgressHUDMaskType? = nil, activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle? = nil, font: UIFont? = nil, message: String? = nil, image: UIImage? = nil, completion: (()->())? = nil ) { KRProgressHUD.sharedView().updateStyles(progressHUDStyle: progressStyle, maskType: type, activityIndicatorStyle: indicatorStyle) KRProgressHUD.sharedView().updateProgressHUDViewText(font, message: message) KRProgressHUD.sharedView().updateProgressHUDViewIcon(image: image) KRProgressHUD.sharedView().show() { completion?() } } /** Showing HUD with success glyph. the HUD dismiss after 1 secound. You can appoint only the args which You want to appoint. (Args is reflected only this time.) - parameter progressHUDStyle: KRProgressHUDStyle - parameter maskType: KRProgressHUDMaskType - parameter activityIndicatorStyle: KRProgressHUDActivityIndicatorStyle - parameter font: HUD's message font - parameter message: HUD's message */ public class func showSuccess( progressHUDStyle progressStyle: KRProgressHUDStyle? = nil, maskType type: KRProgressHUDMaskType? = nil, activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle? = nil, font: UIFont? = nil, message: String? = nil) { KRProgressHUD.sharedView().updateStyles(progressHUDStyle: progressStyle, maskType: type, activityIndicatorStyle: indicatorStyle) KRProgressHUD.sharedView().updateProgressHUDViewText(font, message: message) KRProgressHUD.sharedView().updateProgressHUDViewIcon(.success) KRProgressHUD.sharedView().show() Thread.afterDelay(1.0) { KRProgressHUD.dismiss() } } /** Showing HUD with information glyph. the HUD dismiss after 1 secound. You can appoint only the args which You want to appoint. (Args is reflected only this time.) - parameter progressHUDStyle: KRProgressHUDStyle - parameter maskType: KRProgressHUDMaskType - parameter activityIndicatorStyle: KRProgressHUDActivityIndicatorStyle - parameter font: HUD's message font - parameter message: HUD's message */ public class func showInfo( progressHUDStyle progressStyle: KRProgressHUDStyle? = nil, maskType type: KRProgressHUDMaskType? = nil, activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle? = nil, font: UIFont? = nil, message: String? = nil) { KRProgressHUD.sharedView().updateStyles(progressHUDStyle: progressStyle, maskType: type, activityIndicatorStyle: indicatorStyle) KRProgressHUD.sharedView().updateProgressHUDViewText(font, message: message) KRProgressHUD.sharedView().updateProgressHUDViewIcon(.info) KRProgressHUD.sharedView().show() Thread.afterDelay(1.0) { KRProgressHUD.dismiss() } } /** Showing HUD with warning glyph. the HUD dismiss after 1 secound. You can appoint only the args which You want to appoint. (Args is reflected only this time.) - parameter progressHUDStyle: KRProgressHUDStyle - parameter maskType: KRProgressHUDMaskType - parameter activityIndicatorStyle: KRProgressHUDActivityIndicatorStyle - parameter font: HUD's message font - parameter message: HUD's message */ public class func showWarning( progressHUDStyle progressStyle: KRProgressHUDStyle? = nil, maskType type: KRProgressHUDMaskType? = nil, activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle? = nil, font: UIFont? = nil, message: String? = nil) { KRProgressHUD.sharedView().updateStyles(progressHUDStyle: progressStyle, maskType: type, activityIndicatorStyle: indicatorStyle) KRProgressHUD.sharedView().updateProgressHUDViewText(font, message: message) KRProgressHUD.sharedView().updateProgressHUDViewIcon(.warning) KRProgressHUD.sharedView().show() Thread.afterDelay(1.0) { KRProgressHUD.dismiss() } } /** Showing HUD with error glyph. the HUD dismiss after 1 secound. You can appoint only the args which You want to appoint. (Args is reflected only this time.) - parameter progressHUDStyle: KRProgressHUDStyle - parameter maskType: KRProgressHUDMaskType - parameter activityIndicatorStyle: KRProgressHUDActivityIndicatorStyle - parameter font: HUD's message font - parameter message: HUD's message */ public class func showError( progressHUDStyle progressStyle: KRProgressHUDStyle? = nil, maskType type: KRProgressHUDMaskType? = nil, activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle? = nil, font: UIFont? = nil, message: String? = nil) { KRProgressHUD.sharedView().updateStyles(progressHUDStyle: progressStyle, maskType: type, activityIndicatorStyle: indicatorStyle) KRProgressHUD.sharedView().updateProgressHUDViewText(font, message: message) KRProgressHUD.sharedView().updateProgressHUDViewIcon(.error) KRProgressHUD.sharedView().show() Thread.afterDelay(1.0) { KRProgressHUD.dismiss() } } /** Dismissing HUD. - parameter completion: handler when dismissed. - returns: No return value */ public class func dismiss(_ completion: (()->())? = nil) { DispatchQueue.main.async { () -> Void in UIView.animate(withDuration: 0.5, animations: { KRProgressHUD.sharedView().window.alpha = 0 }, completion: { _ in KRProgressHUD.sharedView().window.isHidden = true KRProgressHUD.sharedView().tmpWindow?.makeKey() KRProgressHUD.sharedView().activityIndicatorView.stopAnimating() KRProgressHUD.sharedView().progressHUDStyle = KRProgressHUD.sharedView().defaultStyle KRProgressHUD.sharedView().maskType = KRProgressHUD.sharedView().defaultMaskType KRProgressHUD.sharedView().activityIndicatorStyle = KRProgressHUD.sharedView().defaultActivityIndicatorStyle KRProgressHUD.sharedView().messageLabel.font = KRProgressHUD.sharedView().defaultMessageFont completion?() }) } } } /** * KRProgressHUD update during show -------------------------- */ extension KRProgressHUD { public class func update(_ text: String) { sharedView().messageLabel.text = text } } /** * KRProgressHUD update style method -------------------------- */ private extension KRProgressHUD { func show(_ completion: (()->())? = nil) { DispatchQueue.main.async { () -> Void in self.tmpWindow = UIApplication.shared.keyWindow self.window.alpha = 0 self.window.makeKeyAndVisible() UIView.animate(withDuration: 0.5, animations: { KRProgressHUD.sharedView().window.alpha = 1 }, completion: { _ in completion?() }) } } func updateStyles(progressHUDStyle progressStyle: KRProgressHUDStyle?, maskType type: KRProgressHUDMaskType?, activityIndicatorStyle indicatorStyle: KRProgressHUDActivityIndicatorStyle?) { if let style = progressStyle { KRProgressHUD.sharedView().progressHUDStyle = style } if let type = type { KRProgressHUD.sharedView().maskType = type } if let style = indicatorStyle { KRProgressHUD.sharedView().activityIndicatorStyle = style } } func updateProgressHUDViewText(_ font: UIFont?, message: String?) { if let text = message { let center = progressHUDView.center var frame = progressHUDView.frame frame.size = CGSize(width: 150, height: 110) progressHUDView.frame = frame progressHUDView.center = center iconView.center = CGPoint(x: 150/2, y: 40) messageLabel.isHidden = false messageLabel.text = text messageLabel.font = font ?? defaultMessageFont } else { let center = progressHUDView.center var frame = progressHUDView.frame frame.size = CGSize(width: 100, height: 100) progressHUDView.frame = frame progressHUDView.center = center iconView.center = CGPoint(x: 50, y: 50) messageLabel.isHidden = true } } func updateProgressHUDViewIcon(_ iconType: KRProgressHUDIconType? = nil, image: UIImage? = nil) { drawView.subviews.forEach { $0.removeFromSuperview() } drawView.layer.sublayers?.forEach { $0.removeFromSuperlayer() } switch (iconType, image) { case (nil, nil): drawView.isHidden = true activityIndicatorView.isHidden = false activityIndicatorView.startAnimating() case let (nil, image): activityIndicatorView.isHidden = true activityIndicatorView.stopAnimating() drawView.isHidden = false let imageView = UIImageView(image: image) imageView.frame = KRProgressHUD.sharedView().drawView.bounds imageView.contentMode = .scaleAspectFit drawView.addSubview(imageView) case let (type, _): drawView.isHidden = false activityIndicatorView.isHidden = true activityIndicatorView.stopAnimating() let pathLayer = CAShapeLayer() pathLayer.frame = drawView.layer.bounds pathLayer.lineWidth = 0 pathLayer.path = type!.getPath() switch progressHUDStyle { case .black: pathLayer.fillColor = UIColor.white.cgColor case .white: pathLayer.fillColor = UIColor.black.cgColor default: pathLayer.fillColor = type!.getColor() } drawView.layer.addSublayer(pathLayer) } } }
mit
dfb2bb1b5eeb8ebdeeb87859f2a2131f
38.835165
192
0.660248
5.611455
false
false
false
false
Sadmansamee/quran-ios
Quran/CollectionType+Extension.swift
1
934
// // CollectionType+Extension.swift // Quran // // Created by Mohamed Afifi on 5/23/16. // Copyright © 2016 Quran.com. All rights reserved. // extension Collection where Index: Strideable { // Implementation from: http://stackoverflow.com/questions/31904396/swift-binary-search-for-standard-array func binarySearch(_ predicate: (Iterator.Element) -> Bool) -> Index { var low = startIndex var high = endIndex while low != high { let mid = self.index(low, offsetBy: self.distance(from: low, to: high) / 2) if predicate(self[mid]) { low = self.index(mid, offsetBy: 1) } else { high = mid } } return low } } extension Collection where Index: Strideable, Iterator.Element: Comparable { func binarySearch(_ value: Iterator.Element) -> Index { return binarySearch { $0 < value } } }
mit
99768d258a02dae234aadae51706f614
28.15625
110
0.601286
4.146667
false
false
false
false
cemolcay/DroppyMenuController
DroppyMenuController/DroppyMenuController/DroppyMenuView.swift
1
7386
// // DroppyMenuView.swift // DroppyMenuController // // Created by Cem Olcay on 23/02/15. // Copyright (c) 2015 Cem Olcay. All rights reserved. // import UIKit extension UIView { var x: CGFloat { get { return self.frame.origin.x } set (value) { self.frame = CGRect (x: value, y: self.y, width: self.w, height: self.h) } } var y: CGFloat { get { return self.frame.origin.y } set (value) { self.frame = CGRect (x: self.x, y: value, width: self.w, height: self.h) } } var w: CGFloat { get { return self.frame.size.width } set (value) { self.frame = CGRect (x: self.x, y: self.y, width: value, height: self.h) } } var h: CGFloat { get { return self.frame.size.height } set (value) { self.frame = CGRect (x: self.x, y: self.y, width: self.w, height: value) } } var left: CGFloat { get { return self.x } set (value) { self.x = value } } var right: CGFloat { get { return self.x + self.w } set (value) { self.x = value - self.w } } var top: CGFloat { get { return self.y } set (value) { self.y = value } } var bottom: CGFloat { get { return self.y + self.h } set (value) { self.y = value - self.h } } var position: CGPoint { get { return self.frame.origin } set (value) { self.frame = CGRect (origin: value, size: self.frame.size) } } var size: CGSize { get { return self.frame.size } set (value) { self.frame = CGRect (origin: self.frame.origin, size: value) } } func leftWithOffset (offset: CGFloat) -> CGFloat { return self.left - offset } func rightWithOffset (offset: CGFloat) -> CGFloat { return self.right + offset } func topWithOffset (offset: CGFloat) -> CGFloat { return self.top - offset } func bottomWithOffset (offset: CGFloat) -> CGFloat { return self.bottom + offset } } struct DroppyMenuViewAppeareance { var tintColor: UIColor var font: UIFont var backgroundColor: UIColor var lineWidth: CGFloat var gravityMagnitude: CGFloat var springVelocity: CGFloat var springDamping: CGFloat } extension DroppyMenuViewAppeareance { init () { self.tintColor = UIColor.whiteColor() self.font = UIFont (name: "HelveticaNeue-Light", size: 20)! self.backgroundColor = UIColor (white: 0, alpha: 0.5) self.gravityMagnitude = 10 self.springDamping = 0.9 self.springVelocity = 0.9 self.lineWidth = 1 } } protocol DroppyMenuViewDelegate { func droppyMenu (droppyMenu: DroppyMenuView, didItemPressedAtIndex index: Int) func droppyMenuDidClosePressed (droppyMenu: DroppyMenuView) } class DroppyMenuView: UIView { // MARK: Properties var delegate: DroppyMenuViewDelegate? var appeareance: DroppyMenuViewAppeareance! { didSet { backgroundColor = appeareance.backgroundColor for view in subviews { if let view = view as? UIButton { view.setTitleColor(appeareance.tintColor, forState: .Normal) view.titleLabel?.font = appeareance.font if let layer = view.layer.sublayers?[0] as? CAShapeLayer { layer.strokeColor = appeareance.tintColor.CGColor layer.lineWidth = appeareance.lineWidth } else if let layer = view.layer.sublayers?[1] as? CALayer { layer.backgroundColor = appeareance.tintColor.CGColor var f = layer.frame f.size.height = appeareance.lineWidth layer.frame = f } } } } } var isAnimating: Bool = false // MARK: Lifecycle convenience init (items: [String]) { self.init (items: items, appeareance: DroppyMenuViewAppeareance()) } init (items: [String], appeareance: DroppyMenuViewAppeareance) { super.init(frame: UIScreen.mainScreen().bounds) self.appeareance = appeareance let itemHeight = frame.size.height / CGFloat(items.count + 1) var currentY: CGFloat = 0 var tag: Int = 0 for title in items { let item = createItem(title, currentY: currentY, itemHeight: itemHeight) item.tag = tag++ currentY += item.h addSubview(item) } let close = closeButton(itemHeight) close.y = currentY addSubview(close) backgroundColor = appeareance.backgroundColor } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: Create func createItem (title: String, currentY: CGFloat, itemHeight: CGFloat) -> UIView { let button = UIButton (frame: CGRect (x: 0, y: currentY, width: frame.size.width, height: itemHeight)) button.setTitle(title, forState: .Normal) button.setTitleColor(appeareance.tintColor, forState: .Normal) button.titleLabel?.font = appeareance.font button.addTarget(self, action: "itemPressed:", forControlEvents: .TouchUpInside) let sep = CALayer () sep.frame = CGRect (x: 0, y: button.h, width: button.w, height: appeareance.lineWidth) sep.backgroundColor = appeareance.tintColor.CGColor button.layer.addSublayer(sep) return button } func closeButton (itemHeight: CGFloat) -> UIView { let button = UIButton (frame: CGRect (x: 0, y: 0, width: frame.size.width, height: itemHeight)) button.addTarget(self, action: "closePressed:", forControlEvents: .TouchUpInside) let close = CAShapeLayer () close.frame = CGRect (x: 0, y: 0, width: 20, height: 20) close.position = button.layer.position let path = UIBezierPath () let a: CGFloat = 20 path.moveToPoint(CGPoint (x: 0, y: 0)) path.addLineToPoint(CGPoint (x: a, y: a)) path.moveToPoint(CGPoint (x: 0, y: a)) path.addLineToPoint(CGPoint (x: a, y: 0)) close.path = path.CGPath close.lineWidth = appeareance.lineWidth close.strokeColor = appeareance.tintColor.CGColor button.layer.addSublayer (close) return button } // MARK: Action func itemPressed (sender: UIButton) { if isAnimating { return } delegate?.droppyMenu(self, didItemPressedAtIndex: sender.tag) } func closePressed (sender: UIButton) { if isAnimating { return } delegate?.droppyMenuDidClosePressed(self) } }
mit
2f2afd541266f3aae633c88fec6f3049
25.858182
110
0.543731
4.393813
false
false
false
false
kumabook/StickyNotesiOS
StickyNotes/PageStickyTableViewController.swift
1
3094
// // PageStickyTableViewController.swift // StickyNotes // // Created by Hiroki Kumamoto on 8/13/16. // Copyright © 2016 kumabook. All rights reserved. // import UIKit class PageStickyTableViewController: UITableViewController { var cellHeight: CGFloat = 160 var appDelegate: AppDelegate { return UIApplication.shared.delegate as! AppDelegate } let reuseIdentifier = "PageStickyTableViewCell" var page: PageEntity? { didSet { self.tableView.reloadData() } } func reloadData() { tableView.reloadData() } override func viewDidLoad() { super.viewDidLoad() let nib = UINib(nibName: "PageStickyTableViewCell", bundle: nil) title = "Sticky list" tableView.register(nib, forCellReuseIdentifier: reuseIdentifier) Store.shared.state.subscribe {[weak self] state in switch state.mode.value { default: self?.reloadData() break } } } func editButtonTapped(_ sticky: StickyEntity) { let vc = EditStickyViewController(sticky: sticky) navigationController?.pushViewController(vc, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() title = "Stickies" } // MARK: - Table view data source override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return cellHeight } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let page = page else { return 0 } return page.stickies.count } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { guard let page = page else { return [] } let sticky = page.stickies[indexPath.item] let remove = UITableViewRowAction(style: .default, title: "Remove".localize()) { (action, indexPath) in Store.shared.dispatch(DeleteStickyAction(sticky: sticky)) } remove.backgroundColor = UIColor.red return [remove] } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for:indexPath) as! PageStickyTableViewCell guard let page = page else { return cell } let sticky = page.stickies[indexPath.item] cell.updateView(sticky) cell.delegate = self return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let page = page else { return } let sticky = page.stickies[indexPath.item] Store.shared.dispatch(JumpStickyAction(sticky: sticky)) } }
mit
b93e9c3629ee3a81fe901ed8834413c5
32.258065
124
0.659554
5.053922
false
false
false
false
czgarrett/SwiftPlaygrounds
CodableWithInheritance.playground/Contents.swift
1
7971
import Foundation // needed for Encoder/Decoder ////////////////////////////////////////////////////////// /// Some helper methods for our playground /////////////////////////////////////////////////////// func encodeJSON<T:Codable>(_ codable: T) throws -> Data { let jsonEncoder = JSONEncoder() jsonEncoder.outputFormatting = .prettyPrinted return try jsonEncoder.encode(codable) } func encodeAndPrint<T:Codable>(_ codable: T) throws { let encodedData = try encodeJSON(codable) let json = String.init(data: encodedData, encoding: .utf8)! print("Here's the JSON for \(String(describing: codable)) encoded\n\n\(json)\n") } func decodeAndPrint<T:Codable>(_ type: T.Type, data: Data) throws { let decoder = JSONDecoder() let object = try decoder.decode(type, from: data) print("Result of decoding data: \n\(String(describing: object))\n") } /////////////////////////////////////////////////////////// /// Simple Example /////////////////////////////////////////////////////// struct BikeWheel: Codable { let diameter: Float let make: String let spokes: Int let valveType: String? // What do nil values look like when encoded? } // Encode a bikewheel to see its JSON let wheel = BikeWheel(diameter: 26.0, make: "Mavic", spokes: 24, valveType: nil) ////////////////////////////////////////////////////////// /// More complicated example /////////////////////////////////////////////////////// // An enum with associated values enum BikeSize: Codable { case topTube(length: Float) case name(String) } // For an associated value enum, we need to provide an implementation to encode/decode it extension BikeSize { private enum CodingKeys: String, CodingKey { // Sometimes we want to conserve storage space for heavily used objects, // so we can use shorter keys for coding. case topTube = "t" case name = "n" } enum BikeSizeCodingError: Error { case missingKey(String) } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) if let value = try? values.decode(Float.self, forKey: .topTube) { self = .topTube(length: value) return } if let value = try? values.decode(String.self, forKey: .name) { self = .name(value) return } throw BikeSizeCodingError.missingKey("Missing key") } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case .topTube(let length): try container.encode(length, forKey: .topTube) case .name(let name): try container.encode(name, forKey: .name) } } } class Bike: Codable { private enum CodingKeys: String, CodingKey { // Sometimes we want to conserve storage space for heavily used objects, // so we can use shorter keys for coding. case make case model case size case wheels case prices } var make: String? var model: String? var size: BikeSize? var wheels: [BikeWheel] = [] // We can't do this: // let prices: [Any] // Or this: // let prices: [Codable] // But we can do a specific type of codable such as an array of Doubles var prices: [Double] = [] init(make: String, model: String, size: BikeSize, wheels: [BikeWheel], prices: [Double]) { self.make = make self.model = model self.size = size self.wheels = wheels self.prices = prices } required init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.make = try values.decode(String.self, forKey: .make) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.make, forKey: .make) } } // Create a subclass with some additional properties class MountainBike: Bike { private enum CodingKeys: String, CodingKey { case suspension } var suspension: String = "" override init(make: String, model: String, size: BikeSize, wheels: [BikeWheel], prices: [Double]) { super.init(make: make, model: model, size: size, wheels: wheels, prices: prices) } required init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.suspension = try values.decode(String.self, forKey: .suspension) try super.init(from: decoder) } override func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.suspension, forKey: .suspension) try super.encode(to: encoder) } } let mountainBike = MountainBike(make: "Specialized", model: "Carbon Camber Comp", size: .name("L"), wheels: [wheel, wheel], prices: [2999.0]) mountainBike.suspension = "Front" let roadBike = Bike(make: "Specialized", model: "Allez Comp", size: .name("M"), wheels: [wheel, wheel], prices: [4999.0]) try encodeAndPrint(mountainBike) // Store our previous bike let bikeData = try encodeJSON(mountainBike) // Try to decode our mountain bike from previous bike data try decodeAndPrint(Bike.self, data: bikeData) // Note that the returned type is of type Bike, not Mountain Bike. This is because the JSON doesn't have any info about which subclass it encodes, // and the init method can't figure it out // If we use the mountain bike class it works: try decodeAndPrint(MountainBike.self, data: bikeData) // An array of two different kinds of Bike: let array = [mountainBike, roadBike] try encodeAndPrint(array) let arrayData = try encodeJSON(array) // Unfortunately this will just decode everything as a bike try decodeAndPrint(Array<Bike>.self, data: arrayData) // If we want to do a heterogenous collection of Bike and its subclass types, we could use an enum to do this: enum BikeReference: Codable { case bike(Bike) case mountainBike(MountainBike) enum BikeReferenceCodingError: Error { case missingKey } private enum CodingKeys: String, CodingKey { // Sometimes we want to conserve storage space for heavily used objects, // so we can use shorter keys for coding. case mountainBike = "m" case bike = "b" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) if values.contains(.bike) { let bike = try values.decode(Bike.self, forKey: .bike) self = .bike(bike) } else if values.contains(.mountainBike) { let bike = try values.decode(MountainBike.self, forKey: .mountainBike) self = .mountainBike(bike) } else { throw BikeReferenceCodingError.missingKey } } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case .bike(let bike): try container.encode(bike, forKey: .bike) case .mountainBike(let mtb): try container.encode(mtb, forKey: .mountainBike) } } } // Now we can have an array of those references let bikeRefs = [BikeReference.mountainBike(mountainBike), BikeReference.bike(roadBike)] let heterogeneousData = try encodeJSON(bikeRefs) // Unfortunately this will just decode everything as a bike try decodeAndPrint(Array<BikeReference>.self, data: heterogeneousData) ////////////////////////////////////////////////////////// /// Discussion /// /// Swift inheritance + Codable seems to be a pain. I'm going to work up another example that uses composition instead of inheritance to do the same thing. /// ///////////////////////////////////////////////////////
mit
41fe0196fe1dbdfdb5cff1a72be84f25
31.534694
156
0.621377
4.151563
false
false
false
false
DarrenKong/firefox-ios
Client/Frontend/Browser/Tab.swift
1
20341
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit import Storage import Shared import SwiftyJSON import XCGLogger protocol TabContentScript { static func name() -> String func scriptMessageHandlerName() -> String? func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) } @objc protocol TabDelegate { func tab(_ tab: Tab, didAddSnackbar bar: SnackBar) func tab(_ tab: Tab, didRemoveSnackbar bar: SnackBar) func tab(_ tab: Tab, didSelectFindInPageForSelection selection: String) @objc optional func tab(_ tab: Tab, didCreateWebView webView: WKWebView) @objc optional func tab(_ tab: Tab, willDeleteWebView webView: WKWebView) } @objc protocol URLChangeDelegate { func tab(_ tab: Tab, urlDidChangeTo url: URL) } struct TabState { var isPrivate: Bool = false var desktopSite: Bool = false var url: URL? var title: String? var favicon: Favicon? } class Tab: NSObject { fileprivate var _isPrivate: Bool = false internal fileprivate(set) var isPrivate: Bool { get { return _isPrivate } set { if _isPrivate != newValue { _isPrivate = newValue } } } var tabState: TabState { return TabState(isPrivate: _isPrivate, desktopSite: desktopSite, url: url, title: displayTitle, favicon: displayFavicon) } // PageMetadata is derived from the page content itself, and as such lags behind the // rest of the tab. var pageMetadata: PageMetadata? var canonicalURL: URL? { if let string = pageMetadata?.siteURL, let siteURL = URL(string: string) { return siteURL } return self.url } var userActivity: NSUserActivity? var webView: WKWebView? var tabDelegate: TabDelegate? weak var urlDidChangeDelegate: URLChangeDelegate? // TODO: generalize this. var bars = [SnackBar]() var favicons = [Favicon]() var lastExecutedTime: Timestamp? var sessionData: SessionData? fileprivate var lastRequest: URLRequest? var restoring: Bool = false var pendingScreenshot = false var url: URL? var mimeType: String? fileprivate var _noImageMode = false /// Returns true if this tab's URL is known, and it's longer than we want to store. var urlIsTooLong: Bool { guard let url = self.url else { return false } return url.absoluteString.lengthOfBytes(using: .utf8) > AppConstants.DB_URL_LENGTH_MAX } // Use computed property so @available can be used to guard `noImageMode`. @available(iOS 11, *) var noImageMode: Bool { get { return _noImageMode } set { if newValue == _noImageMode { return } _noImageMode = newValue let helper = (contentBlocker as? ContentBlockerHelper) helper?.noImageMode(enabled: _noImageMode) } } // There is no 'available macro' on props, we currently just need to store ownership. var contentBlocker: AnyObject? /// The last title shown by this tab. Used by the tab tray to show titles for zombie tabs. var lastTitle: String? /// Whether or not the desktop site was requested with the last request, reload or navigation. Note that this property needs to /// be managed by the web view's navigation delegate. var desktopSite: Bool = false var readerModeAvailableOrActive: Bool { if let readerMode = self.getContentScript(name: "ReaderMode") as? ReaderMode { return readerMode.state != .unavailable } return false } fileprivate(set) var screenshot: UIImage? var screenshotUUID: UUID? // If this tab has been opened from another, its parent will point to the tab from which it was opened var parent: Tab? fileprivate var contentScriptManager = TabContentScriptManager() private(set) var userScriptManager: UserScriptManager? fileprivate var configuration: WKWebViewConfiguration? /// Any time a tab tries to make requests to display a Javascript Alert and we are not the active /// tab instance, queue it for later until we become foregrounded. fileprivate var alertQueue = [JSAlertInfo]() init(configuration: WKWebViewConfiguration, isPrivate: Bool = false) { self.configuration = configuration super.init() self.isPrivate = isPrivate if #available(iOS 11, *) { if let appDelegate = UIApplication.shared.delegate as? AppDelegate, let profile = appDelegate.profile { contentBlocker = ContentBlockerHelper(tab: self, profile: profile) } } } class func toTab(_ tab: Tab) -> RemoteTab? { if let displayURL = tab.url?.displayURL, RemoteTab.shouldIncludeURL(displayURL) { let history = Array(tab.historyList.filter(RemoteTab.shouldIncludeURL).reversed()) return RemoteTab(clientGUID: nil, URL: displayURL, title: tab.displayTitle, history: history, lastUsed: Date.now(), icon: nil) } else if let sessionData = tab.sessionData, !sessionData.urls.isEmpty { let history = Array(sessionData.urls.filter(RemoteTab.shouldIncludeURL).reversed()) if let displayURL = history.first { return RemoteTab(clientGUID: nil, URL: displayURL, title: tab.displayTitle, history: history, lastUsed: sessionData.lastUsedTime, icon: nil) } } return nil } weak var navigationDelegate: WKNavigationDelegate? { didSet { if let webView = webView { webView.navigationDelegate = navigationDelegate } } } func createWebview() { if webView == nil { assert(configuration != nil, "Create webview can only be called once") configuration!.userContentController = WKUserContentController() configuration!.preferences = WKPreferences() configuration!.preferences.javaScriptCanOpenWindowsAutomatically = false configuration!.allowsInlineMediaPlayback = true let webView = TabWebView(frame: .zero, configuration: configuration!) webView.delegate = self configuration = nil webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view") webView.allowsBackForwardNavigationGestures = true webView.allowsLinkPreview = false // Night mode enables this by toggling WKWebView.isOpaque, otherwise this has no effect. webView.backgroundColor = .black // Turning off masking allows the web content to flow outside of the scrollView's frame // which allows the content appear beneath the toolbars in the BrowserViewController webView.scrollView.layer.masksToBounds = false webView.navigationDelegate = navigationDelegate restore(webView) self.webView = webView self.webView?.addObserver(self, forKeyPath: KVOConstants.URL.rawValue, options: .new, context: nil) self.userScriptManager = UserScriptManager(tab: self) tabDelegate?.tab?(self, didCreateWebView: webView) } } func restore(_ webView: WKWebView) { // Pulls restored session data from a previous SavedTab to load into the Tab. If it's nil, a session restore // has already been triggered via custom URL, so we use the last request to trigger it again; otherwise, // we extract the information needed to restore the tabs and create a NSURLRequest with the custom session restore URL // to trigger the session restore via custom handlers if let sessionData = self.sessionData { restoring = true var urls = [String]() for url in sessionData.urls { urls.append(url.absoluteString) } let currentPage = sessionData.currentPage self.sessionData = nil var jsonDict = [String: AnyObject]() jsonDict["history"] = urls as AnyObject? jsonDict["currentPage"] = currentPage as AnyObject? guard let json = JSON(jsonDict).stringValue() else { return } let escapedJSON = json.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! let restoreURL = URL(string: "\(WebServer.sharedInstance.base)/about/sessionrestore?history=\(escapedJSON)") lastRequest = PrivilegedRequest(url: restoreURL!) as URLRequest webView.load(lastRequest!) } else if let request = lastRequest { webView.load(request) } else { print("creating webview with no lastRequest and no session data: \(self.url?.description ?? "nil")") } } deinit { if let webView = webView { webView.removeObserver(self, forKeyPath: KVOConstants.URL.rawValue) tabDelegate?.tab?(self, willDeleteWebView: webView) } } var loading: Bool { return webView?.isLoading ?? false } var estimatedProgress: Double { return webView?.estimatedProgress ?? 0 } var backList: [WKBackForwardListItem]? { return webView?.backForwardList.backList } var forwardList: [WKBackForwardListItem]? { return webView?.backForwardList.forwardList } var historyList: [URL] { func listToUrl(_ item: WKBackForwardListItem) -> URL { return item.url } var tabs = self.backList?.map(listToUrl) ?? [URL]() tabs.append(self.url!) return tabs } var title: String? { return webView?.title } var displayTitle: String { if let title = webView?.title, !title.isEmpty { return title } // When picking a display title. Tabs with sessionData are pending a restore so show their old title. // To prevent flickering of the display title. If a tab is restoring make sure to use its lastTitle. if let url = self.url, url.isAboutHomeURL, sessionData == nil, !restoring { return "" } guard let lastTitle = lastTitle, !lastTitle.isEmpty else { return self.url?.displayURL?.absoluteString ?? "" } return lastTitle } var currentInitialURL: URL? { return self.webView?.backForwardList.currentItem?.initialURL } var displayFavicon: Favicon? { return favicons.max { $0.width! < $1.width! } } var canGoBack: Bool { return webView?.canGoBack ?? false } var canGoForward: Bool { return webView?.canGoForward ?? false } func goBack() { _ = webView?.goBack() } func goForward() { _ = webView?.goForward() } func goToBackForwardListItem(_ item: WKBackForwardListItem) { _ = webView?.go(to: item) } @discardableResult func loadRequest(_ request: URLRequest) -> WKNavigation? { if let webView = webView { lastRequest = request return webView.load(request) } return nil } func stop() { webView?.stopLoading() } func reload() { let userAgent: String? = desktopSite ? UserAgent.desktopUserAgent() : nil if (userAgent ?? "") != webView?.customUserAgent, let currentItem = webView?.backForwardList.currentItem { webView?.customUserAgent = userAgent // Reload the initial URL to avoid UA specific redirection loadRequest(PrivilegedRequest(url: currentItem.initialURL, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60) as URLRequest) return } if let _ = webView?.reloadFromOrigin() { print("reloaded zombified tab from origin") return } if let webView = self.webView { print("restoring webView from scratch") restore(webView) } } func addContentScript(_ helper: TabContentScript, name: String) { contentScriptManager.addContentScript(helper, name: name, forTab: self) } func getContentScript(name: String) -> TabContentScript? { return contentScriptManager.getContentScript(name) } func hideContent(_ animated: Bool = false) { webView?.isUserInteractionEnabled = false if animated { UIView.animate(withDuration: 0.25, animations: { () -> Void in self.webView?.alpha = 0.0 }) } else { webView?.alpha = 0.0 } } func showContent(_ animated: Bool = false) { webView?.isUserInteractionEnabled = true if animated { UIView.animate(withDuration: 0.25, animations: { () -> Void in self.webView?.alpha = 1.0 }) } else { webView?.alpha = 1.0 } } func addSnackbar(_ bar: SnackBar) { bars.append(bar) tabDelegate?.tab(self, didAddSnackbar: bar) } func removeSnackbar(_ bar: SnackBar) { if let index = bars.index(of: bar) { bars.remove(at: index) tabDelegate?.tab(self, didRemoveSnackbar: bar) } } func removeAllSnackbars() { // Enumerate backwards here because we'll remove items from the list as we go. bars.reversed().forEach { removeSnackbar($0) } } func expireSnackbars() { // Enumerate backwards here because we may remove items from the list as we go. bars.reversed().filter({ !$0.shouldPersist(self) }).forEach({ removeSnackbar($0) }) } func setScreenshot(_ screenshot: UIImage?, revUUID: Bool = true) { self.screenshot = screenshot if revUUID { self.screenshotUUID = UUID() } } func toggleDesktopSite() { desktopSite = !desktopSite reload() } func queueJavascriptAlertPrompt(_ alert: JSAlertInfo) { alertQueue.append(alert) } func dequeueJavascriptAlertPrompt() -> JSAlertInfo? { guard !alertQueue.isEmpty else { return nil } return alertQueue.removeFirst() } func cancelQueuedAlerts() { alertQueue.forEach { alert in alert.cancel() } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { guard let webView = object as? WKWebView, webView == self.webView, let path = keyPath, path == KVOConstants.URL.rawValue else { return assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")") } guard let url = self.webView?.url else { return } self.urlDidChangeDelegate?.tab(self, urlDidChangeTo: url) } func isDescendentOf(_ ancestor: Tab) -> Bool { return sequence(first: parent) { $0?.parent }.contains { $0 == ancestor } } func setNightMode(_ enabled: Bool) { webView?.evaluateJavaScript("window.__firefox__.NightMode.setEnabled(\(enabled))", completionHandler: nil) // For WKWebView background color to take effect, isOpaque must be false, which is counter-intuitive. Default is true. // The color is previously set to black in the webview init webView?.isOpaque = !enabled } func injectUserScriptWith(fileName: String, type: String = "js", injectionTime: WKUserScriptInjectionTime = .atDocumentEnd, mainFrameOnly: Bool = true) { guard let webView = self.webView else { return } if let path = Bundle.main.path(forResource: fileName, ofType: type), let source = try? String(contentsOfFile: path) { let userScript = WKUserScript(source: source, injectionTime: injectionTime, forMainFrameOnly: mainFrameOnly) webView.configuration.userContentController.addUserScript(userScript) } } func observeURLChanges(delegate: URLChangeDelegate) { self.urlDidChangeDelegate = delegate } func removeURLChangeObserver(delegate: URLChangeDelegate) { if let existing = self.urlDidChangeDelegate, existing === delegate { self.urlDidChangeDelegate = nil } } } extension Tab: TabWebViewDelegate { fileprivate func tabWebView(_ tabWebView: TabWebView, didSelectFindInPageForSelection selection: String) { tabDelegate?.tab(self, didSelectFindInPageForSelection: selection) } } private class TabContentScriptManager: NSObject, WKScriptMessageHandler { fileprivate var helpers = [String: TabContentScript]() @objc func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { for helper in helpers.values { if let scriptMessageHandlerName = helper.scriptMessageHandlerName() { if scriptMessageHandlerName == message.name { helper.userContentController(userContentController, didReceiveScriptMessage: message) return } } } } func addContentScript(_ helper: TabContentScript, name: String, forTab tab: Tab) { if let _ = helpers[name] { assertionFailure("Duplicate helper added: \(name)") } helpers[name] = helper // If this helper handles script messages, then get the handler name and register it. The Browser // receives all messages and then dispatches them to the right TabHelper. if let scriptMessageHandlerName = helper.scriptMessageHandlerName() { tab.webView?.configuration.userContentController.add(self, name: scriptMessageHandlerName) } } func getContentScript(_ name: String) -> TabContentScript? { return helpers[name] } } private protocol TabWebViewDelegate: class { func tabWebView(_ tabWebView: TabWebView, didSelectFindInPageForSelection selection: String) } private class TabWebView: WKWebView, MenuHelperInterface { fileprivate weak var delegate: TabWebViewDelegate? override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { return super.canPerformAction(action, withSender: sender) || action == MenuHelper.SelectorFindInPage } @objc func menuHelperFindInPage() { evaluateJavaScript("getSelection().toString()") { result, _ in let selection = result as? String ?? "" self.delegate?.tabWebView(self, didSelectFindInPageForSelection: selection) } } fileprivate override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { // The find-in-page selection menu only appears if the webview is the first responder. becomeFirstResponder() return super.hitTest(point, with: event) } } /// // Temporary fix for Bug 1390871 - NSInvalidArgumentException: -[WKContentView menuHelperFindInPage]: unrecognized selector // // This class only exists to contain the swizzledMenuHelperFindInPage. This class is actually never // instantiated. It only serves as a placeholder for the method. When the method is called, self is // actually pointing to a WKContentView. Which is not public, but that is fine, we only need to know // that it is a UIView subclass to access its superview. // class TabWebViewMenuHelper: UIView { @objc func swizzledMenuHelperFindInPage() { if let tabWebView = superview?.superview as? TabWebView { tabWebView.evaluateJavaScript("getSelection().toString()") { result, _ in let selection = result as? String ?? "" tabWebView.delegate?.tabWebView(tabWebView, didSelectFindInPageForSelection: selection) } } } }
mpl-2.0
f70b5da2303011cc17adbe15a67c6b67
34.623468
157
0.6393
5.273788
false
false
false
false
MoooveOn/Advanced-Frameworks
Movies/MovieSelector3DTouch/MovieSelector/Movie.swift
1
6520
// // Movie.swift // MovieSelector // // Created by Pavel Selivanov on 10.07.17. // Copyright © 2017 Pavel Selivanov. All rights reserved. // import UIKit public struct Movie { private static let APIKEY = "ab5ca251920d475619647b10a29109e8" private static let imageBaseURL = "http://image.tmdb.org/t/p/w500" public var title: String! public var imagePath: String! public var description: String! init(title: String, imagePath: String, description: String) { self.title = title self.imagePath = imagePath self.description = description } private static func getMovieData(with completion: @escaping (_ success: Bool, _ object: AnyObject?) ->()) { let session = URLSession(configuration: .default) let request = URLRequest(url: URL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=\(APIKEY)")!) session.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in if let data = data { let json = try? JSONSerialization.jsonObject(with: data, options: []) if let response = response as? HTTPURLResponse, 200...299 ~= response.statusCode { completion(true, json as AnyObject?) } else { completion(false, json as AnyObject?) } } }.resume() } public static func nowPlaying(with completion: @escaping (_ success: Bool, _ movies: [Movie]?) -> () ) { Movie.getMovieData { (success, object) in if success { var movieArray = [Movie]() if let movieResults = object?["results"] as? [Dictionary<String, Any>] { for movie in movieResults { let title = movie["original_title"] as! String let overview = movie["overview"] as! String guard let posterImage = movie["poster_path"] as? String else {continue} let movieObject = Movie(title: title, imagePath: posterImage, description: overview) movieArray.append(movieObject) } completion(true, movieArray) } else { completion(false, nil) } } } } private static func getDocumentsDirectory() -> String? { let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) guard let documents: String = paths.first else { return nil } return documents } private static func checkForImageData(withMovieObject movie: Movie) -> String? { if let documents = getDocumentsDirectory() { let movieImagePath = documents + "/\(movie.title)" let escapedImagePath = movieImagePath.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) if FileManager.default.fileExists(atPath: escapedImagePath!) { return escapedImagePath } } return nil } public static func getImage(forMovie movie: Movie) -> UIImage? { if let imagePath = checkForImageData(withMovieObject: movie) { if let imageData = FileManager.default.contents(atPath: imagePath) { return UIImage(data: imageData) } } return nil } public static func getImage(forCell cell: AnyObject, withMovieObject movie: Movie) { if let imagePath = checkForImageData(withMovieObject: movie) { // Image already downloaded if let imageData = FileManager.default.contents(atPath: imagePath) { if cell is UITableViewCell { let tableViewCell = cell as! UITableViewCell tableViewCell.imageView?.image = UIImage(data: imageData) tableViewCell.setNeedsLayout() } else { let collectionViewCell = cell as! MovieCollectionViewCell collectionViewCell.movieImageView.image = UIImage(data: imageData) collectionViewCell.setNeedsLayout() } } } else { // Download an image and save on disk let imagePath = Movie.imageBaseURL + movie.imagePath let imageURL = URL(string: imagePath) DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async { do { let data = try Data(contentsOf: imageURL!) let documents = getDocumentsDirectory() let imageFilePathString = documents! + "/\(movie.title)" let escapedImagePath = imageFilePathString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)! if FileManager.default.createFile(atPath: escapedImagePath, contents: data, attributes: nil) { print("Image saved.") } DispatchQueue.main.async { if cell is UITableViewCell { let tableViewCell = cell as! UITableViewCell tableViewCell.imageView?.image = UIImage(data: data) tableViewCell.setNeedsLayout() } else { let collectionViewCell = cell as! MovieCollectionViewCell collectionViewCell.movieImageView.image = UIImage(data: data) collectionViewCell.setNeedsLayout() } } } catch { print("No image at specified location.") //print(imageURL) } } } } }
mit
26633b9f9b21c3ade8746a3e65aee6e4
31.272277
139
0.506366
6.167455
false
false
false
false
voucherifyio/voucherify-ios-sdk
VoucherifySwiftSdk/Classes/Models/OrderItem.swift
1
750
import Foundation import ObjectMapper public struct OrderItem: Mappable { public var productId: String? public var skuId: String? public var quantity: Int? public var price: Int? public init(productId: String, skuId: String, quantity: Int, price: Int? = nil) { self.productId = productId self.skuId = skuId self.quantity = quantity self.price = price } public init?(map: Map) { mapping(map: map) } mutating public func mapping(map: Map) { productId <- map["product_id"] skuId <- map["sku_id"] quantity <- map["quantity"] price <- map["price"] } }
mit
d8c7951cb031a4d00b18db28a885c5ff
22.4375
44
0.530667
4.411765
false
false
false
false
nathawes/swift
test/ClangImporter/attr-swift_private.swift
7
4704
// RUN: %empty-directory(%t) // RUN: %build-clang-importer-objc-overlays // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -I %S/Inputs/custom-modules -typecheck %s -verify // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -I %S/Inputs/custom-modules -emit-ir %s -D IRGEN | %FileCheck %s // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk-nosource -I %t) -I %S/Inputs/custom-modules -print-module -source-filename="%s" -module-to-print SwiftPrivateAttr > %t.txt // RUN: %FileCheck -check-prefix=GENERATED-NEGATIVE %s < %t.txt // RUN: diff -U3 %S/Inputs/SwiftPrivateAttr.txt %t.txt // Look for identifiers with "Priv" in them that haven't been prefixed. // GENERATED-NEGATIVE-NOT: {{[^A-Za-z0-9_][A-Za-z0-9]*[Pp]riv}} // REQUIRES: objc_interop import SwiftPrivateAttr // Note: The long-term plan is for these to only be available from the Swift // half of a module, or from an overlay. At that point we should test that these // are available in that case and /not/ in the normal import case. // CHECK-LABEL: define{{( protected)?}} swiftcc void @{{.+}}12testProperty public func testProperty(_ foo: Foo) { // CHECK: @"\01L_selector(setPrivValue:)" _ = foo.__privValue foo.__privValue = foo // CHECK: @"\01L_selector(setPrivClassValue:)" _ = Foo.__privClassValue Foo.__privClassValue = foo #if !IRGEN _ = foo.privValue // expected-error {{value of type 'Foo' has no member 'privValue'}} #endif } // CHECK-LABEL: define{{( protected)?}} swiftcc void @{{.+}}11testMethods public func testMethods(_ foo: Foo) { // CHECK: @"\01L_selector(noArgs)" foo.__noArgs() // CHECK: @"\01L_selector(oneArg:)" foo.__oneArg(1) // CHECK: @"\01L_selector(twoArgs:other:)" foo.__twoArgs(1, other: 2) } // CHECK-LABEL: define{{( protected)?}} swiftcc void @{{.+}}16testInitializers public func testInitializers() { // Checked below; look for "CSo3Bar". _ = Bar(__noArgs: ()) _ = Bar(__oneArg: 1) _ = Bar(__twoArgs: 1, other: 2) _ = Bar(__: 1) } // CHECK-LABEL: define{{( protected)?}} swiftcc void @{{.+}}18testFactoryMethods public func testFactoryMethods() { // CHECK: @"\01L_selector(fooWithOneArg:)" _ = Foo(__oneArg: 1) // CHECK: @"\01L_selector(fooWithTwoArgs:other:)" _ = Foo(__twoArgs: 1, other: 2) // CHECK: @"\01L_selector(foo:)" _ = Foo(__: 1) } #if !IRGEN public func testSubscript(_ foo: Foo) { _ = foo[foo] // expected-error {{value of type 'Foo' has no subscripts}} _ = foo[1] // expected-error {{value of type 'Foo' has no subscripts}} } #endif // CHECK-LABEL: define{{( protected)?}} swiftcc void @{{.+}}12testTopLevel public func testTopLevel() { // Checked below; look for "PrivFooSub". let foo = __PrivFooSub() _ = foo as __PrivProto // CHECK: @"\01l_OBJC_PROTOCOL_REFERENCE_$_PrivProto" foo.conforms(to: __PrivProto.self) // CHECK: call void @privTest() __privTest() _ = __PrivS1() #if !IRGEN let _ = PrivFooSub() // expected-error {{cannot find 'PrivFooSub' in scope}} privTest() // expected-error {{cannot find 'privTest' in scope}} PrivS1() // expected-error {{cannot find 'PrivS1' in scope}} #endif } _ = __PrivAnonymousA _ = __E0PrivA _ = __PrivE1A as __PrivE1 _ = NSEnum.__privA _ = NSEnum.B _ = NSOptions.__privA _ = NSOptions.B func makeSureAnyObject(_: AnyObject) {} #if !IRGEN func testUnavailableRefs() { var x: __PrivCFTypeRef // expected-error {{'__PrivCFTypeRef' has been renamed to '__PrivCFType'}} var y: __PrivCFSubRef // expected-error {{'__PrivCFSubRef' has been renamed to '__PrivCFSub'}} } #endif func testCF(_ a: __PrivCFType, b: __PrivCFSub, c: __PrivInt) { makeSureAnyObject(a) makeSureAnyObject(b) #if !IRGEN makeSureAnyObject(c) // expected-error {{argument type '__PrivInt' (aka 'Int32') expected to be an instance of a class or class-constrained type}} #endif } extension __PrivCFType {} extension __PrivCFSub {} _ = 1 as __PrivInt #if !IRGEN func testRawNames() { let _ = Foo.__fooWithOneArg(0) // expected-error {{'__fooWithOneArg' has been replaced by 'init(__oneArg:)'}} let _ = Foo.__foo // expected-error{{'__foo' has been replaced by 'init(__:)'}} } #endif // CHECK-LABEL: define linkonce_odr hidden {{.+}} @"$sSo3BarC8__noArgsABSgyt_tcfcTO" // CHECK: @"\01L_selector(initWithNoArgs)" // CHECK-LABEL: define linkonce_odr hidden {{.+}} @"$sSo3BarC8__oneArgABSgs5Int32V_tcfcTO" // CHECK: @"\01L_selector(initWithOneArg:)" // CHECK-LABEL: define linkonce_odr hidden {{.+}} @"$sSo3BarC9__twoArgs5otherABSgs5Int32V_AGtcfcTO" // CHECK: @"\01L_selector(initWithTwoArgs:other:)" // CHECK-LABEL: define linkonce_odr hidden {{.+}} @"$sSo3BarC2__ABSgs5Int32V_tcfcTO" // CHECK: @"\01L_selector(init:)"
apache-2.0
c5ce301dc9546b719fcf5e10e1db537b
33.335766
183
0.664328
3.23299
false
true
false
false
jopamer/swift
test/Sema/exhaustive_switch.swift
1
33572
// RUN: %target-typecheck-verify-swift -swift-version 5 -enable-resilience // RUN: %target-typecheck-verify-swift -swift-version 4 -enable-resilience -enable-nonfrozen-enum-exhaustivity-diagnostics func foo(a: Int?, b: Int?) -> Int { switch (a, b) { case (.none, _): return 1 case (_, .none): return 2 case (.some(_), .some(_)): return 3 } switch (a, b) { case (.none, _): return 1 case (_, .none): return 2 case (_?, _?): return 3 } switch Optional<(Int?, Int?)>.some((a, b)) { case .none: return 1 case let (_, x?)?: return x case let (x?, _)?: return x case (.none, .none)?: return 0 } } func bar(a: Bool, b: Bool) -> Int { switch (a, b) { case (false, false): return 1 case (true, _): return 2 case (false, true): return 3 } } enum Result<T> { case Ok(T) case Error(Error) func shouldWork<U>(other: Result<U>) -> Int { switch (self, other) { // No warning case (.Ok, .Ok): return 1 case (.Error, .Error): return 2 case (.Error, _): return 3 case (_, .Error): return 4 } } } func overParenthesized() { // SR-7492: Space projection needs to treat extra paren-patterns explicitly. let x: Result<(Result<Int>, String)> = .Ok((.Ok(1), "World")) switch x { case let .Error(e): print(e) case let .Ok((.Error(e), b)): print(e, b) case let .Ok((.Ok(a), b)): // No warning here. print(a, b) } } enum Foo { case A(Int) case B(Int) } func foo() { switch (Foo.A(1), Foo.B(1)) { case (.A(_), .A(_)): () case (.B(_), _): () case (_, .B(_)): () } switch (Foo.A(1), Optional<(Int, Int)>.some((0, 0))) { case (.A(_), _): break case (.B(_), (let q, _)?): print(q) case (.B(_), nil): break } } class C {} enum Bar { case TheCase(C?) } func test(f: Bar) -> Bool { switch f { case .TheCase(_?): return true case .TheCase(nil): return false } } func op(this : Optional<Bool>, other : Optional<Bool>) -> Optional<Bool> { switch (this, other) { // No warning case let (.none, w): return w case let (w, .none): return w case let (.some(e1), .some(e2)): return .some(e1 && e2) } } enum Threepeat { case a, b, c } func test3(x: Threepeat, y: Threepeat) { switch (x, y) { // expected-error {{switch must be exhaustive}} // expected-note@-1 {{add missing case: '(.a, .c)'}} case (.a, .a): () case (.b, _): () case (.c, _): () case (_, .b): () } } enum A { case A(Int) case B(Bool) case C case D } enum B { case A case B } func s(a: A, b: B) { switch (a, b) { case (.A(_), .A): break case (.A(_), .B): break case (.B(_), let b): // expected-warning@-1 {{immutable value 'b' was never used; consider replacing with '_' or removing it}} break case (.C, _), (.D, _): break } } enum Grimble { case A case B case C } enum Gromble { case D case E } func doSomething(foo:Grimble, bar:Gromble) { switch(foo, bar) { // No warning case (.A, .D): break case (.A, .E): break case (.B, _): break case (.C, _): break } } enum E { case A case B } func f(l: E, r: E) { switch (l, r) { case (.A, .A): return case (.A, _): return case (_, .A): return case (.B, .B): return } } enum TestEnum { case A, B } func switchOverEnum(testEnumTuple: (TestEnum, TestEnum)) { switch testEnumTuple { case (_,.B): // Matches (.A, .B) and (.B, .B) break case (.A,_): // Matches (.A, .A) // Would also match (.A, .B) but first case takes precedent break case (.B,.A): // Matches (.B, .A) break } } func tests(a: Int?, b: String?) { switch (a, b) { case let (.some(n), _): print("a: ", n, "?") case (.none, _): print("Nothing", "?") } switch (a, b) { case let (.some(n), .some(s)): print("a: ", n, "b: ", s) case let (.some(n), .none): print("a: ", n, "Nothing") case (.none, _): print("Nothing") } switch (a, b) { case let (.some(n), .some(s)): print("a: ", n, "b: ", s) case let (.some(n), .none): print("a: ", n, "Nothing") case let (.none, .some(s)): print("Nothing", "b: ", s) case (.none, _): print("Nothing", "?") } switch (a, b) { case let (.some(n), .some(s)): print("a: ", n, "b: ", s) case let (.some(n), .none): print("a: ", n, "Nothing") case let (.none, .some(s)): print("Nothing", "b: ", s) case (.none, .none): print("Nothing", "Nothing") } } enum X { case Empty case A(Int) case B(Int) } func f(a: X, b: X) { switch (a, b) { case (_, .Empty): () case (.Empty, _): () case (.A, .A): () case (.B, .B): () case (.A, .B): () case (.B, .A): () } } func f2(a: X, b: X) { switch (a, b) { case (.A, .A): () case (.B, .B): () case (.A, .B): () case (.B, .A): () case (_, .Empty): () case (.Empty, _): () case (.A, .A): () // expected-warning {{case is already handled by previous patterns; consider removing it}} case (.B, .B): () // expected-warning {{case is already handled by previous patterns; consider removing it}} case (.A, .B): () // expected-warning {{case is already handled by previous patterns; consider removing it}} case (.B, .A): () // expected-warning {{case is already handled by previous patterns; consider removing it}} default: () } } enum XX : Int { case A case B case C case D case E } func switcheroo(a: XX, b: XX) -> Int { switch(a, b) { // No warning case (.A, _) : return 1 case (_, .A) : return 2 case (.C, _) : return 3 case (_, .C) : return 4 case (.B, .B) : return 5 case (.B, .D) : return 6 case (.D, .B) : return 7 case (.B, .E) : return 8 case (.E, .B) : return 9 case (.E, _) : return 10 case (_, .E) : return 11 case (.D, .D) : return 12 default: print("never hits this:", a, b) return 13 } } enum PatternCasts { case one(Any) case two case three(String) } func checkPatternCasts() { // Pattern casts with this structure shouldn't warn about duplicate cases. let x: PatternCasts = .one("One") switch x { case .one(let s as String): print(s) case .one: break case .two: break case .three: break } // But should warn here. switch x { case .one(_): print(s) case .one: break // expected-warning {{case is already handled by previous patterns; consider removing it}} case .two: break case .three: break } // And not here switch x { case .one: break case .two: break case .three(let s as String?): print(s as Any) } } enum MyNever {} func ~= (_ : MyNever, _ : MyNever) -> Bool { return true } func myFatalError() -> MyNever { fatalError() } func checkUninhabited() { // Scrutinees of uninhabited type may match any number and kind of patterns // that Sema is willing to accept at will. After all, it's quite a feat to // productively inhabit the type of crashing programs. func test1(x : Never) { switch x {} // No diagnostic. } func test2(x : Never) { switch (x, x) {} // No diagnostic. } func test3(x : MyNever) { switch x { // No diagnostic. case myFatalError(): break case myFatalError(): break case myFatalError(): break } } } enum Runcible { case spoon case hat case fork } func checkDiagnosticMinimality(x: Runcible?) { switch (x!, x!) { // expected-error {{switch must be exhaustive}} // expected-note@-1 {{add missing case: '(.fork, _)'}} // expected-note@-2 {{add missing case: '(.hat, .hat)'}} // expected-note@-3 {{add missing case: '(_, .fork)'}} case (.spoon, .spoon): break case (.spoon, .hat): break case (.hat, .spoon): break } switch (x!, x!) { // expected-error {{switch must be exhaustive}} // expected-note@-1 {{add missing case: '(.fork, _)'}} // expected-note@-2 {{add missing case: '(.hat, .spoon)'}} // expected-note@-3 {{add missing case: '(.spoon, .hat)'}} // expected-note@-4 {{add missing case: '(_, .fork)'}} case (.spoon, .spoon): break case (.hat, .hat): break } } enum LargeSpaceEnum { case case0 case case1 case case2 case case3 case case4 case case5 case case6 case case7 case case8 case case9 case case10 } func notQuiteBigEnough() -> Bool { switch (LargeSpaceEnum.case1, LargeSpaceEnum.case2) { // expected-error {{switch must be exhaustive}} // expected-note@-1 110 {{add missing case:}} case (.case0, .case0): return true case (.case1, .case1): return true case (.case2, .case2): return true case (.case3, .case3): return true case (.case4, .case4): return true case (.case5, .case5): return true case (.case6, .case6): return true case (.case7, .case7): return true case (.case8, .case8): return true case (.case9, .case9): return true case (.case10, .case10): return true } } enum OverlyLargeSpaceEnum { case case0 case case1 case case2 case case3 case case4 case case5 case case6 case case7 case case8 case case9 case case10 case case11 } enum ContainsOverlyLargeEnum { case one(OverlyLargeSpaceEnum) case two(OverlyLargeSpaceEnum) case three(OverlyLargeSpaceEnum, OverlyLargeSpaceEnum) } func quiteBigEnough() -> Bool { switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { // expected-error {{the compiler is unable to check that this switch is exhaustive in reasonable time}} // expected-note@-1 {{do you want to add a default clause?}} case (.case0, .case0): return true case (.case1, .case1): return true case (.case2, .case2): return true case (.case3, .case3): return true case (.case4, .case4): return true case (.case5, .case5): return true case (.case6, .case6): return true case (.case7, .case7): return true case (.case8, .case8): return true case (.case9, .case9): return true case (.case10, .case10): return true case (.case11, .case11): return true } switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { // expected-error {{the compiler is unable to check that this switch is exhaustive in reasonable time}} // expected-note@-1 {{do you want to add a default clause?}} case (.case0, _): return true case (.case1, _): return true case (.case2, _): return true case (.case3, _): return true case (.case4, _): return true case (.case5, _): return true case (.case6, _): return true case (.case7, _): return true case (.case8, _): return true case (.case9, _): return true case (.case10, _): return true } switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { // expected-error {{the compiler is unable to check that this switch is exhaustive in reasonable time}} case (.case0, _): return true case (.case1, _): return true case (.case2, _): return true case (.case3, _): return true case (.case4, _): return true case (.case5, _): return true case (.case6, _): return true case (.case7, _): return true case (.case8, _): return true case (.case9, _): return true case (.case10, _): return true @unknown default: return false // expected-note {{remove '@unknown' to handle remaining values}} {{3-12=}} } // No diagnostic switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { case (.case0, _): return true case (.case1, _): return true case (.case2, _): return true case (.case3, _): return true case (.case4, _): return true case (.case5, _): return true case (.case6, _): return true case (.case7, _): return true case (.case8, _): return true case (.case9, _): return true case (.case10, _): return true case (.case11, _): return true } // No diagnostic switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { case (_, .case0): return true case (_, .case1): return true case (_, .case2): return true case (_, .case3): return true case (_, .case4): return true case (_, .case5): return true case (_, .case6): return true case (_, .case7): return true case (_, .case8): return true case (_, .case9): return true case (_, .case10): return true case (_, .case11): return true } // No diagnostic switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { case (_, _): return true } // No diagnostic switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { case (.case0, .case0): return true case (.case1, .case1): return true case (.case2, .case2): return true case (.case3, .case3): return true case _: return true } // No diagnostic switch ContainsOverlyLargeEnum.one(.case0) { case .one: return true case .two: return true case .three: return true } // Make sure we haven't just stopped emitting diagnostics. switch OverlyLargeSpaceEnum.case1 { // expected-error {{switch must be exhaustive}} expected-note 12 {{add missing case}} expected-note {{handle unknown values}} } } indirect enum InfinitelySized { case one case two case recur(InfinitelySized) case mutualRecur(MutuallyRecursive, InfinitelySized) } indirect enum MutuallyRecursive { case one case two case recur(MutuallyRecursive) case mutualRecur(InfinitelySized, MutuallyRecursive) } func infinitelySized() -> Bool { switch (InfinitelySized.one, InfinitelySized.one) { // expected-error {{switch must be exhaustive}} // expected-note@-1 8 {{add missing case:}} case (.one, .one): return true case (.two, .two): return true } switch (MutuallyRecursive.one, MutuallyRecursive.one) { // expected-error {{switch must be exhaustive}} // expected-note@-1 8 {{add missing case:}} case (.one, .one): return true case (.two, .two): return true } } func diagnoseDuplicateLiterals() { let str = "def" let int = 2 let dbl = 2.5 // No Diagnostics switch str { case "abc": break case "def": break case "ghi": break default: break } switch str { case "abc": break case "def": break // expected-note {{first occurrence of identical literal pattern is here}} case "def": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case "ghi": break default: break } switch str { case "abc", "def": break // expected-note 2 {{first occurrence of identical literal pattern is here}} case "ghi", "jkl": break case "abc", "def": break // expected-warning 2 {{literal value is already handled by previous pattern; consider removing it}} default: break } switch str { case "xyz": break // expected-note {{first occurrence of identical literal pattern is here}} case "ghi": break case "def": break case "abc": break case "xyz": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} default: break } func someStr() -> String { return "sdlkj" } let otherStr = "ifnvbnwe" switch str { case "sdlkj": break case "ghi": break // expected-note {{first occurrence of identical literal pattern is here}} case someStr(): break case "def": break case otherStr: break case "xyz": break // expected-note {{first occurrence of identical literal pattern is here}} case "ifnvbnwe": break case "ghi": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case "xyz": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} default: break } // No Diagnostics switch int { case -2: break case -1: break case 0: break case 1: break case 2: break case 3: break default: break } switch int { case -2: break // expected-note {{first occurrence of identical literal pattern is here}} case -2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 1: break case 2: break // expected-note {{first occurrence of identical literal pattern is here}} case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 3: break default: break } switch int { case -2, -2: break // expected-note {{first occurrence of identical literal pattern is here}} expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 1, 2: break // expected-note 3 {{first occurrence of identical literal pattern is here}} case 2, 3: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 1, 2: break // expected-warning 2 {{literal value is already handled by previous pattern; consider removing it}} case 4, 5: break case 7, 7: break // expected-note {{first occurrence of identical literal pattern is here}} // expected-warning@-1 {{literal value is already handled by previous pattern; consider removing it}} default: break } switch int { case 1: break // expected-note {{first occurrence of identical literal pattern is here}} case 2: break // expected-note 2 {{first occurrence of identical literal pattern is here}} case 3: break case 17: break // expected-note {{first occurrence of identical literal pattern is here}} case 4: break case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 001: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 5: break case 0x11: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 0b10: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} default: break } switch int { case 10: break case 0b10: break // expected-note {{first occurrence of identical literal pattern is here}} case -0b10: break // expected-note {{first occurrence of identical literal pattern is here}} case 3000: break case 0x12: break // expected-note {{first occurrence of identical literal pattern is here}} case 400: break case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case -2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 18: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} default: break } func someInt() -> Int { return 0x1234 } let otherInt = 13254 switch int { case 13254: break case 3000: break case 00000002: break // expected-note {{first occurrence of identical literal pattern is here}} case 0x1234: break case someInt(): break case 400: break case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 18: break case otherInt: break case 230: break default: break } // No Diagnostics switch dbl { case -3.5: break case -2.5: break case -1.5: break case 1.5: break case 2.5: break case 3.5: break default: break } switch dbl { case -3.5: break case -2.5: break // expected-note {{first occurrence of identical literal pattern is here}} case -2.5: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case -1.5: break case 1.5: break case 2.5: break // expected-note {{first occurrence of identical literal pattern is here}} case 2.5: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 3.5: break default: break } switch dbl { case 1.5, 4.5, 7.5, 6.9: break // expected-note 2 {{first occurrence of identical literal pattern is here}} case 3.4, 1.5: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 7.5, 2.3: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} default: break } switch dbl { case 1: break case 1.5: break // expected-note 2 {{first occurrence of identical literal pattern is here}} case 2.5: break case 3.5: break // expected-note {{first occurrence of identical literal pattern is here}} case 5.3132: break case 1.500: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 46.2395: break case 1.5000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 0003.50000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 23452.43: break default: break } func someDouble() -> Double { return 324.4523 } let otherDouble = 458.2345 switch dbl { case 1: break // expected-note {{first occurrence of identical literal pattern is here}} case 1.5: break case 2.5: break case 3.5: break // expected-note {{first occurrence of identical literal pattern is here}} case 5.3132: break case 46.2395: break case someDouble(): break case 0003.50000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case otherDouble: break case 2.50505: break // expected-note {{first occurrence of identical literal pattern is here}} case 23452.43: break case 00001: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} case 123453: break case 2.50505000000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}} default: break } } func checkLiteralTuples() { let str1 = "abc" let str2 = "def" let int1 = 23 let int2 = 7 let dbl1 = 4.23 let dbl2 = 23.45 // No Diagnostics switch (str1, str2) { case ("abc", "def"): break case ("def", "ghi"): break case ("ghi", "def"): break case ("abc", "def"): break // We currently don't catch this default: break } // No Diagnostics switch (int1, int2) { case (94, 23): break case (7, 23): break case (94, 23): break // We currently don't catch this case (23, 7): break default: break } // No Diagnostics switch (dbl1, dbl2) { case (543.21, 123.45): break case (543.21, 123.45): break // We currently don't catch this case (23.45, 4.23): break case (4.23, 23.45): break default: break } } func sr6975() { enum E { case a, b } let e = E.b switch e { case .a as E: // expected-warning {{'as' test is always true}} print("a") case .b: // Valid! print("b") case .a: // expected-warning {{case is already handled by previous patterns; consider removing it}} print("second a") } func foo(_ str: String) -> Int { switch str { // expected-error {{switch must be exhaustive}} // expected-note@-1 {{do you want to add a default clause?}} case let (x as Int) as Any: return x } } _ = foo("wtf") } public enum NonExhaustive { case a, b } public enum NonExhaustivePayload { case a(Int), b(Bool) } @_frozen public enum TemporalProxy { case seconds(Int) case milliseconds(Int) case microseconds(Int) case nanoseconds(Int) @_downgrade_exhaustivity_check case never } // Inlinable code is considered "outside" the module and must include a default // case. @inlinable public func testNonExhaustive(_ value: NonExhaustive, _ payload: NonExhaustivePayload, for interval: TemporalProxy, flag: Bool) { switch value { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{none}} case .a: break } switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{3-3=@unknown default:\n<#fatalError#>()\n}} case .a: break case .b: break } switch value { case .a: break case .b: break default: break // no-warning } switch value { case .a: break case .b: break @unknown case _: break // no-warning } switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} {{none}} case .a: break @unknown case _: break } switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.a'}} {{none}} expected-note {{add missing case: '.b'}} {{none}} @unknown case _: break } switch value { case _: break @unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}} } // Test being part of other spaces. switch value as Optional { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.some(_)'}} case .a?: break case .b?: break case nil: break } switch value as Optional { case .a?: break case .b?: break case nil: break @unknown case _: break } // no-warning switch value as Optional { case _?: break case nil: break } // no-warning switch (value, flag) { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '(_, false)'}} case (.a, _): break case (.b, false): break case (_, true): break } switch (value, flag) { case (.a, _): break case (.b, false): break case (_, true): break @unknown case _: break } // no-warning switch (flag, value) { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '(false, _)'}} case (_, .a): break case (false, .b): break case (true, _): break } switch (flag, value) { case (_, .a): break case (false, .b): break case (true, _): break @unknown case _: break } // no-warning switch (value, value) { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '(_, _)'}} case (.a, _), (_, .a): break case (.b, _), (_, .b): break } switch (value, value) { case (.a, _), (_, .a): break case (.b, _), (_, .b): break @unknown case _: break } // no-warning // Test interaction with @_downgrade_exhaustivity_check. switch (value, interval) { // expected-warning {{switch must be exhaustive}} {{none}} // expected-note@-1 {{add missing case: '(_, .milliseconds(_))'}} // expected-note@-2 {{add missing case: '(_, .microseconds(_))'}} // expected-note@-3 {{add missing case: '(_, .nanoseconds(_))'}} // expected-note@-4 {{add missing case: '(_, .never)'}} case (_, .seconds): break case (.a, _): break case (.b, _): break } switch (value, interval) { // expected-warning {{switch must be exhaustive}} {{none}} // expected-note@-1 {{add missing case: '(_, .seconds(_))'}} // expected-note@-2 {{add missing case: '(_, .milliseconds(_))'}} // expected-note@-3 {{add missing case: '(_, .microseconds(_))'}} // expected-note@-4 {{add missing case: '(_, .nanoseconds(_))'}} case (_, .never): break case (.a, _): break case (.b, _): break } // Test payloaded enums. switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{none}} case .a: break } switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{3-3=@unknown default:\n<#fatalError#>()\n}} case .a: break case .b: break } switch payload { case .a: break case .b: break default: break // no-warning } switch payload { case .a: break case .b: break @unknown case _: break // no-warning } switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}} case .a: break @unknown case _: break } switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}} expected-note {{handle unknown values using "@unknown default"}} {{none}} case .a: break case .b(false): break } switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}} case .a: break case .b(false): break @unknown case _: break } // Test fully-covered switches. switch interval { case .seconds, .milliseconds, .microseconds, .nanoseconds: break case .never: break @unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}} } switch flag { case true: break case false: break @unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}} } switch flag as Optional { case _?: break case nil: break @unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}} } switch (flag, value) { case (true, _): break case (false, _): break @unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}} } } public func testNonExhaustiveWithinModule(_ value: NonExhaustive, _ payload: NonExhaustivePayload, for interval: TemporalProxy, flag: Bool) { switch value { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} case .a: break } switch value { // no-warning case .a: break case .b: break } switch value { case .a: break case .b: break default: break // no-warning } switch value { case .a: break case .b: break @unknown case _: break // no-warning } switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} {{none}} case .a: break @unknown case _: break } switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.a'}} {{none}} expected-note {{add missing case: '.b'}} {{none}} @unknown case _: break } switch value { case _: break @unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}} } // Test being part of other spaces. switch value as Optional { // no-warning case .a?: break case .b?: break case nil: break } switch value as Optional { case _?: break case nil: break } // no-warning switch (value, flag) { // no-warning case (.a, _): break case (.b, false): break case (_, true): break } switch (flag, value) { // no-warning case (_, .a): break case (false, .b): break case (true, _): break } switch (value, value) { // no-warning case (.a, _): break case (.b, _): break case (_, .a): break case (_, .b): break } switch (value, value) { // no-warning case (.a, _): break case (.b, _): break case (_, .a): break case (_, .b): break @unknown case _: break } // Test interaction with @_downgrade_exhaustivity_check. switch (value, interval) { // no-warning case (_, .seconds): break case (.a, _): break case (.b, _): break } switch (value, interval) { // no-warning case (_, .never): break case (.a, _): break case (.b, _): break } // Test payloaded enums. switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}} case .a: break } switch payload { // no-warning case .a: break case .b: break } switch payload { case .a: break case .b: break default: break // no-warning } switch payload { case .a: break case .b: break @unknown case _: break // no-warning } switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}} case .a: break @unknown case _: break } switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}} case .a: break case .b(false): break } switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}} case .a: break case .b(false): break @unknown case _: break } } enum UnavailableCase { case a case b @available(*, unavailable) case oopsThisWasABadIdea } enum UnavailableCaseOSSpecific { case a case b #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) @available(macOS, unavailable) @available(iOS, unavailable) @available(tvOS, unavailable) @available(watchOS, unavailable) case unavailableOnAllTheseApplePlatforms #else @available(*, unavailable) case dummyCaseForOtherPlatforms #endif } enum UnavailableCaseOSIntroduced { case a case b @available(macOS 50, iOS 50, tvOS 50, watchOS 50, *) case notYetIntroduced } func testUnavailableCases(_ x: UnavailableCase, _ y: UnavailableCaseOSSpecific, _ z: UnavailableCaseOSIntroduced) { switch x { case .a: break case .b: break } // no-error switch y { case .a: break case .b: break } // no-error switch z { case .a: break case .b: break case .notYetIntroduced: break } // no-error } // The following test used to behave differently when the uninhabited enum was // defined in the same module as the function (as opposed to using Swift.Never). enum NoError {} extension Result where T == NoError { func testUninhabited() { switch self { case .Error(_): break // No .Ok case possible because of the 'NoError'. } switch self { case .Error(_): break case .Ok(_): break // But it's okay to write one. } } }
apache-2.0
654ed550254137a83bc67cce43702dc0
25.965462
205
0.636215
3.621184
false
false
false
false
dominicpr/PagingMenuController
Pod/Classes/MenuView.swift
1
10030
// // MenuView.swift // PagingMenuController // // Created by Yusuke Kita on 5/9/15. // Copyright (c) 2015 kitasuke. All rights reserved. // import UIKit class MenuView: UIScrollView { internal var menuItemViews = [MenuItemView]() private var options: PagingMenuOptions! private var contentView: UIView! private var underlineView: UIView! private var roundRectView: UIView! private var currentPage: Int = 0 // MARK: - Lifecycle internal init(menuItemTitles: [String], options: PagingMenuOptions) { super.init(frame: CGRectZero) self.options = options setupScrollView() constructContentView() layoutContentView() constructRoundRectViewIfNeeded() constructMenuItemViews(titles: menuItemTitles) layoutMenuItemViews() constructUnderlineViewIfNeeded() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() adjustmentContentInsetIfNeeded() } // MARK: - Public method internal func moveToMenu(page page: Int, animated: Bool) { let duration = animated ? options.animationDuration : 0 currentPage = page focusMenuItem() UIView.animateWithDuration(duration, animations: { [unowned self] () -> Void in self.contentOffset.x = self.targetContentOffsetX() self.animateUnderlineViewIfNeeded() self.animateRoundRectViewIfNeeded() }) } internal func updateMenuItemConstraintsIfNeeded(size size: CGSize) { if case .SegmentedControl = options.menuDisplayMode { for menuItemView in menuItemViews { menuItemView.updateLabelConstraints(size: size) } } contentView.setNeedsLayout() contentView.layoutIfNeeded() self.animateUnderlineViewIfNeeded() self.animateRoundRectViewIfNeeded() } // MARK: - Private method private func setupScrollView() { if case .RoundRect(_, _, _, _) = options.menuItemMode { backgroundColor = UIColor.clearColor() } else { backgroundColor = options.backgroundColor } showsHorizontalScrollIndicator = false showsVerticalScrollIndicator = false bounces = bounces() scrollEnabled = scrollEnabled() scrollsToTop = false translatesAutoresizingMaskIntoConstraints = false } private func constructContentView() { contentView = UIView(frame: CGRectZero) contentView.translatesAutoresizingMaskIntoConstraints = false addSubview(contentView) } private func layoutContentView() { let viewsDictionary = ["contentView": contentView, "scrollView": self] let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[contentView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary) let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[contentView(==scrollView)]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary) NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints) } private func constructMenuItemViews(titles titles: [String]) { for title in titles { let menuItemView = MenuItemView(title: title, options: options) menuItemView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(menuItemView) menuItemViews.append(menuItemView) } } private func layoutMenuItemViews() { for (index, menuItemView) in menuItemViews.enumerate() { let visualFormat: String; var viewsDicrionary = ["menuItemView": menuItemView] if index == 0 { visualFormat = "H:|[menuItemView]" } else { viewsDicrionary["previousMenuItemView"] = menuItemViews[index - 1] if index == menuItemViews.count - 1 { visualFormat = "H:[previousMenuItemView][menuItemView]|" } else { visualFormat = "H:[previousMenuItemView][menuItemView]" } } let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(visualFormat, options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDicrionary) let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[menuItemView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDicrionary) NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints) } } private func constructUnderlineViewIfNeeded() { if case .Underline(let height, let color, let horizontalPadding, let verticalPadding) = options.menuItemMode { let width = menuItemViews.first!.bounds.width - horizontalPadding * 2 underlineView = UIView(frame: CGRectMake(horizontalPadding, options.menuHeight - (height + verticalPadding), width, height)) underlineView.backgroundColor = color contentView.addSubview(underlineView) } } private func constructRoundRectViewIfNeeded() { switch options.menuItemMode { case .RoundRect(let radius, _, let verticalPadding, let selectedColor): let height = options.menuHeight - verticalPadding * 2 roundRectView = UIView(frame: CGRectMake(0, verticalPadding, 0, height)) roundRectView.frame.origin.y = verticalPadding roundRectView.userInteractionEnabled = true roundRectView.layer.cornerRadius = radius roundRectView.backgroundColor = selectedColor contentView.addSubview(roundRectView) default: break } } private func animateUnderlineViewIfNeeded() { switch self.options.menuItemMode { case .Underline(_, _, let horizontalPadding, _): if let underlineView = self.underlineView { let targetFrame = self.menuItemViews[self.currentPage].frame underlineView.frame.origin.x = targetFrame.origin.x + horizontalPadding underlineView.frame.size.width = targetFrame.width - horizontalPadding * 2 } default: break } } private func animateRoundRectViewIfNeeded() { switch self.options.menuItemMode { case .RoundRect(_, let horizontalPadding, _, _): if let roundRectView = self.roundRectView { let targetFrame = self.menuItemViews[self.currentPage].frame roundRectView.frame.origin.x = targetFrame.origin.x + horizontalPadding roundRectView.frame.size.width = targetFrame.width - horizontalPadding * 2 } default: break } } private func bounces() -> Bool { switch options.menuDisplayMode { case .FlexibleItemWidth(_, let scrollingMode): if case .ScrollEnabledAndBouces = scrollingMode { return true } case .FixedItemWidth(_, _, let scrollingMode): if case .ScrollEnabledAndBouces = scrollingMode { return true } case .SegmentedControl: return false } return false } private func scrollEnabled() -> Bool { switch options.menuDisplayMode { case .FlexibleItemWidth(_, let scrollingMode): if case .PagingEnabled = scrollingMode { return false } case .FixedItemWidth(_, _, let scrollingMode): if case .PagingEnabled = scrollingMode { return false } default: return false } return true } private func adjustmentContentInsetIfNeeded() { switch options.menuDisplayMode { case .FlexibleItemWidth(let centerItem, _) where centerItem != true: return case .FixedItemWidth(_, let centerItem, _) where centerItem != true: return case .SegmentedControl: return default: break } let firstMenuView = menuItemViews.first! as MenuItemView let lastMenuView = menuItemViews.last! as MenuItemView var inset = contentInset let halfWidth = frame.width / 2 inset.left = halfWidth - firstMenuView.frame.width / 2 inset.right = halfWidth - lastMenuView.frame.width / 2 contentInset = inset } private func targetContentOffsetX() -> CGFloat { switch options.menuDisplayMode { case .FlexibleItemWidth(let centerItem, _) where centerItem: return centerOfScreenWidth() case .FixedItemWidth(_, let centerItem, _) where centerItem: return centerOfScreenWidth() case .SegmentedControl: return contentOffset.x default: return contentOffsetXForCurrentPage() } } private func centerOfScreenWidth() -> CGFloat { return menuItemViews[currentPage].frame.origin.x + menuItemViews[currentPage].frame.width / 2 - frame.width / 2 } private func contentOffsetXForCurrentPage() -> CGFloat { if menuItemViews.count == options.minumumSupportedViewCount { return 0.0 } let ratio = CGFloat(currentPage) / CGFloat(menuItemViews.count - 1) return (contentSize.width - frame.width) * ratio } private func focusMenuItem() { for (index, menuItemView) in menuItemViews.enumerate() { menuItemView.focusLabel(index == currentPage) } setNeedsLayout() layoutIfNeeded() } }
mit
79487a4fc782ba094cc1e1180bbf326e
36.565543
198
0.630708
5.945465
false
false
false
false
IndisputableLabs/Swifthereum
Swifthereum/Classes/Geth/KeyStore.swift
1
8640
// // KeyStore.swift // GethTest // // Created by Ronald Mannak on 7/21/17. // Copyright © 2017 Indisputable. All rights reserved. // import Foundation import Geth /** Interface for Ethereum account management, stored on disk in an encrypted keystore. For more information, see the [Ethereum accounts documentation](https://godoc.org/github.com/ethereum/go-ethereum/accounts) and the [Web3 Secret Storage file format](https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition) */ open class KeyStore { public enum EncryptionN { case Standard case Light case Custom(CLong) var rawValue: CLong { switch self { case .Standard: return 262144 // = GethStandardScryptN case .Light: return 4096 // = GethLightScryptN case .Custom(let value): return value } } } /** */ public enum EncryptionP { case Standard case Light case Custom(CLong) var rawValue: CLong { switch self { case .Standard: return 1 // = GethStandardScryptP case .Light: return 6 // = GethLightScryptP case .Custom(let value): return value } } } internal var _gethKeyStore: GethKeyStore /** the accounts stored in the current encrypted keystore. Returns nil in case of an error or */ open var accounts: [Account]? { var accounts = [Account]() guard let gethAccounts = _gethKeyStore.getAccounts(), gethAccounts.size() > 0 else { return nil } print("number of accounts: \(gethAccounts.size())") for index in 0 ..< gethAccounts.size() { if let account = try? gethAccounts.get(index) { accounts.append(Account(account: account)) } } return accounts } internal let path: String /** Public initializer for KeyStore. - parameters: - path: Path where the encrypted keystores are stored or will be stored. If path is nil, a "keystore" directory will be created in the app's default document directory. - encryptionN: Level of encryption. For mobile apps, the .Light option is the default. - encryptionP: Level of encryption. For mobile apps, the .Light option is the default. */ public init?(path: String? = nil, encryptionN: EncryptionN = .Light, encryptionP: EncryptionP = .Light) { self.path = path ?? NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "/keystore" guard let keyStore = GethNewKeyStore(self.path, encryptionN.rawValue, encryptionP.rawValue) else { return nil } _gethKeyStore = keyStore } } /* ======= * Address * ======= */ public extension KeyStore { /** - bug: Method doesn't return Bool - throws: Error generated by Geth */ public func lock(address: Address) throws { //} -> Bool { try _gethKeyStore.lock(address._gethAddress) } } /* ======= * Account * ======= */ public extension KeyStore { /** Create a new account with the specified encryption passphrase in a new encrypted file in the KeyStore's `self.path` directory. - parameters: - passphrase: user provided passphrase for the account. - returns: The newly created account - throws: Error generated by Geth */ public func newAccountWith(passphrase: String) throws -> Account { let account = try _gethKeyStore.newAccount(passphrase) return Account(account: account) } /** Deletes account keyfile from the local keystore - bug: Method does not return a Bool - returns: nothing (bug) */ public func delete(account: Account, passphrase: String) throws { // }-> Bool { try _gethKeyStore.delete(account._gethAccount, passphrase: passphrase) // return ... } /** - bug: Method does not return a Bool */ public func timedUnlock(account: Account, passphrase: String, timeout: TimeInterval) throws { //} -> Bool { try _gethKeyStore.timedUnlock(account._gethAccount, passphrase: passphrase, timeout: Int64(timeout)) } /** - bug: Method does not return a Bool */ public func ulock(account: Account, passphrase: String) throws { //}-> Bool { try _gethKeyStore.unlock(account._gethAccount, passphrase: passphrase) } /** Update the passphrase on the account created above inside the local keystore. - bug: Method does not return a Bool */ public func update(account: Account, passphrase: String, newPassphrase: String) throws { //}-> Bool { try _gethKeyStore.update(account._gethAccount, passphrase: passphrase, newPassphrase: newPassphrase) } } /* ======= * Signing * ======= */ extension KeyStore { /** Signs passphrase with hash parameters: - passphrase: Passphrase to be hashed - account: Account - hash: Hash to sign passphrase with - returns: Signed passprhase as Data - throws: Error generated by Geth */ open func sign(passphrase: String, for account: Account, hash: Data) throws -> Data { return try _gethKeyStore.signHashPassphrase(account._gethAccount, passphrase: passphrase, hash: hash) } /** Signs a transaction - parameters: - transaction: Transaction - account: Account - chainID: ChainID - returns: New signed transaction - throws: Error generated by Geth */ open func sign(transaction: Transaction, for account: Account, with chainID: ChainID) throws -> Transaction { return try Transaction(transaction: _gethKeyStore.signTx(account._gethAccount, tx: transaction._gethTransaction, chainID: GethBigInt(chainID.rawValue))) } /** Signs a transaction passphrase - throws: Error generated by Geth */ open func sign(transactionPassphrase: String, for transaction: Transaction, in account: Account, chainID: ChainID) throws -> Transaction { return try Transaction(transaction: _gethKeyStore.signTxPassphrase(account._gethAccount, passphrase: transactionPassphrase, tx: transaction._gethTransaction, chainID: GethBigInt(chainID.rawValue))) } open func sign(hash: Data, for address: Address) throws -> Data { return try _gethKeyStore.signHash(address._gethAddress, hash: hash) } } /* === * Key * === */ extension KeyStore { /** Export the newly created account with a different passphrase. The returned data from this method invocation is a JSON encoded, encrypted key-file. - throws: Error generated by Geth */ open func export(newAccount: Account, passphrase: String, newPassphrase: String) throws -> Data { return try _gethKeyStore.exportKey(newAccount._gethAccount, passphrase: passphrase, newPassphrase: newPassphrase) } /** - throws: Error generated by Geth */ open func importECDSAKey(_ key: Data, passphrase: String) throws -> Account { return try Account(account: _gethKeyStore.importECDSAKey(key, passphrase: passphrase)) } /** Imports an account from a JSON encoded encrypted keyfile with a new passphrase - throws: Error generated by Geth */ open func importKey(_ keyJSON: Data, passphrase: String, newPassphrase: String) throws -> Account { return try Account(account: _gethKeyStore.importKey(keyJSON, passphrase: passphrase, newPassphrase: newPassphrase)) } open func imporPreSaleKey(_ keyJSON: Data, passphrase: String) throws -> Account { return try Account(account: _gethKeyStore.importPreSaleKey(keyJSON, passphrase: passphrase)) } } /* ======================= * CustomStringConvertible * ======================= */ extension KeyStore: CustomStringConvertible { open var description: String { return self.path + " : \(self.accounts?.count ?? 0) accounts" } } /* ========= * Equatable * ========= */ extension KeyStore: Equatable { open static func ==(lhs: KeyStore, rhs: KeyStore) -> Bool { return lhs.path == rhs.path } open func has(address: Address) -> Bool { return _gethKeyStore.hasAddress(address._gethAddress) } open static func ==(lhs: KeyStore, rhs: Address) -> Bool { return lhs.has(address: rhs) } }
mit
35db2ef122b374827c3ee4f762323548
32.614786
205
0.627966
4.471532
false
false
false
false
sjsoad/SKUtils
SKUtils/Flows/Examples/Router/ExamplesRouter.swift
1
1892
// // ExamplesRouter.swift // SKUtils // // Created by Sergey on 04.09.2018. // Copyright © 2018 Sergey Kostyan. All rights reserved. // import UIKit import SKCustomNavigation protocol ExamplesRoutable { func showExample(at indexPath: IndexPath) } class ExamplesRouter: ExamplesRoutable { private weak var viewController: UIViewController? private var examples: [[BuilderProvidable]] private var customModalTransition: TransitioningDelegate = { return DefaultTransitioningDelegate(animatedTransitioning: Page(transitionDirection: .fromTop)) }() init(with viewController: UIViewController, _ examples: [[BuilderProvidable]]) { self.viewController = viewController self.examples = examples } func showExample(at indexPath: IndexPath) { guard let example = example(at: indexPath) else { return } let nextViewController = example.builder.build() if indexPath.section == 0 { push(nextViewController) } else { present(nextViewController) } } // MARK: - Private - private func example(at indexPath: IndexPath) -> BuilderProvidable? { guard examples.indices.contains(indexPath.section) else { return nil } let examplesSection = examples[indexPath.section] guard examplesSection.indices.contains(indexPath.row) else { return nil } return examplesSection[indexPath.row] } private func push(_ nextViewController: UIViewController) { viewController?.navigationController?.pushViewController(nextViewController, animated: true) } private func present(_ nextViewController: UIViewController) { nextViewController.transitioningDelegate = customModalTransition viewController?.present(nextViewController, animated: true, completion: nil) } }
mit
0f597f81ecc8af3ebcc8a1515b74f384
31.050847
103
0.691169
5.166667
false
false
false
false
justinhester/hacking-with-swift
src/Project12/Project12/ViewController.swift
1
4949
// // ViewController.swift // Project12 // // Created by Justin Lawrence Hester on 1/25/16. // Copyright © 2016 Justin Lawrence Hester. All rights reserved. // import UIKit class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var collectionView: UICollectionView! var people = [Person]() override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = UIBarButtonItem( barButtonSystemItem: .Add, target: self, action: "addNewPerson" ) let defaults = NSUserDefaults.standardUserDefaults() if let savedPeople = defaults.objectForKey("people") as? NSData { people = NSKeyedUnarchiver.unarchiveObjectWithData(savedPeople) as! [Person] } } func addNewPerson() { let picker = UIImagePickerController() picker.allowsEditing = true picker.delegate = self presentViewController(picker, animated: true, completion: nil) } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return people.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier( "Person", forIndexPath: indexPath ) as! PersonCell let person = people[indexPath.item] cell.name.text = person.name let path = getDocumentsDirectory().stringByAppendingPathComponent(person.image) cell.imageView.image = UIImage(contentsOfFile: path) cell.imageView.layer.borderColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3).CGColor cell.imageView.layer.borderWidth = 2 cell.imageView.layer.cornerRadius = 3 cell.layer.cornerRadius = 7 return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let person = people[indexPath.item] /* DEBUG */ let i = indexPath.item.description self.title = "clicked \(i)" let ac = UIAlertController(title: "Rename person", message: nil, preferredStyle: .Alert) ac.addTextFieldWithConfigurationHandler(nil) ac.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) ac.addAction(UIAlertAction(title: "OK", style: .Default) { [unowned self, ac] _ in let newName = ac.textFields![0] person.name = newName.text! self.collectionView.reloadData() self.save() }) presentViewController(ac, animated: true, completion: nil) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { var newImage: UIImage /* Get selected image from info dictionary. */ if let possibleImage = info["UIImagePickerControllerEditedImage"] as? UIImage { newImage = possibleImage } else if let possibleImage = info["UIImagePickerControllerOriginalImage"] as? UIImage { newImage = possibleImage } else { return } /* Create a uuid for the file name and get a String to the user's Document directory. */ let imageName = NSUUID().UUIDString let imagePath = getDocumentsDirectory().stringByAppendingPathComponent(imageName) /* Convert the image into a NSData type and write it to disk. */ if let jpegData = UIImageJPEGRepresentation(newImage, 80) { jpegData.writeToFile(imagePath, atomically: true) } let person = Person(name: "Unknown", image: imageName) people.append(person) collectionView.reloadData() dismissViewControllerAnimated(true, completion: nil) self.save() } func getDocumentsDirectory() -> NSString { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let documentsDirectory = paths[0] return documentsDirectory } func save() { let savedData = NSKeyedArchiver.archivedDataWithRootObject(people) let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(savedData, forKey: "people") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-3.0
c6947fe8fc8fdb747af457d314eebae6
34.342857
159
0.650364
5.7669
false
false
false
false
andreyvit/ExpressiveFoundation.swift
Source/Strings.swift
1
1963
import Foundation public extension String { public mutating func removePrefixInPlace(prefix: String) -> Bool { if prefix.isEmpty { return false } if hasPrefix(prefix) { guard let range = rangeOfString(prefix, options: []) else { fatalError() } self.removeRange(startIndex ..< range.startIndex) return true } else { return false } } public mutating func removeSuffixInPlace(suffix: String) -> Bool { if suffix.isEmpty { return false } if hasSuffix(suffix) { guard let range = rangeOfString(suffix, options: [.BackwardsSearch]) else { fatalError() } self.removeRange(range.startIndex ..< endIndex) return true } else { return false } } public func removePrefix(suffix: String) -> (String, Bool) { var copy = self let found = copy.removePrefixInPlace(suffix) return (copy, found) } public func removeSuffix(suffix: String) -> (String, Bool) { var copy = self let found = copy.removeSuffixInPlace(suffix) return (copy, found) } public func removePrefixOrNil(prefix: String) -> String? { var copy = self if copy.removePrefixInPlace(prefix) { return copy } else { return nil } } public mutating func replaceSuffixInPlace(oldSuffix: String, _ newSuffix: String) -> Bool { if removeSuffixInPlace(oldSuffix) { appendContentsOf(newSuffix) return true } else { return false } } public func replaceSuffix(oldSuffix: String, _ newSuffix: String) -> (String, Bool) { var copy = self let found = copy.replaceSuffixInPlace(oldSuffix, newSuffix) return (copy, found) } }
mit
a2dc188ea56233af56bf0cbb593528b3
26.647887
95
0.556801
4.870968
false
false
false
false
luckymarmot/ThemeKit
Sources/Theme.swift
1
7994
// // Theme.swift // ThemeKit // // Created by Nuno Grilo on 06/09/16. // Copyright © 2016 Paw & Nuno Grilo. All rights reserved. // import Foundation /** Theme protocol: the base of all themes. *ThemeKit* makes available, without any further coding: - a `LightTheme` (the default macOS theme) - a `DarkTheme` (the dark macOS theme, using `NSAppearanceNameVibrantDark`) - a `SystemTheme` (which dynamically resolve to either `LightTheme` or `DarkTheme depending on the macOS preference at **System Preferences > General > Appearance**) You can choose wheter or not to use these, and you can also implement your custom themes by: - implementing native `Theme` classes conforming to this protocol and `NSObject` - provide user themes (`UserTheme`) with `.theme` files Please check the provided *Demo.app* project for sample implementations of both. */ @objc(TKTheme) public protocol Theme: NSObjectProtocol { // MARK: Required Properties /// Unique theme identifier. var identifier: String { get } /// Theme display name. var displayName: String { get } /// Theme short display name. var shortDisplayName: String { get } /// Is this a dark theme? var isDarkTheme: Bool { get } // MARK: Optional Methods/Properties /// Optional: foreground color to be used on when a foreground color is not provided /// by the theme. @objc optional var fallbackForegroundColor: NSColor? { get } /// Optional: background color to be used on when a background color (a color which /// contains `Background` in its name) is not provided by the theme. @objc optional var fallbackBackgroundColor: NSColor? { get } /// Optional: gradient to be used on when a gradient is not provided by the theme. @objc optional var fallbackGradient: NSGradient? { get } /// Optional: image to be used on when an image is not provided by the theme. @objc optional var fallbackImage: NSImage? { get } } /// Theme protocol extension. /// /// These functions are available for all `Theme`s. public extension Theme { // MARK: Convenient Methods/Properties (Swift only) /// Is this a light theme? /// /// This method is not available from Objective-C. Alternative code: /// /// ```objc /// !aTheme.isDarkTheme /// ``` var isLightTheme: Bool { return !isDarkTheme } /// Is this the system theme? If true, theme automatically resolve to /// `ThemeManager.lightTheme` or `ThemeManager.darkTheme`, accordingly to /// **System Preferences > General > Appearance**. /// /// This method is not available from Objective-C. Alternative code: /// /// ```objc /// [aTheme.identifier isEqualToString:TKSystemTheme.identifier] /// ``` var isSystemTheme: Bool { return identifier == SystemTheme.identifier } /// Is this a user theme? /// /// This method is not available from Objective-C. Alternative code: /// /// ```objc /// [aTheme isKindOfClass:[TKUserTheme class]] /// ``` var isUserTheme: Bool { return self is UserTheme } /// Apply theme (make it the current one). /// /// This method is not available from Objective-C. Alternative code: /// /// ```objc /// [[TKThemeManager sharedManager] setTheme:aTheme] /// ``` func apply() { ThemeManager.shared.theme = self } /// Theme asset for the specified key. Supported assets are `NSColor`, `NSGradient`, `NSImage` and `NSString`. /// /// This function is overriden by `UserTheme`. /// /// This method is not available from Objective-C. /// /// - parameter key: A color name, gradient name, image name or a theme string /// /// - returns: The theme value for the specified key. func themeAsset(_ key: String) -> Any? { // Because `Theme` is an @objc protocol, we cannot define this method on // the protocol and a provide a default implementation on this extension, // plus another on `UserTheme`. This is a workaround to accomplish it. if let userTheme = self as? UserTheme { return userTheme.themeAsset(key) } let selector = NSSelectorFromString(key) if let theme = self as? NSObject, theme.responds(to: selector) { return theme.perform(selector).takeUnretainedValue() } return nil } /// Checks if a theme asset is provided for the given key. /// /// This function is overriden by `UserTheme`. /// /// This method is not available from Objective-C. /// /// - parameter key: A color name, gradient name, image name or a theme string /// /// - returns: `true` if theme provides an asset for the given key; `false` otherwise. func hasThemeAsset(_ key: String) -> Bool { return themeAsset(key) != nil } /// Default foreground color to be used on fallback situations when /// no `fallbackForegroundColor` was specified by the theme. /// /// This method is not available from Objective-C. Alternative code: /// /// ```objc /// aTheme.isDarkTheme ? NSColor.whiteColor : NSColor.blackColor /// ``` var defaultFallbackForegroundColor: NSColor { return isLightTheme ? NSColor.black : NSColor.white } /// Default background color to be used on fallback situations when /// no `fallbackBackgroundColor` was specified by the theme (background color /// is a color method that contains `Background` in its name). /// /// This method is not available from Objective-C. Alternative code: /// /// ```objc /// aTheme.isDarkTheme ? NSColor.blackColor : NSColor.whiteColor /// ``` var defaultFallbackBackgroundColor: NSColor { return isLightTheme ? NSColor.white : NSColor.black } /// Default gradient to be used on fallback situations when /// no `fallbackForegroundColor` was specified by the theme. /// /// This method is not available from Objective-C. Alternative code: /// /// ```objc /// [[NSGradient alloc] initWithStartingColor:(aTheme.isDarkTheme ? NSColor.blackColor : NSColor.whiteColor) endingColor:(aTheme.isDarkTheme ? NSColor.whiteColor : NSColor.blackColor)] /// ``` var defaultFallbackGradient: NSGradient? { return NSGradient(starting: defaultFallbackBackgroundColor, ending: defaultFallbackBackgroundColor) } /// Default image to be used on fallback situations when /// no image was specified by the theme. /// /// This method is not available from Objective-C. Alternative code: /// /// ```objc /// [[NSImage alloc] initWithSize:NSZeroSize] /// ``` var defaultFallbackImage: NSImage { return NSImage(size: NSSize.zero) } /// Effective theme, which can be different from itself if it represents the /// system theme, respecting **System Preferences > General > Appearance** /// (in that case it will be either `ThemeManager.lightTheme` or `ThemeManager.darkTheme`). /// /// This method is not available from Objective-C. Alternative code: /// /// ```objc /// [aTheme.identifier isEqualToString:TKSystemTheme.identifier] ? (aTheme.isDarkTheme ? TKThemeManager.darkTheme : TKThemeManager.lightTheme) : aTheme; /// ``` var effectiveTheme: Theme { if isSystemTheme { return isDarkTheme ? ThemeManager.darkTheme : ThemeManager.lightTheme } else { return self } } /// Theme description. func themeDescription(_ theme: Theme) -> String { return "\"\(displayName)\" [\(identifier)]\(isDarkTheme ? " (Dark)" : "")" } } /// Check if themes are the same. func == (lhs: Theme, rhs: Theme) -> Bool { return lhs.identifier == rhs.identifier } /// Check if themes are different. func != (lhs: Theme, rhs: Theme) -> Bool { return lhs.identifier != rhs.identifier }
mit
4685778bb7e308aaad53aab139afd433
33.012766
188
0.650444
4.538898
false
false
false
false
lyngbym/SwiftGraph
SwiftGraphLib/SwiftGraphLib/SwiftPriorityQueue.swift
4
6730
// // SwiftPriorityQueue.swift // SwiftPriorityQueue // // Copyright (c) 2015 David Kopec // // 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. // This code was inspired by Section 2.4 of Algorithms by Sedgewick & Wayne, 4th Edition #if !swift(>=3.0) typealias IteratorProtocol = GeneratorType typealias Sequence = SequenceType typealias Collection = CollectionType #endif /// A PriorityQueue takes objects to be pushed of any type that implements Comparable. /// It will pop the objects in the order that they would be sorted. A pop() or a push() /// can be accomplished in O(lg n) time. It can be specified whether the objects should /// be popped in ascending or descending order (Max Priority Queue or Min Priority Queue) /// at the time of initialization. public struct PriorityQueue<T: Comparable> { fileprivate var heap = [T]() private let ordered: (T, T) -> Bool public init(ascending: Bool = false, startingValues: [T] = []) { if ascending { ordered = { $0 > $1 } } else { ordered = { $0 < $1 } } // Based on "Heap construction" from Sedgewick p 323 heap = startingValues var i = heap.count/2 - 1 while i >= 0 { sink(i) i -= 1 } } /// How many elements the Priority Queue stores public var count: Int { return heap.count } /// true if and only if the Priority Queue is empty public var isEmpty: Bool { return heap.isEmpty } /// Add a new element onto the Priority Queue. O(lg n) /// /// - parameter element: The element to be inserted into the Priority Queue. public mutating func push(_ element: T) { heap.append(element) swim(heap.count - 1) } /// Remove and return the element with the highest priority (or lowest if ascending). O(lg n) /// /// - returns: The element with the highest priority in the Priority Queue, or nil if the PriorityQueue is empty. public mutating func pop() -> T? { if heap.isEmpty { return nil } if heap.count == 1 { return heap.removeFirst() } // added for Swift 2 compatibility // so as not to call swap() with two instances of the same location swap(&heap[0], &heap[heap.count - 1]) let temp = heap.removeLast() sink(0) return temp } /// Removes the first occurence of a particular item. Finds it by value comparison using ==. O(n) /// Silently exits if no occurrence found. /// /// - parameter item: The item to remove the first occurrence of. public mutating func remove(_ item: T) { if let index = heap.index(of: item) { swap(&heap[index], &heap[heap.count - 1]) heap.removeLast() swim(index) sink(index) } } /// Removes all occurences of a particular item. Finds it by value comparison using ==. O(n) /// Silently exits if no occurrence found. /// /// - parameter item: The item to remove. public mutating func removeAll(_ item: T) { var lastCount = heap.count remove(item) while (heap.count < lastCount) { lastCount = heap.count remove(item) } } /// Get a look at the current highest priority item, without removing it. O(1) /// /// - returns: The element with the highest priority in the PriorityQueue, or nil if the PriorityQueue is empty. public func peek() -> T? { return heap.first } /// Eliminate all of the elements from the Priority Queue. public mutating func clear() { #if swift(>=3.0) heap.removeAll(keepingCapacity: false) #else heap.removeAll(keepCapacity: false) #endif } // Based on example from Sedgewick p 316 private mutating func sink(_ index: Int) { var index = index while 2 * index + 1 < heap.count { var j = 2 * index + 1 if j < (heap.count - 1) && ordered(heap[j], heap[j + 1]) { j += 1 } if !ordered(heap[index], heap[j]) { break } swap(&heap[index], &heap[j]) index = j } } // Based on example from Sedgewick p 316 private mutating func swim(_ index: Int) { var index = index while index > 0 && ordered(heap[(index - 1) / 2], heap[index]) { swap(&heap[(index - 1) / 2], &heap[index]) index = (index - 1) / 2 } } } // MARK: - GeneratorType extension PriorityQueue: IteratorProtocol { public typealias Element = T mutating public func next() -> Element? { return pop() } } // MARK: - SequenceType extension PriorityQueue: Sequence { public typealias Iterator = PriorityQueue public func makeIterator() -> Iterator { return self } } // MARK: - CollectionType extension PriorityQueue: Collection { public typealias Index = Int public var startIndex: Int { return heap.startIndex } public var endIndex: Int { return heap.endIndex } public subscript(i: Int) -> T { return heap[i] } #if swift(>=3.0) public func index(after i: PriorityQueue.Index) -> PriorityQueue.Index { return heap.index(after: i) } #endif } // MARK: - CustomStringConvertible, CustomDebugStringConvertible extension PriorityQueue: CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return heap.description } public var debugDescription: String { return heap.debugDescription } }
apache-2.0
af0e007c985f82105a18e1de02fb8635
33.870466
117
0.62318
4.462865
false
false
false
false
robertherdzik/RHPlaygroundFreestyle
Hypnotize/RHHypnotize.playground/Contents.swift
1
1884
import UIKit import PlaygroundSupport let sideLenght = 200 let viewFrame = CGRect(x: 0, y: 0, width: sideLenght, height: sideLenght) let baseView = UIView(frame: viewFrame) baseView.backgroundColor = UIColor.gray // Creating our circle path let circlePath = UIBezierPath(arcCenter: baseView.center, radius: viewFrame.size.width/2, startAngle: CGFloat(0), endAngle: CGFloat.pi * 2, clockwise: true) let lineWidth = CGFloat(3) let shapeLayer = CAShapeLayer() shapeLayer.frame = viewFrame shapeLayer.path = circlePath.cgPath shapeLayer.fillColor = UIColor.clear.cgColor shapeLayer.strokeColor = UIColor.cyan.cgColor shapeLayer.lineWidth = lineWidth // Now the magic 🎩 begins, we create our Replicator 🎉 which will multiply our shapeLayer. let replicator = CAReplicatorLayer() replicator.frame = viewFrame replicator.instanceDelay = 0.05 replicator.instanceCount = 30 replicator.instanceTransform = CATransform3DMakeScale(1, 1, 1) replicator.addSublayer(shapeLayer) baseView.layer.addSublayer(replicator) let fade = CABasicAnimation(keyPath: "opacity") fade.fromValue = 0.05 fade.toValue = 0.3 fade.duration = 1.5 fade.beginTime = CACurrentMediaTime() fade.repeatCount = .infinity fade.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut) shapeLayer.add(fade, forKey: "shapeLayerOpacity") let scale = CABasicAnimation(keyPath: "transform") scale.fromValue = NSValue(caTransform3D: CATransform3DMakeScale(0, 0, 1)) scale.toValue = NSValue(caTransform3D: CATransform3DMakeScale(1, 1, 1)) scale.duration = 1.5 scale.repeatCount = .infinity scale.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) shapeLayer.add(scale, forKey: "shapeLayerScale") PlaygroundPage.current.liveView = baseView
mit
26dd10bfc87fca9292fb09f3bae92d5e
31.947368
91
0.749201
4.418824
false
false
false
false
duliodenis/pocket-critter-go
Pokecrit Go/Pokecrit Go/Controllers/BattleViewController.swift
1
757
// // BattleViewController.swift // Pokecrit Go // // Created by Dulio Denis on 5/18/17. // Copyright © 2017 ddApps. All rights reserved. // import UIKit import SpriteKit class BattleViewController: UIViewController { var pokecrit: Pokecrit! override func viewDidLoad() { super.viewDidLoad() let scene = BattleScene(size: CGSize(width: view.frame.size.width, height: view.frame.size.height)) scene.scaleMode = .aspectFill scene.pokecrit = pokecrit self.view = SKView() let skView = self.view as! SKView skView.showsFPS = false skView.showsNodeCount = false skView.ignoresSiblingOrder = false skView.presentScene(scene) } }
mit
8272d4e18007cd1ab7d1e2317bd05c4f
21.909091
107
0.634921
4.176796
false
false
false
false
manavgabhawala/swift
test/SILGen/functions.swift
1
22694
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -emit-silgen %s | %FileCheck %s import Swift // just for Optional func markUsed<T>(_ t: T) {} typealias Int = Builtin.Int64 typealias Int64 = Builtin.Int64 typealias Bool = Builtin.Int1 var zero = getInt() func getInt() -> Int { return zero } func standalone_function(_ x: Int, _ y: Int) -> Int { return x } func higher_order_function(_ f: (_ x: Int, _ y: Int) -> Int, _ x: Int, _ y: Int) -> Int { return f(x, y) } func higher_order_function2(_ f: (Int, Int) -> Int, _ x: Int, _ y: Int) -> Int { return f(x, y) } struct SomeStruct { // -- Constructors and methods are uncurried in 'self' // -- Instance methods use 'method' cc init(x:Int, y:Int) {} mutating func method(_ x: Int) {} static func static_method(_ x: Int) {} func generic_method<T>(_ x: T) {} } class SomeClass { // -- Constructors and methods are uncurried in 'self' // -- Instance methods use 'method' cc // CHECK-LABEL: sil hidden @_T09functions9SomeClassC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (Builtin.Int64, Builtin.Int64, @owned SomeClass) -> @owned SomeClass // CHECK: bb0(%0 : $Builtin.Int64, %1 : $Builtin.Int64, %2 : $SomeClass): // CHECK-LABEL: sil hidden @_T09functions9SomeClassC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (Builtin.Int64, Builtin.Int64, @thick SomeClass.Type) -> @owned SomeClass // CHECK: bb0(%0 : $Builtin.Int64, %1 : $Builtin.Int64, %2 : $@thick SomeClass.Type): init(x:Int, y:Int) {} // CHECK-LABEL: sil hidden @_T09functions9SomeClassC6method{{[_0-9a-zA-Z]*}}F : $@convention(method) (Builtin.Int64, @guaranteed SomeClass) -> () // CHECK: bb0(%0 : $Builtin.Int64, %1 : $SomeClass): func method(_ x: Int) {} // CHECK-LABEL: sil hidden @_T09functions9SomeClassC13static_method{{[_0-9a-zA-Z]*}}FZ : $@convention(method) (Builtin.Int64, @thick SomeClass.Type) -> () // CHECK: bb0(%0 : $Builtin.Int64, %1 : $@thick SomeClass.Type): class func static_method(_ x: Int) {} var someProperty: Int { get { return zero } set {} } subscript(x:Int, y:Int) -> Int { get { return zero } set {} } func generic<T>(_ x: T) -> T { return x } } func SomeClassWithBenefits() -> SomeClass.Type { return SomeClass.self } protocol SomeProtocol { func method(_ x: Int) static func static_method(_ x: Int) } struct ConformsToSomeProtocol : SomeProtocol { func method(_ x: Int) { } static func static_method(_ x: Int) { } } class SomeGeneric<T> { init() { } func method(_ x: T) -> T { return x } func generic<U>(_ x: U) -> U { return x } } // CHECK-LABEL: sil hidden @_T09functions5calls{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int64, Builtin.Int64, Builtin.Int64) -> () func calls(_ i:Int, j:Int, k:Int) { var i = i var j = j var k = k // CHECK: bb0(%0 : $Builtin.Int64, %1 : $Builtin.Int64, %2 : $Builtin.Int64): // CHECK: [[IBOX:%[0-9]+]] = alloc_box ${ var Builtin.Int64 } // CHECK: [[IADDR:%.*]] = project_box [[IBOX]] // CHECK: [[JBOX:%[0-9]+]] = alloc_box ${ var Builtin.Int64 } // CHECK: [[JADDR:%.*]] = project_box [[JBOX]] // CHECK: [[KBOX:%[0-9]+]] = alloc_box ${ var Builtin.Int64 } // CHECK: [[KADDR:%.*]] = project_box [[KBOX]] // CHECK: [[FUNC:%[0-9]+]] = function_ref @_T09functions19standalone_function{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64 // CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]] // CHECK: [[J:%[0-9]+]] = load [trivial] [[JADDR]] // CHECK: apply [[FUNC]]([[I]], [[J]]) standalone_function(i, j) // -- Curry 'self' onto struct method argument lists. // CHECK: [[ST_ADDR:%.*]] = alloc_box ${ var SomeStruct } // CHECK: [[CTOR:%.*]] = function_ref @_T09functions10SomeStructV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (Builtin.Int64, Builtin.Int64, @thin SomeStruct.Type) -> SomeStruct // CHECK: [[METATYPE:%.*]] = metatype $@thin SomeStruct.Type // CHECK: [[I:%.*]] = load [trivial] [[IADDR]] // CHECK: [[J:%.*]] = load [trivial] [[JADDR]] // CHECK: apply [[CTOR]]([[I]], [[J]], [[METATYPE]]) : $@convention(method) (Builtin.Int64, Builtin.Int64, @thin SomeStruct.Type) -> SomeStruct var st = SomeStruct(x: i, y: j) // -- Use of unapplied struct methods as values. // CHECK: [[THUNK:%.*]] = function_ref @_T09functions10SomeStructV6method{{[_0-9a-zA-Z]*}}F // CHECK: [[THUNK_THICK:%.*]] = thin_to_thick_function [[THUNK]] var stm1 = SomeStruct.method stm1(&st)(i) // -- Curry 'self' onto method argument lists dispatched using class_method. // CHECK: [[CBOX:%[0-9]+]] = alloc_box ${ var SomeClass } // CHECK: [[CADDR:%.*]] = project_box [[CBOX]] // CHECK: [[FUNC:%[0-9]+]] = function_ref @_T09functions9SomeClassC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (Builtin.Int64, Builtin.Int64, @thick SomeClass.Type) -> @owned SomeClass // CHECK: [[META:%[0-9]+]] = metatype $@thick SomeClass.Type // CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]] // CHECK: [[J:%[0-9]+]] = load [trivial] [[JADDR]] // CHECK: [[C:%[0-9]+]] = apply [[FUNC]]([[I]], [[J]], [[META]]) var c = SomeClass(x: i, y: j) // CHECK: [[C:%[0-9]+]] = load [copy] [[CADDR]] // CHECK: [[METHOD:%[0-9]+]] = class_method [[C]] : {{.*}}, #SomeClass.method!1 // CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]] // CHECK: apply [[METHOD]]([[I]], [[C]]) // CHECK: destroy_value [[C]] c.method(i) // -- Curry 'self' onto unapplied methods dispatched using class_method. // CHECK: [[METHOD_CURRY_THUNK:%.*]] = function_ref @_T09functions9SomeClassC6method{{[_0-9a-zA-Z]*}}F // CHECK: apply [[METHOD_CURRY_THUNK]] var cm1 = SomeClass.method(c) cm1(i) // CHECK: [[C:%[0-9]+]] = load [copy] [[CADDR]] // CHECK: [[METHOD:%[0-9]+]] = class_method [[C]] : {{.*}}, #SomeClass.method!1 // CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]] // CHECK: apply [[METHOD]]([[I]], [[C]]) // CHECK: destroy_value [[C]] SomeClass.method(c)(i) // -- Curry the Type onto static method argument lists. // CHECK: [[C:%[0-9]+]] = load_borrow [[CADDR]] // CHECK: [[META:%.*]] = value_metatype $@thick SomeClass.Type, [[C]] // CHECK: [[METHOD:%[0-9]+]] = class_method [[META]] : {{.*}}, #SomeClass.static_method!1 // CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]] // CHECK: apply [[METHOD]]([[I]], [[META]]) type(of: c).static_method(i) // -- Curry property accesses. // -- FIXME: class_method-ify class getters. // CHECK: [[C:%[0-9]+]] = load [copy] [[CADDR]] // CHECK: [[GETTER:%[0-9]+]] = class_method {{.*}} : $SomeClass, #SomeClass.someProperty!getter.1 // CHECK: apply [[GETTER]]([[C]]) // CHECK: destroy_value [[C]] i = c.someProperty // CHECK: [[C:%[0-9]+]] = load [copy] [[CADDR]] // CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]] // CHECK: [[SETTER:%[0-9]+]] = class_method [[C]] : $SomeClass, #SomeClass.someProperty!setter.1 : (SomeClass) -> (Builtin.Int64) -> () // CHECK: apply [[SETTER]]([[I]], [[C]]) // CHECK: destroy_value [[C]] c.someProperty = i // CHECK: [[C:%[0-9]+]] = load [copy] [[CADDR]] // CHECK: [[J:%[0-9]+]] = load [trivial] [[JADDR]] // CHECK: [[K:%[0-9]+]] = load [trivial] [[KADDR]] // CHECK: [[GETTER:%[0-9]+]] = class_method [[C]] : $SomeClass, #SomeClass.subscript!getter.1 : (SomeClass) -> (Builtin.Int64, Builtin.Int64) -> Builtin.Int64, $@convention(method) (Builtin.Int64, Builtin.Int64, @guaranteed SomeClass) -> Builtin.Int64 // CHECK: apply [[GETTER]]([[J]], [[K]], [[C]]) // CHECK: destroy_value [[C]] i = c[j, k] // CHECK: [[C:%[0-9]+]] = load [copy] [[CADDR]] // CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]] // CHECK: [[J:%[0-9]+]] = load [trivial] [[JADDR]] // CHECK: [[K:%[0-9]+]] = load [trivial] [[KADDR]] // CHECK: [[SETTER:%[0-9]+]] = class_method [[C]] : $SomeClass, #SomeClass.subscript!setter.1 : (SomeClass) -> (Builtin.Int64, Builtin.Int64, Builtin.Int64) -> (), $@convention(method) (Builtin.Int64, Builtin.Int64, Builtin.Int64, @guaranteed SomeClass) -> () // CHECK: apply [[SETTER]]([[K]], [[I]], [[J]], [[C]]) // CHECK: destroy_value [[C]] c[i, j] = k // -- Curry the projected concrete value in an existential (or its Type) // -- onto protocol type methods dispatched using protocol_method. // CHECK: [[PBOX:%[0-9]+]] = alloc_box ${ var SomeProtocol } // CHECK: [[PADDR:%.*]] = project_box [[PBOX]] var p : SomeProtocol = ConformsToSomeProtocol() // CHECK: [[TEMP:%.*]] = alloc_stack $SomeProtocol // CHECK: copy_addr [[PADDR]] to [initialization] [[TEMP]] // CHECK: [[PVALUE:%[0-9]+]] = open_existential_addr immutable_access [[TEMP]] : $*SomeProtocol to $*[[OPENED:@opened(.*) SomeProtocol]] // CHECK: [[PMETHOD:%[0-9]+]] = witness_method $[[OPENED]], #SomeProtocol.method!1 // CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]] // CHECK: apply [[PMETHOD]]<[[OPENED]]>([[I]], [[PVALUE]]) // CHECK: destroy_addr [[PVALUE]] // CHECK: deinit_existential_addr [[TEMP]] // CHECK: dealloc_stack [[TEMP]] p.method(i) // CHECK: [[PVALUE:%[0-9]+]] = open_existential_addr immutable_access [[PADDR:%.*]] : $*SomeProtocol to $*[[OPENED:@opened(.*) SomeProtocol]] // CHECK: [[PMETHOD:%[0-9]+]] = witness_method $[[OPENED]], #SomeProtocol.method!1 // CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]] // CHECK: apply [[PMETHOD]]<[[OPENED]]>([[I]], [[PVALUE]]) var sp : SomeProtocol = ConformsToSomeProtocol() sp.method(i) // FIXME: [[PMETHOD:%[0-9]+]] = witness_method $[[OPENED:@opened(.*) SomeProtocol]], #SomeProtocol.static_method!1 // FIXME: [[I:%[0-9]+]] = load [trivial] [[IADDR]] // FIXME: apply [[PMETHOD]]([[I]], [[PMETA]]) // Needs existential metatypes //type(of: p).static_method(i) // -- Use an apply or partial_apply instruction to bind type parameters of a generic. // CHECK: [[GBOX:%[0-9]+]] = alloc_box ${ var SomeGeneric<Builtin.Int64> } // CHECK: [[GADDR:%.*]] = project_box [[GBOX]] // CHECK: [[CTOR_GEN:%[0-9]+]] = function_ref @_T09functions11SomeGenericC{{[_0-9a-zA-Z]*}}fC : $@convention(method) <τ_0_0> (@thick SomeGeneric<τ_0_0>.Type) -> @owned SomeGeneric<τ_0_0> // CHECK: [[META:%[0-9]+]] = metatype $@thick SomeGeneric<Builtin.Int64>.Type // CHECK: apply [[CTOR_GEN]]<Builtin.Int64>([[META]]) var g = SomeGeneric<Builtin.Int64>() // CHECK: [[G:%[0-9]+]] = load [copy] [[GADDR]] // CHECK: [[METHOD_GEN:%[0-9]+]] = class_method [[G]] : {{.*}}, #SomeGeneric.method!1 // CHECK: [[TMPR:%.*]] = alloc_stack $Builtin.Int64 // CHECK: [[TMPI:%.*]] = alloc_stack $Builtin.Int64 // CHECK: apply [[METHOD_GEN]]<{{.*}}>([[TMPR]], [[TMPI]], [[G]]) // CHECK: destroy_value [[G]] g.method(i) // CHECK: [[G:%[0-9]+]] = load [copy] [[GADDR]] // CHECK: [[METHOD_GEN:%[0-9]+]] = class_method [[G]] : {{.*}}, #SomeGeneric.generic!1 // CHECK: [[TMPR:%.*]] = alloc_stack $Builtin.Int64 // CHECK: [[TMPJ:%.*]] = alloc_stack $Builtin.Int64 // CHECK: apply [[METHOD_GEN]]<{{.*}}>([[TMPR]], [[TMPJ]], [[G]]) // CHECK: destroy_value [[G]] g.generic(j) // CHECK: [[C:%[0-9]+]] = load [copy] [[CADDR]] // CHECK: [[METHOD_GEN:%[0-9]+]] = class_method [[C]] : {{.*}}, #SomeClass.generic!1 // CHECK: [[TMPR:%.*]] = alloc_stack $Builtin.Int64 // CHECK: [[TMPK:%.*]] = alloc_stack $Builtin.Int64 // CHECK: apply [[METHOD_GEN]]<{{.*}}>([[TMPR]], [[TMPK]], [[C]]) // CHECK: destroy_value [[C]] c.generic(k) // FIXME: curried generic entry points //var gm1 = g.method //gm1(i) //var gg1 : (Int) -> Int = g.generic //gg1(j) //var cg1 : (Int) -> Int = c.generic //cg1(k) // SIL-level "thin" function values need to be able to convert to // "thick" function values when stored, returned, or passed as arguments. // CHECK: [[FBOX:%[0-9]+]] = alloc_box ${ var @callee_owned (Builtin.Int64, Builtin.Int64) -> Builtin.Int64 } // CHECK: [[FADDR:%.*]] = project_box [[FBOX]] // CHECK: [[FUNC_THIN:%[0-9]+]] = function_ref @_T09functions19standalone_function{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64 // CHECK: [[FUNC_THICK:%[0-9]+]] = thin_to_thick_function [[FUNC_THIN]] // CHECK: store [[FUNC_THICK]] to [init] [[FADDR]] var f = standalone_function // CHECK: [[F:%[0-9]+]] = load [copy] [[FADDR]] // CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]] // CHECK: [[J:%[0-9]+]] = load [trivial] [[JADDR]] // CHECK: apply [[F]]([[I]], [[J]]) f(i, j) // CHECK: [[HOF:%[0-9]+]] = function_ref @_T09functions21higher_order_function{{[_0-9a-zA-Z]*}}F : $@convention(thin) {{.*}} // CHECK: [[FUNC_THIN:%[0-9]+]] = function_ref @_T09functions19standalone_function{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64 // CHECK: [[FUNC_THICK:%[0-9]+]] = thin_to_thick_function [[FUNC_THIN]] // CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]] // CHECK: [[J:%[0-9]+]] = load [trivial] [[JADDR]] // CHECK: apply [[HOF]]([[FUNC_THICK]], [[I]], [[J]]) higher_order_function(standalone_function, i, j) // CHECK: [[HOF2:%[0-9]+]] = function_ref @_T09functions22higher_order_function2{{[_0-9a-zA-Z]*}}F : $@convention(thin) {{.*}} // CHECK: [[FUNC_THIN:%[0-9]+]] = function_ref @_T09functions19standalone_function{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64 // CHECK: [[FUNC_THICK:%.*]] = thin_to_thick_function [[FUNC_THIN]] // CHECK: [[I:%[0-9]+]] = load [trivial] [[IADDR]] // CHECK: [[J:%[0-9]+]] = load [trivial] [[JADDR]] // CHECK: apply [[HOF2]]([[FUNC_THICK]], [[I]], [[J]]) higher_order_function2(standalone_function, i, j) } // -- Curried entry points // CHECK-LABEL: sil shared [thunk] @_T09functions10SomeStructV6method{{[_0-9a-zA-Z]*}}FTc : $@convention(thin) (@inout SomeStruct) -> @owned @callee_owned (Builtin.Int64) -> () { // CHECK: [[UNCURRIED:%.*]] = function_ref @_T09functions10SomeStructV6method{{[_0-9a-zA-Z]*}}F : $@convention(method) (Builtin.Int64, @inout SomeStruct) -> (){{.*}} // user: %2 // CHECK: [[CURRIED:%.*]] = partial_apply [[UNCURRIED]] // CHECK: return [[CURRIED]] // CHECK-LABEL: sil shared [thunk] @_T09functions9SomeClassC6method{{[_0-9a-zA-Z]*}}FTc : $@convention(thin) (@owned SomeClass) -> @owned @callee_owned (Builtin.Int64) -> () // CHECK: bb0(%0 : $SomeClass): // CHECK: class_method %0 : $SomeClass, #SomeClass.method!1 : (SomeClass) -> (Builtin.Int64) -> () // CHECK: %2 = partial_apply %1(%0) // CHECK: return %2 func return_func() -> (_ x: Builtin.Int64, _ y: Builtin.Int64) -> Builtin.Int64 { // CHECK: [[FUNC_THIN:%[0-9]+]] = function_ref @_T09functions19standalone_function{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int64, Builtin.Int64) -> Builtin.Int64 // CHECK: [[FUNC_THICK:%[0-9]+]] = thin_to_thick_function [[FUNC_THIN]] // CHECK: return [[FUNC_THICK]] return standalone_function } func standalone_generic<T>(_ x: T, y: T) -> T { return x } // CHECK-LABEL: sil hidden @_T09functions14return_genericBi64_Bi64__Bi64_tcyF func return_generic() -> (_ x:Builtin.Int64, _ y:Builtin.Int64) -> Builtin.Int64 { // CHECK: [[GEN:%.*]] = function_ref @_T09functions18standalone_generic{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0> (@in τ_0_0, @in τ_0_0) -> @out τ_0_0 // CHECK: [[SPEC:%.*]] = partial_apply [[GEN]]<Builtin.Int64>() // CHECK: [[THUNK:%.*]] = function_ref @{{.*}} : $@convention(thin) (Builtin.Int64, Builtin.Int64, @owned @callee_owned (@in Builtin.Int64, @in Builtin.Int64) -> @out Builtin.Int64) -> Builtin.Int64 // CHECK: [[T0:%.*]] = partial_apply [[THUNK]]([[SPEC]]) // CHECK: return [[T0]] return standalone_generic } // CHECK-LABEL: sil hidden @_T09functions20return_generic_tuple{{[_0-9a-zA-Z]*}}F func return_generic_tuple() -> (_ x: (Builtin.Int64, Builtin.Int64), _ y: (Builtin.Int64, Builtin.Int64)) -> (Builtin.Int64, Builtin.Int64) { // CHECK: [[GEN:%.*]] = function_ref @_T09functions18standalone_generic{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0> (@in τ_0_0, @in τ_0_0) -> @out τ_0_0 // CHECK: [[SPEC:%.*]] = partial_apply [[GEN]]<(Builtin.Int64, Builtin.Int64)>() // CHECK: [[THUNK:%.*]] = function_ref @{{.*}} : $@convention(thin) (Builtin.Int64, Builtin.Int64, Builtin.Int64, Builtin.Int64, @owned @callee_owned (@in (Builtin.Int64, Builtin.Int64), @in (Builtin.Int64, Builtin.Int64)) -> @out (Builtin.Int64, Builtin.Int64)) -> (Builtin.Int64, Builtin.Int64) // CHECK: [[T0:%.*]] = partial_apply [[THUNK]]([[SPEC]]) // CHECK: return [[T0]] return standalone_generic } // CHECK-LABEL: sil hidden @_T09functions16testNoReturnAttrs5NeverOyF : $@convention(thin) () -> Never func testNoReturnAttr() -> Never {} // CHECK-LABEL: sil hidden @_T09functions20testNoReturnAttrPoly{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T> (@in T) -> Never func testNoReturnAttrPoly<T>(_ x: T) -> Never {} // CHECK-LABEL: sil hidden @_T09functions21testNoReturnAttrParam{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@owned @callee_owned () -> Never) -> () func testNoReturnAttrParam(_ fptr: () -> Never) -> () {} // CHECK-LABEL: sil hidden [transparent] @_T09functions15testTransparent{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int1) -> Builtin.Int1 @_transparent func testTransparent(_ x: Bool) -> Bool { return x } // CHECK-LABEL: sil hidden @_T09functions16applyTransparent{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int1) -> Builtin.Int1 { func applyTransparent(_ x: Bool) -> Bool { // CHECK: [[FUNC:%[0-9]+]] = function_ref @_T09functions15testTransparent{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Builtin.Int1) -> Builtin.Int1 // CHECK: apply [[FUNC]]({{%[0-9]+}}) : $@convention(thin) (Builtin.Int1) -> Builtin.Int1 return testTransparent(x) } // CHECK-LABEL: sil hidden [noinline] @_T09functions15noinline_calleeyyF : $@convention(thin) () -> () @inline(never) func noinline_callee() {} // CHECK-LABEL: sil hidden [always_inline] @_T09functions20always_inline_calleeyyF : $@convention(thin) () -> () @inline(__always) func always_inline_callee() {} // CHECK-LABEL: sil [fragile] [always_inline] @_T09functions27public_always_inline_calleeyyF : $@convention(thin) () -> () @inline(__always) public func public_always_inline_callee() {} protocol AlwaysInline { func alwaysInlined() } // CHECK-LABEL: sil hidden [always_inline] @_T09functions19AlwaysInlinedMemberV06alwaysC0{{[_0-9a-zA-Z]*}}F : $@convention(method) (AlwaysInlinedMember) -> () { // protocol witness for functions.AlwaysInline.alwaysInlined <A : functions.AlwaysInline>(functions.AlwaysInline.Self)() -> () in conformance functions.AlwaysInlinedMember : functions.AlwaysInline in functions // CHECK-LABEL: sil hidden [transparent] [thunk] [always_inline] @_T09functions19AlwaysInlinedMemberVAA0B6InlineA2aDP06alwaysC0{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in_guaranteed AlwaysInlinedMember) -> () { struct AlwaysInlinedMember : AlwaysInline { @inline(__always) func alwaysInlined() {} } // CHECK-LABEL: sil hidden [_semantics "foo"] @_T09functions9semanticsyyF : $@convention(thin) () -> () @_semantics("foo") func semantics() {} // <rdar://problem/17828355> curried final method on a class crashes in irgen final class r17828355Class { func method(_ x : Int) { var a : r17828355Class var fn = a.method // currying a final method. } } // The curry thunk for the method should not include a class_method instruction. // CHECK-LABEL: sil shared [thunk] @_T09functions14r17828355ClassC6method // CHECK: bb0(%0 : $r17828355Class): // CHECK-NEXT: // function_ref functions.r17828355Class.method (Builtin.Int64) -> () // CHECK-NEXT: %1 = function_ref @_T09functions14r17828355ClassC6method{{[_0-9a-zA-Z]*}}F : $@convention(method) (Builtin.Int64, @guaranteed r17828355Class) -> () // CHECK-NEXT: partial_apply %1(%0) : $@convention(method) (Builtin.Int64, @guaranteed r17828355Class) -> () // CHECK-NEXT: return // <rdar://problem/19981118> Swift 1.2 beta 2: Closures nested in closures copy, rather than reference, captured vars. func noescapefunc(f: () -> ()) {} func escapefunc(_ f : @escaping () -> ()) {} func testNoescape() { // "a" must be captured by-box into noescapefunc because the inner closure // could escape it. var a = 0 noescapefunc { escapefunc { a = 42 } } markUsed(a) } // CHECK-LABEL: functions.testNoescape () -> () // CHECK-NEXT: sil hidden @_T09functions12testNoescapeyyF : $@convention(thin) () -> () // CHECK: function_ref functions.(testNoescape () -> ()).(closure #1) // CHECK-NEXT: function_ref @_T09functions12testNoescapeyyFyycfU_ : $@convention(thin) (@owned { var Int }) -> () // Despite being a noescape closure, this needs to capture 'a' by-box so it can // be passed to the capturing closure.closure // CHECK: functions.(testNoescape () -> ()).(closure #1) // CHECK-NEXT: sil shared @_T09functions12testNoescapeyyFyycfU_ : $@convention(thin) (@owned { var Int }) -> () { func testNoescape2() { // "a" must be captured by-box into noescapefunc because the inner closure // could escape it. This also checks for when the outer closure captures it // in a way that could be used with escape: the union of the two requirements // doesn't allow a by-address capture. var a = 0 noescapefunc { escapefunc { a = 42 } markUsed(a) } markUsed(a) } // CHECK-LABEL: sil hidden @_T09functions13testNoescape2yyF : $@convention(thin) () -> () { // CHECK: // functions.(testNoescape2 () -> ()).(closure #1) // CHECK-NEXT: sil shared @_T09functions13testNoescape2yyFyycfU_ : $@convention(thin) (@owned { var Int }) -> () { // CHECK: // functions.(testNoescape2 () -> ()).(closure #1).(closure #1) // CHECK-NEXT: sil shared @_T09functions13testNoescape2yyFyycfU_yycfU_ : $@convention(thin) (@owned { var Int }) -> () { enum PartialApplyEnumPayload<T, U> { case Left(T) case Right(U) } struct S {} struct C {} func partialApplyEnumCases(_ x: S, y: C) { let left = PartialApplyEnumPayload<S, C>.Left let left2 = left(S()) let right = PartialApplyEnumPayload<S, C>.Right let right2 = right(C()) } // CHECK-LABEL: sil shared [transparent] [thunk] @_T09functions23PartialApplyEnumPayloadO4Left{{[_0-9a-zA-Z]*}}F // CHECK: [[UNCURRIED:%.*]] = function_ref @_T09functions23PartialApplyEnumPayloadO4Left{{[_0-9a-zA-Z]*}}F // CHECK: [[CLOSURE:%.*]] = partial_apply [[UNCURRIED]]<T, U>(%0) // CHECK: return [[CLOSURE]] // CHECK-LABEL: sil shared [transparent] [thunk] @_T09functions23PartialApplyEnumPayloadO5Right{{[_0-9a-zA-Z]*}}F // CHECK: [[UNCURRIED:%.*]] = function_ref @_T09functions23PartialApplyEnumPayloadO5Right{{[_0-9a-zA-Z]*}}F // CHECK: [[CLOSURE:%.*]] = partial_apply [[UNCURRIED]]<T, U>(%0) // CHECK: return [[CLOSURE]]
apache-2.0
2cca1d61e92329fd6ef70ca5d7a5ebad
44.824242
298
0.615042
3.199295
false
false
false
false
apple/swift
test/Constraints/gather_all_adjacencies.swift
4
718
// RUN: %target-swift-frontend -typecheck %s // rdar://problem/32618740 // https://github.com/apple/swift/issues/47696 protocol InitCollection: Collection { init(_ array: [Iterator.Element]) } protocol InitAny { init() } extension Array: InitCollection { init(_ array: [Iterator.Element]) { self = array } } extension String: InitAny { init() { self = "bar" } } class Foo { func foo<T: InitCollection, U: InitAny>(of type: U.Type) -> T where T.Iterator.Element == U { return T.init([U.init()]) } func foo<T: InitCollection, U: InitAny>(of type: U.Type) -> T? where T.Iterator.Element == U { return T.init([U.init()]) } } let _: [String] = Foo().foo(of: String.self)
apache-2.0
bc902c64b6fb178de38e3a7ff05b03e3
16.95
64
0.626741
3.016807
false
false
false
false
madcato/OSLibrary
OSLibrary/OSEditableTableViewController.swift
1
5164
// // OSEditableTableViewController.swift // mavlink // // Created by Daniel Vela on 26/06/16. // Copyright © 2016 Daniel Vela. All rights reserved. // import UIKit protocol OSDataSource { func count() -> Int func get(index: Int) -> String func put(element: String, at: Int) func insert(element: String, at: Int) func post(element: String) func removeAtIndex(index: Int) } // Sample //class TestData: NSObject, OSDataSource { // // var data:[String] // override init() { // data = [] // data.append("Hola") // data.append("Hola1") // data.append("Hola2") // data.append("Hola3") // data.append("Adios") // super.init() // } // // func count() -> Int { // return data.count // } // // func get(index: Int) -> String { // return data[index] // } // // func put(element: String, at: Int) { // data[at] = element // } // // func insert(element: String, at: Int) { // data.insert(element, atIndex: at) // } // // func post(element: String) { // data.append(element) // } // // func removeAtIndex(index: Int) { // data.removeAtIndex(index) // } //} class OSEditableTableViewController: UITableViewController { var dataSource: OSDataSource? override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations self.clearsSelectionOnViewWillAppear = true // Uncomment the following line to display an Edit button in the navigation bar for this view controller. self.navigationItem.rightBarButtonItem = self.editButtonItem() dataSource = TestData() } @IBAction func insertPressed(sender: AnyObject) { let row = self.tableView(self.tableView, numberOfRowsInSection: 0) dataSource?.post("newElement") let indexPath = NSIndexPath(forRow: row, inSection: 0) tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows if let count = dataSource?.count() { return count } else { return 0 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("FileTableCell", forIndexPath: indexPath) // Configure the cell... cell.textLabel?.text = dataSource?.get(indexPath.row) return cell } // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source dataSource?.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { if let data = dataSource?.get(fromIndexPath.row) { dataSource?.removeAtIndex(fromIndexPath.row) dataSource?.insert(data, at: toIndexPath.row) } } // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
3d545a156592ee69535b174b5f61271d
30.481707
157
0.645361
4.820728
false
false
false
false
icapps/swiftGenericWebService
Example/Pods/Stella/Sources/Keychain/Keychain.swift
3
3619
// // Keychain.swift // Pods // // Created by Jelle Vandebeeck on 05/09/16. // // /// `Keychain` is a wrapper for the Keychain shared instance. public let Keychain = KeychainHandler.shared /// The `KeychainHandler` class is responsible for the interaction with the keychain. public class KeychainHandler { public static let shared = KeychainHandler() fileprivate func data(for key: String) -> Data? { let query: [String: AnyObject] = [ kSecClass as String : kSecClassGenericPassword as NSString, kSecMatchLimit as String : kSecMatchLimitOne, kSecReturnData as String : kCFBooleanTrue, kSecAttrService as String: (Bundle.main.bundleIdentifier ?? "") as AnyObject, kSecAttrAccount as String: key as AnyObject ] return self.secItemCopy(query).data as? Data } fileprivate func set(_ data: Data?, for key: String) -> Bool { var query: [String: AnyObject] = [ kSecClass as String : (kSecClassGenericPassword as NSString), kSecAttrAccount as String: key as AnyObject, kSecAttrService as String: (Bundle.main.bundleIdentifier ?? "") as AnyObject, ] if let data = data { query[kSecValueData as String] = data as AnyObject return self.secItemAdd(query) == noErr } else { return self.secItemDelete(query) == noErr } } private func secItemCopy(_ query: [String: AnyObject]) -> (status: OSStatus, data: AnyObject?) { var result: AnyObject? let status: OSStatus = withUnsafeMutablePointer(to: &result) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) } return (status, result) } private func secItemAdd(_ attributes: [String: AnyObject]) -> OSStatus { _ = self.secItemDelete(attributes) return SecItemAdd(attributes as CFDictionary, nil) } private func secItemUpdate(_ query: [String: AnyObject], attributes: [String: AnyObject]) -> OSStatus { return SecItemUpdate(query as CFDictionary, attributes as CFDictionary) } private func secItemDelete(_ query: [String: AnyObject]) -> OSStatus { return SecItemDelete(query as CFDictionary) } } /// `Keys` is a wrapper we can extend to define all the different keychain keys available. /// /// ``` /// extension Keys { /// static let string = Key<String?>("the string keychain key") /// } /// ``` open class Keys {} /// The `Key` defines the key and the value type for a certain keychain value. open class Key<ValueType>: Keys { fileprivate let key: String /// Initialize the key in your `Keys` extension. /// /// ``` /// static let string = Key<String?>("the string keychain key") /// ``` public init(_ key: String) { self.key = key } } public extension KeychainHandler { /// Get the keychain String value for the given `DefaultsKey`. The preferred way to do this is to pass the static key variable defined in the `DefaultsKeys` extension. /// /// ``` /// static let string = Key<String?>("the string defaults key") /// ``` public subscript(key: Key<String?>) -> String? { get { if let data = data(for: key.key) { return String(data: data, encoding: .utf8) } return nil } set { let value = newValue?.data(using: .utf8, allowLossyConversion: false) let _ = set(value, for: key.key) } } }
mit
630387908fc3275aec086c233ea0b0ac
32.509259
171
0.611771
4.681759
false
false
false
false
pollarm/MondoKit
MondoKitTestApp/Accounts/AccountsListViewController.swift
1
2040
// // AccountsListViewController.swift // MondoKit // // Created by Mike Pollard on 24/01/2016. // Copyright © 2016 Mike Pollard. All rights reserved. // import UIKit import MondoKit class AccountsListViewController: UIViewController { private static let AccountCellIdentifier = "AccountCell" @IBOutlet private var tableView : UITableView! private var accounts : [MondoAccount] = [] override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) MondoAPI.instance.listAccounts() { [weak self] (accounts, error) in if let accounts = accounts { self?.accounts = accounts self?.tableView.reloadData() } } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let detailsController = segue.destinationViewController as? AccountDetailsViewController, indexPath = tableView.indexPathForSelectedRow { detailsController.account = accounts[indexPath.row] } } } extension AccountsListViewController : UITableViewDataSource, UITableViewDelegate { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return accounts.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(AccountsListViewController.AccountCellIdentifier, forIndexPath: indexPath) let account = accounts[indexPath.row] cell.textLabel?.text = account.description cell.detailTextLabel?.text = account.accountNumber return cell } }
mit
2b005cc638af9812562d31f53a40e798
27.71831
137
0.655223
5.809117
false
false
false
false
brentdax/swift
test/expr/delayed-ident/static_var.swift
4
1679
// RUN: %target-typecheck-verify-swift // Simple struct types struct X1 { static var AnX1 = X1() static var NotAnX1 = 42 } func acceptInOutX1(_ x1: inout X1) { } var x1: X1 = .AnX1 x1 = .AnX1 x1 = .NotAnX1 // expected-error{{member 'NotAnX1' in 'X1' produces result of type 'Int', but context expects 'X1'}} // Delayed identifier expressions as lvalues (.AnX1 = x1) acceptInOutX1(&(.AnX1)) // Generic struct types struct X2<T> { static var AnX2 = X2() // expected-error{{static stored properties not supported in generic types}} static var NotAnX2 = 0 // expected-error {{static stored properties not supported in generic types}} } var x2: X2<Int> = .AnX2 x2 = .AnX2 // reference to isInvalid() decl. x2 = .NotAnX2 // expected-error{{member 'NotAnX2' in 'X2<Int>' produces result of type 'Int', but context expects 'X2<Int>'}} // Static variables through operators. struct Foo { static var Bar = Foo() static var Wibble = Foo() } func & (x: Foo, y: Foo) -> Foo { } var fooValue: Foo = .Bar & .Wibble // Static closure variables. struct HasClosure { static var factoryNormal: (Int) -> HasClosure = { _ in .init() } static var factoryReturnOpt: (Int) -> HasClosure? = { _ in .init() } static var factoryIUO: ((Int) -> HasClosure)! = { _ in .init() } static var factoryOpt: ((Int) -> HasClosure)? = { _ in .init() } } var _: HasClosure = .factoryNormal(0) var _: HasClosure = .factoryReturnOpt(1)! var _: HasClosure = .factoryIUO(2) var _: HasClosure = .factoryOpt(3) // expected-error {{static property 'factoryOpt' is not a function}} var _: HasClosure = .factoryOpt!(4) // expected-error {{type of expression is ambiguous without more context}}
apache-2.0
0cce7b152b7b8447db01f6d3899005a4
32.58
125
0.673615
3.198095
false
false
false
false
away4m/Vendors
Vendors/Extensions/UIColor.swift
1
84679
// // UIColor.swift // Pods // // Created by Admin on 11/24/16. // // #if canImport(UIKit) import UIKit /// Color public typealias Color = UIColor #endif #if canImport(Cocoa) import Cocoa /// Color public typealias Color = NSColor #endif #if !os(watchOS) import CoreImage #endif #if !os(Linux) public func UIColorFromRGB(_ colorCode: String, alpha: Float = 1.0) -> Color { let scanner = Scanner(string: colorCode) var color: UInt32 = 0 scanner.scanHexInt32(&color) let mask = 0x0000_00FF let r = CGFloat(Float(Int(color >> 16) & mask) / 255.0) let g = CGFloat(Float(Int(color >> 8) & mask) / 255.0) let b = CGFloat(Float(Int(color) & mask) / 255.0) return Color(red: r, green: g, blue: b, alpha: CGFloat(alpha)) } // MARK: - Properties public extension Color { /** The six-digit hexadecimal representation of color of the form #RRGGBB. - parameter hex: Six-digit hexadecimal value. */ public convenience init(hex: UInt32, alpha: CGFloat = 1) { let divisor = CGFloat(255) let red = CGFloat((hex & 0xFF0000) >> 16) / divisor let green = CGFloat((hex & 0x00FF00) >> 8) / divisor let blue = CGFloat(hex & 0x0000FF) / divisor self.init(red: red, green: green, blue: blue, alpha: alpha) } /** The shorthand three-digit hexadecimal representation of color. #RGB defines to the color #RRGGBB. - parameter hex3: Three-digit hexadecimal value. - parameter alpha: 0.0 - 1.0. The default is 1.0. */ public convenience init(hex3: UInt16, alpha: CGFloat = 1) { let divisor = CGFloat(15) let red = CGFloat((hex3 & 0xF00) >> 8) / divisor let green = CGFloat((hex3 & 0x0F0) >> 4) / divisor let blue = CGFloat(hex3 & 0x00F) / divisor self.init(red: red, green: green, blue: blue, alpha: alpha) } /** The shorthand four-digit hexadecimal representation of color with alpha. #RGBA defines to the color #RRGGBBAA. - parameter hex4: Four-digit hexadecimal value. */ public convenience init(hex4: UInt16) { let divisor = CGFloat(15) let red = CGFloat((hex4 & 0xF000) >> 12) / divisor let green = CGFloat((hex4 & 0x0F00) >> 8) / divisor let blue = CGFloat((hex4 & 0x00F0) >> 4) / divisor let alpha = CGFloat(hex4 & 0x000F) / divisor self.init(red: red, green: green, blue: blue, alpha: alpha) } /** The six-digit hexadecimal representation of color of the form #RRGGBB. - parameter hex6: Six-digit hexadecimal value. */ public convenience init(hex6: UInt32, alpha: CGFloat = 1) { let divisor = CGFloat(255) let red = CGFloat((hex6 & 0xFF0000) >> 16) / divisor let green = CGFloat((hex6 & 0x00FF00) >> 8) / divisor let blue = CGFloat(hex6 & 0x0000FF) / divisor self.init(red: red, green: green, blue: blue, alpha: alpha) } /** The six-digit hexadecimal representation of color with alpha of the form #RRGGBBAA. - parameter hex8: Eight-digit hexadecimal value. */ public convenience init(hex8: UInt32) { let divisor = CGFloat(255) let red = CGFloat((hex8 & 0xFF00_0000) >> 24) / divisor let green = CGFloat((hex8 & 0x00FF_0000) >> 16) / divisor let blue = CGFloat((hex8 & 0x0000_FF00) >> 8) / divisor let alpha = CGFloat(hex8 & 0x0000_00FF) / divisor self.init(red: red, green: green, blue: blue, alpha: alpha) } /** Returns a UIColor initialized with color components divided by 255.0. - parameter red: Integer representation of the red component in range of 0-255. - parameter green: Integer representation of the green component in range of 0-255. - parameter blue: Integer representation of the blue component in range of 0-255. */ public convenience init(red: UInt8, green: UInt8, blue: UInt8) { self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } /// SwifterSwift: Create NSColor from RGB values with optional transparency. /// /// - Parameters: /// - red: red component. /// - green: green component. /// - blue: blue component. /// - transparency: optional transparency value (default is 1). public convenience init?(red: Int, green: Int, blue: Int, transparency: CGFloat = 1) { guard red >= 0, red <= 255 else { return nil } guard green >= 0, green <= 255 else { return nil } guard blue >= 0, blue <= 255 else { return nil } var trans = transparency if trans < 0 { trans = 0 } if trans > 1 { trans = 1 } self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: trans) } /** Returns a UIColor from the given RGB components. - parameter red: The red component in range of 0-255. - parameter green: The green component in range of 0-255. - parameter blue: The blue component in range of 0-255. - parameter alpha: The alpha component. - returns: A UIColor initialized with the given RGB components. */ public static func rgb(_ red: UInt8, _ green: UInt8, _ blue: UInt8, alpha: CGFloat = 1) -> Color { return Color(red: red, green: green, blue: blue).alpha(alpha) } /** Returns an alpha-adjusted UIColor. - returns: A UIColor with an adjust alpha component (shorthand for `colorWithAlphaComponent`). */ public final func alpha(_ alpha: CGFloat) -> Color { return withAlphaComponent(alpha) } /** Returns a UIColor from a hue-saturation-lightness (HSL) set. - parameter hue: The hue component of the color object, specified as a value from 0.0 to 1.0. - parameter saturation: The saturation component of the color object, specified as a value from 0.0 to 1.0. - parameter lightness: The lightness component of the color object, specified as a value from 0.0 to 1.0. - parameter alpha: The opacity component of the color object, specified as a value from 0.0 to 1.0 (optional). - returns: A UIColor initialized with the given color value. */ public convenience init(hue: CGFloat, saturation: CGFloat, lightness: CGFloat, alpha: CGFloat = 1) { assert((0 ... 1).contains(hue), "hue value must be a value between 0.0 and 1.0") assert((0 ... 1).contains(saturation), "saturation must be a value between 0.0 and 1.0") assert((0 ... 1).contains(lightness), "lightness must be a value between 0.0 and 1.0") assert((0 ... 1).contains(alpha), "alpha must be a value between 0.0 and 1.0") let (r, g, b) = Model.hsl(hue, saturation, lightness).rgb self.init(red: r / 255, green: g / 255, blue: b / 255, alpha: alpha) } /** Returns a UIColor from a cyan-magenta-yellow-key (CMYK) set. - parameter cyan: The cyan component of the color object, specified as a value from 0.0 to 1.0. - parameter magenta: The magenta component of the color object, specified as a value from 0.0 to 1.0. - parameter yellow: The yellow component of the color object, specified as a value from 0.0 to 1.0. - parameter key: The key (black) component of the color object, specified as a value from 0.0 to 1.0. - parameter alpha: The opacity component of the color object, specified as a value from 0.0 to 1.0 (optional). - returns: A UIColor initialized with the given color value. */ public convenience init(cyan: CGFloat, magenta: CGFloat, yellow: CGFloat, key: CGFloat, alpha: CGFloat = 1) { assert((0 ... 1).contains(cyan), "cyan value must be a value between 0.0 and 1.0") assert((0 ... 1).contains(magenta), "magenta must be a value between 0.0 and 1.0") assert((0 ... 1).contains(yellow), "yellow must be a value between 0.0 and 1.0") assert((0 ... 1).contains(key), "key must be a value between 0.0 and 1.0") assert((0 ... 1).contains(alpha), "alpha must be a value between 0.0 and 1.0") let (r, g, b) = Model.cmyk(cyan, magenta, yellow, key).rgb self.init(red: r / 255, green: g / 255, blue: b / 255, alpha: alpha) } /// SwifterSwift: Create NSColor from hexadecimal value with optional transparency. /// /// - Parameters: /// - hex: hex Int (example: 0xDECEB5). /// - transparency: optional transparency value (default is 1). public convenience init?(hex: Int, transparency: CGFloat = 1) { var trans = transparency if trans < 0 { trans = 0 } if trans > 1 { trans = 1 } let red = (hex >> 16) & 0xFF let green = (hex >> 8) & 0xFF let blue = hex & 0xFF self.init(red: red, green: green, blue: blue, transparency: trans) } /// SwifterSwift: Create Color from hexadecimal string with optional transparency (if applicable). /// /// - Parameters: /// - hexString: hexadecimal string (examples: EDE7F6, 0xEDE7F6, #EDE7F6, #0ff, 0xF0F, ..). /// - transparency: optional transparency value (default is 1). public convenience init?(hexString: String, transparency: CGFloat = 1) { var string = "" if hexString.lowercased().hasPrefix("0x") { string = hexString.replacingOccurrences(of: "0x", with: "") } else if hexString.hasPrefix("#") { string = hexString.replacingOccurrences(of: "#", with: "") } else { string = hexString } if string.count == 3 { // convert hex to 6 digit format if in short format var str = "" string.forEach { str.append(String(repeating: String($0), count: 2)) } string = str } guard let hexValue = Int(string, radix: 16) else { return nil } var trans = transparency if trans < 0 { trans = 0 } if trans > 1 { trans = 1 } let red = (hexValue >> 16) & 0xFF let green = (hexValue >> 8) & 0xFF let blue = hexValue & 0xFF self.init(red: red, green: green, blue: blue, transparency: trans) } // swiftlint:disable next large_tuple /// SwifterSwift: RGB components for a Color (between 0 and 255). /// /// UIColor.red.rgbComponents.red -> 255 /// NSColor.green.rgbComponents.green -> 255 /// UIColor.blue.rgbComponents.blue -> 255 /// public var rgbComponents: (red: Int, green: Int, blue: Int) { var components: [CGFloat] { let comps = cgColor.components! if comps.count == 4 { return comps } return [comps[0], comps[0], comps[0], comps[1]] } let red = components[0] let green = components[1] let blue = components[2] return (red: Int(red * 255.0), green: Int(green * 255.0), blue: Int(blue * 255.0)) } // swiftlint:disable next large_tuple /// SwifterSwift: RGB components for a Color represented as CGFloat numbers (between 0 and 1) /// /// UIColor.red.rgbComponents.red -> 1.0 /// NSColor.green.rgbComponents.green -> 1.0 /// UIColor.blue.rgbComponents.blue -> 1.0 /// public var cgFloatComponents: (red: CGFloat, green: CGFloat, blue: CGFloat) { var components: [CGFloat] { let comps = cgColor.components! if comps.count == 4 { return comps } return [comps[0], comps[0], comps[0], comps[1]] } let red = components[0] let green = components[1] let blue = components[2] return (red: red, green: green, blue: blue) } #if !os(watchOS) /// SwifterSwift: CoreImage.CIColor (read-only) public var coreImageColor: CoreImage.CIColor? { return CoreImage.CIColor(color: self) } #endif /// SwifterSwift: Create Color from a complementary of a Color (if applicable). /// /// - Parameter color: color of which opposite color is desired. public convenience init?(complementaryFor color: Color) { let colorSpaceRGB = CGColorSpaceCreateDeviceRGB() let convertColorToRGBSpace: ((_ color: Color) -> Color?) = { color -> Color? in if color.cgColor.colorSpace!.model == CGColorSpaceModel.monochrome { let oldComponents = color.cgColor.components let components: [CGFloat] = [oldComponents![0], oldComponents![0], oldComponents![0], oldComponents![1]] let colorRef = CGColor(colorSpace: colorSpaceRGB, components: components) let colorOut = Color(cgColor: colorRef!) return colorOut } else { return color } } let c = convertColorToRGBSpace(color) guard let componentColors = c?.cgColor.components else { return nil } let r: CGFloat = sqrt(pow(255.0, 2.0) - pow((componentColors[0] * 255), 2.0)) / 255 let g: CGFloat = sqrt(pow(255.0, 2.0) - pow((componentColors[1] * 255), 2.0)) / 255 let b: CGFloat = sqrt(pow(255.0, 2.0) - pow((componentColors[2] * 255), 2.0)) / 255 self.init(red: r, green: g, blue: b, alpha: 1.0) } /// SwifterSwift: Get UInt representation of a Color (read-only). public var uInt: UInt { let comps: [CGFloat] = { let comps = cgColor.components! return comps.count == 4 ? comps : [comps[0], comps[0], comps[0], comps[1]] }() var colorAsUInt32: UInt32 = 0 colorAsUInt32 += UInt32(comps[0] * 255.0) << 16 colorAsUInt32 += UInt32(comps[1] * 255.0) << 8 colorAsUInt32 += UInt32(comps[2] * 255.0) return UInt(colorAsUInt32) } // Red component of UIColor (read-only). public var redComponent: Int { var red: CGFloat = 0 getRed(&red, green: nil, blue: nil, alpha: nil) return Int(red * 255) } // Green component of UIColor (read-only). public var greenComponent: Int { var green: CGFloat = 0 getRed(nil, green: &green, blue: nil, alpha: nil) return Int(green * 255) } // blue component of UIColor (read-only). public var blueComponent: Int { var blue: CGFloat = 0 getRed(nil, green: nil, blue: &blue, alpha: nil) return Int(blue * 255) } // SwifterSwift: Alpha of Color (read-only). public var alpha: CGFloat { return cgColor.alpha } /// RGB properties: luminance. public var luminance: CGFloat { if canProvideRGBComponents() { var red: CGFloat = 0.0, green: CGFloat = 0.0, blue: CGFloat = 0.0, alpha: CGFloat = 0.0 if !getRed(&red, green: &green, blue: &blue, alpha: &alpha) { return 0.0 } return red * 0.2126 + green * 0.7152 + blue * 0.0722 } return 0.0 } /// Check if the color is in RGB format. /// /// - Returns: Returns if the color is in RGB format. public func canProvideRGBComponents() -> Bool { guard let colorSpace = self.cgColor.colorSpace else { return false } switch colorSpace.model { case CGColorSpaceModel.rgb, CGColorSpaceModel.monochrome: return true default: return false } } /// SwifterSwift: Get color complementary (read-only, if applicable). public var complementary: Color? { let colorSpaceRGB = CGColorSpaceCreateDeviceRGB() let convertColorToRGBSpace: ((_ color: Color) -> Color?) = { _ -> Color? in if self.cgColor.colorSpace!.model == CGColorSpaceModel.monochrome { let oldComponents = self.cgColor.components let components: [CGFloat] = [oldComponents![0], oldComponents![0], oldComponents![0], oldComponents![1]] let colorRef = CGColor(colorSpace: colorSpaceRGB, components: components) let colorOut = Color(cgColor: colorRef!) return colorOut } else { return self } } let c = convertColorToRGBSpace(self) guard let componentColors = c?.cgColor.components else { return nil } let r: CGFloat = sqrt(pow(255.0, 2.0) - pow((componentColors[0] * 255), 2.0)) / 255 let g: CGFloat = sqrt(pow(255.0, 2.0) - pow((componentColors[1] * 255), 2.0)) / 255 let b: CGFloat = sqrt(pow(255.0, 2.0) - pow((componentColors[2] * 255), 2.0)) / 255 return Color(red: r, green: g, blue: b, alpha: 1.0) } /// A good contrasting color, it will be either black or white. /// /// - Returns: Returns the color. public func contrasting() -> Color { return luminance > 0.5 ? UIColor.black : UIColor.white } /// SwifterSwift: Hexadecimal value string (read-only). public var hexString: String { let components: [Int] = { let comps = cgColor.components! let components = comps.count == 4 ? comps : [comps[0], comps[0], comps[0], comps[1]] return components.map { Int($0 * 255.0) } }() return String(format: "#%02X%02X%02X", components[0], components[1], components[2]) } /** Returns the color representation as a 32-bit integer. - returns: A UInt32 that represents the hexadecimal color. */ public final var hex: UInt32 { let (r, g, b, _) = rgba return Model.rgb(r * 255, g * 255, b * 255).hex } /** Returns the RGBA (red, green, blue, alpha) components, specified as values from 0.0 to 1.0. - returns: The RGBA components as a tuple (r, g, b, a). */ public final var rgba: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) { var (r, g, b, a): (CGFloat, CGFloat, CGFloat, CGFloat) = (0, 0, 0, 0) getRed(&r, green: &g, blue: &b, alpha: &a) return (r, g, b, a) } /** Returns the HSL (hue, saturation, lightness) components, specified as values from 0.0 to 1.0. - returns: The HSL components as a tuple (h, s, l). */ public final var hsl: (h: CGFloat, s: CGFloat, l: CGFloat) { let (r, g, b, _) = rgba return Model.rgb(r * 255, g * 255, b * 255).hsl } /** Returns the HSB (hue, saturation, brightness) components, specified as values from 0.0 to 1.0. - returns: The HSB components as a tuple (h, s, b). */ public final var hsb: (h: CGFloat, s: CGFloat, b: CGFloat) { let (r, g, b, _) = rgba return Model.rgb(r * 255, g * 255, b * 255).hsb } /** Returns the CMYK (cyan, magenta, yellow, key) components, specified as values from 0.0 to 1.0. - returns: The CMYK components as a tuple (c, m, y, k). */ public final var cmyk: (c: CGFloat, m: CGFloat, y: CGFloat, k: CGFloat) { let (r, g, b, _) = rgba return Model.rgb(r * 255, g * 255, b * 255).cmyk } /// SwifterSwift: Short hexadecimal value string (read-only, if applicable). public var shortHexString: String? { let string = hexString.replacingOccurrences(of: "#", with: "") let chrs = Array(string) guard chrs[0] == chrs[1], chrs[2] == chrs[3], chrs[4] == chrs[5] else { return nil } return "#\(chrs[0])\(chrs[2])\(chrs[4])" } /// SwifterSwift: Short hexadecimal value string, or full hexadecimal string if not possible (read-only). public var shortHexOrHexString: String { let components: [Int] = { let comps = cgColor.components! let components = comps.count == 4 ? comps : [comps[0], comps[0], comps[0], comps[1]] return components.map { Int($0 * 255.0) } }() let hexString = String(format: "#%02X%02X%02X", components[0], components[1], components[2]) let string = hexString.replacingOccurrences(of: "#", with: "") let chrs = Array(string) guard chrs[0] == chrs[1], chrs[2] == chrs[3], chrs[4] == chrs[5] else { return hexString } return "#\(chrs[0])\(chrs[2])\(chrs[4])" } /// SwifterSwift: Random color. public static var random: Color { let r = Int(arc4random_uniform(255)) let g = Int(arc4random_uniform(255)) let b = Int(arc4random_uniform(255)) return Color(red: r, green: g, blue: b)! } open override var description: String { return self.hexString } open override var debugDescription: String { return hexString } /// Mixes the color with another color /// /// - parameter color: The color to mix with /// - parameter amount: The amount (0-1) to mix the new color in. /// - returns: A new UIColor instance representing the resulting color public func mixWithColor(color: UIColor, amount: Float) -> Color { let rgba1 = rgba var comp1 = [rgba1.r, rgba1.g, rgba1.b, rgba1.a] // self.getRed(&comp1[0], green: &comp1[1], blue: &comp1[2], alpha: &comp1[3]) var rgba2 = color.rgba var comp2 = [rgba2.r, rgba2.g, rgba2.b, rgba2.a] // color.getRed(&comp2[0], green: &comp2[1], blue: &comp2[2], alpha: &comp2[3]) var comp: [CGFloat] = Array(repeating: 0, count: 4) for i in 0 ... 3 { comp[i] = comp1[i] + (comp2[i] - comp1[i]) * CGFloat(amount) } return Color(red: comp[0], green: comp[1], blue: comp[2], alpha: comp[3]) } /// SwifterSwift: Lighten a color /// /// let color = Color(red: r, green: g, blue: b, alpha: a) /// let lighterColor: Color = color.lighten(by: 0.2) /// /// - Parameter percentage: Percentage by which to lighten the color /// - Returns: A lightened color public func lighten(by percentage: CGFloat = 0.2) -> Color { // https://stackoverflow.com/questions/38435308/swift-get-lighter-and-darker-color-variations-for-a-given-uicolor var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: &a) return Color( red: min(r + percentage, 1.0), green: min(g + percentage, 1.0), blue: min(b + percentage, 1.0), alpha: a ) } /// SwifterSwift: Darken a color /// /// let color = Color(red: r, green: g, blue: b, alpha: a) /// let darkerColor: Color = color.darken(by: 0.2) /// /// - Parameter percentage: Percentage by which to darken the color /// - Returns: A darkened color public func darken(by percentage: CGFloat = 0.2) -> Color { // https://stackoverflow.com/questions/38435308/swift-get-lighter-and-darker-color-variations-for-a-given-uicolor var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: &a) return Color( red: max(r - percentage, 0), green: max(g - percentage, 0), blue: max(b - percentage, 0), alpha: a ) } } // MARK: - Model extension Color { /** Model is an enum for describing and converting color models. - `rgb`: Red, Green, Blue color representation - `hsl`: Hue, Saturation, Lightness color representation - `hsb`: Hue, Saturation, Brightness color representation - `cmyk`: Cyan, Magenta, Yellow, Key (Black) color representation - `hex`: UInt32 (hex) color representation */ public enum Model { /// Red, Green, Blue case rgb(CGFloat, CGFloat, CGFloat) /// Hue, Saturation, Lightness case hsl(CGFloat, CGFloat, CGFloat) /// Hue, Saturation, Brightness case hsb(CGFloat, CGFloat, CGFloat) /// Cyan, Magenta, Yellow, Key (Black) case cmyk(CGFloat, CGFloat, CGFloat, CGFloat) /// UInt32 (hex) case hex(UInt32) /// Returns the model as an RGB tuple public var rgb: (r: CGFloat, g: CGFloat, b: CGFloat) { switch self { case let .rgb(rgb): return rgb case let .hsl(h, s, l): return convert(hsl: h, s, l) case let .hsb(h, s, b): return convert(hsb: h, s, b) case let .cmyk(c, m, y, k): return convert(cmyk: c, m, y, k) case let .hex(hex): return convert(hex: hex) } } /// Returns the model as an HSL tuple public var hsl: (h: CGFloat, s: CGFloat, l: CGFloat) { switch self { case let .rgb(r, g, b): return convert(rgb: r, g, b) case let .hsl(hsl): return hsl case .hsb, .cmyk, .hex: let (r, g, b) = rgb return convert(rgb: r, g, b) } } /// Returns the model as an HSB tuple public var hsb: (h: CGFloat, s: CGFloat, b: CGFloat) { switch self { case let .rgb(r, g, b): return convert(rgb: r, g, b) case .hsl, .cmyk, .hex: let (r, g, b) = rgb return convert(rgb: r, g, b) case let .hsb(hsb): return hsb } } /// Returns the model as a CMYK tuple public var cmyk: (c: CGFloat, m: CGFloat, y: CGFloat, k: CGFloat) { switch self { case let .rgb(r, g, b): return convert(rgb: r, g, b) case .hsl, .hsb, .hex: let (r, g, b) = rgb return convert(rgb: r, g, b) case let .cmyk(cmyk): return cmyk } } /// Returns the model as a UInt32 (hex) value public var hex: UInt32 { switch self { case let .rgb(r, g, b): return convert(rgb: r, g, b) case .hsl, .hsb, .cmyk: let (r, g, b) = rgb return convert(rgb: r, g, b) case let .hex(hex): return hex } } } } // MARK: - Private color model conversions /// Converts RGB to HSL (https://en.wikipedia.org/wiki/HSL_and_HSV) private func convert(rgb r: CGFloat, _ g: CGFloat, _ b: CGFloat) -> (h: CGFloat, s: CGFloat, l: CGFloat) { let r = r / 255 let g = g / 255 let b = b / 255 let max = Swift.max(r, g, b) let min = Swift.min(r, g, b) var h, s: CGFloat let l = (max + min) / 2 if max == min { h = 0 s = 0 } else { let d = max - min s = (l > 0.5) ? d / (2 - max - min) : d / (max + min) switch max { case r: h = (g - b) / d + (g < b ? 6 : 0) case g: h = (b - r) / d + 2 case b: h = (r - g) / d + 4 default: h = 0 } h /= 6 } return (h, s, l) } /// Converts HSL to RGB (https://en.wikipedia.org/wiki/HSL_and_HSV) private func convert(hsl h: CGFloat, _ s: CGFloat, _ l: CGFloat) -> (r: CGFloat, g: CGFloat, b: CGFloat) { let r, g, b: CGFloat if s == 0 { r = l g = l b = l } else { let c = (1 - abs(2 * l - 1)) * s let x = c * (1 - abs((h * 6).truncatingRemainder(dividingBy: 2) - 1)) let m = l - c / 2 switch h * 6 { case 0 ..< 1: (r, g, b) = (c, x, 0) + m case 1 ..< 2: (r, g, b) = (x, c, 0) + m case 2 ..< 3: (r, g, b) = (0, c, x) + m case 3 ..< 4: (r, g, b) = (0, x, c) + m case 4 ..< 5: (r, g, b) = (x, 0, c) + m case 5 ..< 6: (r, g, b) = (c, 0, x) + m default: (r, g, b) = (0, 0, 0) + m } } return (round(r * 255), round(g * 255), round(b * 255)) } /// Converts RGB to HSB (https://en.wikipedia.org/wiki/HSL_and_HSV) private func convert(rgb r: CGFloat, _ g: CGFloat, _ b: CGFloat) -> (h: CGFloat, s: CGFloat, b: CGFloat) { var h, s, v: CGFloat let r = r / 255 let g = g / 255 let b = b / 255 let max = Swift.max(r, g, b) let min = Swift.min(r, g, b) let d = max - min if d == 0 { h = 0 s = 0 } else { s = (max == 0) ? 0 : d / max switch max { case r: h = ((g - b) / d) + (g < b ? 6 : 0) case g: h = ((b - r) / d) + 2 case b: h = ((r - g) / d) + 4 default: h = 0 } h /= 6 } v = max return (h, s, v) } /// Converts HSB to RGB (https://en.wikipedia.org/wiki/HSL_and_HSV) private func convert(hsb h: CGFloat, _ s: CGFloat, _ b: CGFloat) -> (r: CGFloat, g: CGFloat, b: CGFloat) { let c = b * s let x = c * (1 - abs((h * 6).truncatingRemainder(dividingBy: 2) - 1)) let m = b - c var r, g, b: CGFloat switch h * 6 { case 0 ..< 1: (r, g, b) = (c, x, 0) + m case 1 ..< 2: (r, g, b) = (x, c, 0) + m case 2 ..< 3: (r, g, b) = (0, c, x) + m case 3 ..< 4: (r, g, b) = (0, x, c) + m case 4 ..< 5: (r, g, b) = (x, 0, c) + m case 5 ..< 6: (r, g, b) = (c, 0, x) + m default: (r, g, b) = (0, 0, 0) + m } return (round(r * 255), round(g * 255), round(b * 255)) } /// Converts UInt32 to RGB private func convert(hex: UInt32) -> (r: CGFloat, g: CGFloat, b: CGFloat) { let r = CGFloat((hex >> 16) & 0xFF) let g = CGFloat((hex >> 8) & 0xFF) let b = CGFloat(hex & 0xFF) return (r, g, b) } /// Converts RGB to UInt32 private func convert(rgb r: CGFloat, _ g: CGFloat, _ b: CGFloat) -> UInt32 { return (UInt32(r) << 16) | (UInt32(g) << 8) | UInt32(b) } /// Converts RGB to CMYK (http://www.rapidtables.com/convert/color/rgb-to-cmyk.htm) private func convert(rgb r: CGFloat, _ g: CGFloat, _ b: CGFloat) -> (c: CGFloat, m: CGFloat, y: CGFloat, k: CGFloat) { let r = r / 255 let g = g / 255 let b = b / 255 let k = 1 - max(r, g, b) let c = (k == 1) ? 0 : (1 - r - k) / (1 - k) let m = (k == 1) ? 0 : (1 - g - k) / (1 - k) let y = (k == 1) ? 0 : (1 - b - k) / (1 - k) return (c, m, y, k) } /// Converts CMYK to RGB (http://www.rapidtables.com/convert/color/cmyk-to-rgb.htm) private func convert(cmyk c: CGFloat, _ m: CGFloat, _ y: CGFloat, _ k: CGFloat) -> (r: CGFloat, g: CGFloat, b: CGFloat) { let r = 255 * (1 - c) * (1 - k) let g = 255 * (1 - m) * (1 - k) let b = 255 * (1 - y) * (1 - k) return (round(r), round(g), round(b)) } /// Private operator for HSL and HSB conversion private func + (lhs: (CGFloat, CGFloat, CGFloat), rhs: CGFloat) -> (CGFloat, CGFloat, CGFloat) { return (lhs.0 + rhs, lhs.1 + rhs, lhs.2 + rhs) } // swiftlint:disable next type_body_length // MARK: - Social public extension Color { /// SwifterSwift: Brand identity color of popular social media platform. public struct Social { // https://www.lockedowndesign.com/social-media-colors/ /// red: 59, green: 89, blue: 152 public static let facebook = Color(red: 59, green: 89, blue: 152)! /// red: 0, green: 182, blue: 241 public static let twitter = Color(red: 0, green: 182, blue: 241)! /// red: 223, green: 74, blue: 50 public static let googlePlus = Color(red: 223, green: 74, blue: 50)! /// red: 0, green: 123, blue: 182 public static let linkedIn = Color(red: 0, green: 123, blue: 182)! /// red: 69, green: 187, blue: 255 public static let vimeo = Color(red: 69, green: 187, blue: 255)! /// red: 179, green: 18, blue: 23 public static let youtube = Color(red: 179, green: 18, blue: 23)! /// red: 195, green: 42, blue: 163 public static let instagram = Color(red: 195, green: 42, blue: 163)! /// red: 203, green: 32, blue: 39 public static let pinterest = Color(red: 203, green: 32, blue: 39)! /// red: 244, green: 0, blue: 131 public static let flickr = Color(red: 244, green: 0, blue: 131)! /// red: 67, green: 2, blue: 151 public static let yahoo = Color(red: 67, green: 2, blue: 151)! /// red: 67, green: 2, blue: 151 public static let soundCloud = Color(red: 67, green: 2, blue: 151)! /// red: 44, green: 71, blue: 98 public static let tumblr = Color(red: 44, green: 71, blue: 98)! /// red: 252, green: 69, blue: 117 public static let foursquare = Color(red: 252, green: 69, blue: 117)! /// red: 255, green: 176, blue: 0 public static let swarm = Color(red: 255, green: 176, blue: 0)! /// red: 234, green: 76, blue: 137 public static let dribbble = Color(red: 234, green: 76, blue: 137)! /// red: 255, green: 87, blue: 0 public static let reddit = Color(red: 255, green: 87, blue: 0)! /// red: 74, green: 93, blue: 78 public static let devianArt = Color(red: 74, green: 93, blue: 78)! /// red: 238, green: 64, blue: 86 public static let pocket = Color(red: 238, green: 64, blue: 86)! /// red: 170, green: 34, blue: 182 public static let quora = Color(red: 170, green: 34, blue: 182)! /// red: 247, green: 146, blue: 30 public static let slideShare = Color(red: 247, green: 146, blue: 30)! /// red: 0, green: 153, blue: 229 public static let px500 = Color(red: 0, green: 153, blue: 229)! /// red: 223, green: 109, blue: 70 public static let listly = Color(red: 223, green: 109, blue: 70)! /// red: 0, green: 180, blue: 137 public static let vine = Color(red: 0, green: 180, blue: 137)! /// red: 0, green: 175, blue: 240 public static let skype = Color(red: 0, green: 175, blue: 240)! /// red: 235, green: 73, blue: 36 public static let stumbleUpon = Color(red: 235, green: 73, blue: 36)! /// red: 255, green: 252, blue: 0 public static let snapchat = Color(red: 255, green: 252, blue: 0)! } } // MARK: - Material colors public extension Color { /// SwifterSwift: Google Material design colors palette. public struct Material { // https://material.google.com/style/color.html /// SwifterSwift: color red500 public static let red = red500 /// SwifterSwift: hex #FFEBEE public static let red50 = Color(hex: 0xFFEBEE)! /// SwifterSwift: hex #FFCDD2 public static let red100 = Color(hex: 0xFFCDD2)! /// SwifterSwift: hex #EF9A9A public static let red200 = Color(hex: 0xEF9A9A)! /// SwifterSwift: hex #E57373 public static let red300 = Color(hex: 0xE57373)! /// SwifterSwift: hex #EF5350 public static let red400 = Color(hex: 0xEF5350)! /// SwifterSwift: hex #F44336 public static let red500 = Color(hex: 0xF44336)! /// SwifterSwift: hex #E53935 public static let red600 = Color(hex: 0xE53935)! /// SwifterSwift: hex #D32F2F public static let red700 = Color(hex: 0xD32F2F)! /// SwifterSwift: hex #C62828 public static let red800 = Color(hex: 0xC62828)! /// SwifterSwift: hex #B71C1C public static let red900 = Color(hex: 0xB71C1C)! /// SwifterSwift: hex #FF8A80 public static let redA100 = Color(hex: 0xFF8A80)! /// SwifterSwift: hex #FF5252 public static let redA200 = Color(hex: 0xFF5252)! /// SwifterSwift: hex #FF1744 public static let redA400 = Color(hex: 0xFF1744)! /// SwifterSwift: hex #D50000 public static let redA700 = Color(hex: 0xD50000)! /// SwifterSwift: color pink500 public static let pink = pink500 /// SwifterSwift: hex #FCE4EC public static let pink50 = Color(hex: 0xFCE4EC)! /// SwifterSwift: hex #F8BBD0 public static let pink100 = Color(hex: 0xF8BBD0)! /// SwifterSwift: hex #F48FB1 public static let pink200 = Color(hex: 0xF48FB1)! /// SwifterSwift: hex #F06292 public static let pink300 = Color(hex: 0xF06292)! /// SwifterSwift: hex #EC407A public static let pink400 = Color(hex: 0xEC407A)! /// SwifterSwift: hex #E91E63 public static let pink500 = Color(hex: 0xE91E63)! /// SwifterSwift: hex #D81B60 public static let pink600 = Color(hex: 0xD81B60)! /// SwifterSwift: hex #C2185B public static let pink700 = Color(hex: 0xC2185B)! /// SwifterSwift: hex #AD1457 public static let pink800 = Color(hex: 0xAD1457)! /// SwifterSwift: hex #880E4F public static let pink900 = Color(hex: 0x880E4F)! /// SwifterSwift: hex #FF80AB public static let pinkA100 = Color(hex: 0xFF80AB)! /// SwifterSwift: hex #FF4081 public static let pinkA200 = Color(hex: 0xFF4081)! /// SwifterSwift: hex #F50057 public static let pinkA400 = Color(hex: 0xF50057)! /// SwifterSwift: hex #C51162 public static let pinkA700 = Color(hex: 0xC51162)! /// SwifterSwift: color purple500 public static let purple = purple500 /// SwifterSwift: hex #F3E5F5 public static let purple50 = Color(hex: 0xF3E5F5)! /// SwifterSwift: hex #E1BEE7 public static let purple100 = Color(hex: 0xE1BEE7)! /// SwifterSwift: hex #CE93D8 public static let purple200 = Color(hex: 0xCE93D8)! /// SwifterSwift: hex #BA68C8 public static let purple300 = Color(hex: 0xBA68C8)! /// SwifterSwift: hex #AB47BC public static let purple400 = Color(hex: 0xAB47BC)! /// SwifterSwift: hex #9C27B0 public static let purple500 = Color(hex: 0x9C27B0)! /// SwifterSwift: hex #8E24AA public static let purple600 = Color(hex: 0x8E24AA)! /// SwifterSwift: hex #7B1FA2 public static let purple700 = Color(hex: 0x7B1FA2)! /// SwifterSwift: hex #6A1B9A public static let purple800 = Color(hex: 0x6A1B9A)! /// SwifterSwift: hex #4A148C public static let purple900 = Color(hex: 0x4A148C)! /// SwifterSwift: hex #EA80FC public static let purpleA100 = Color(hex: 0xEA80FC)! /// SwifterSwift: hex #E040FB public static let purpleA200 = Color(hex: 0xE040FB)! /// SwifterSwift: hex #D500F9 public static let purpleA400 = Color(hex: 0xD500F9)! /// SwifterSwift: hex #AA00FF public static let purpleA700 = Color(hex: 0xAA00FF)! /// SwifterSwift: color deepPurple500 public static let deepPurple = deepPurple500 /// SwifterSwift: hex #EDE7F6 public static let deepPurple50 = Color(hex: 0xEDE7F6)! /// SwifterSwift: hex #D1C4E9 public static let deepPurple100 = Color(hex: 0xD1C4E9)! /// SwifterSwift: hex #B39DDB public static let deepPurple200 = Color(hex: 0xB39DDB)! /// SwifterSwift: hex #9575CD public static let deepPurple300 = Color(hex: 0x9575CD)! /// SwifterSwift: hex #7E57C2 public static let deepPurple400 = Color(hex: 0x7E57C2)! /// SwifterSwift: hex #673AB7 public static let deepPurple500 = Color(hex: 0x673AB7)! /// SwifterSwift: hex #5E35B1 public static let deepPurple600 = Color(hex: 0x5E35B1)! /// SwifterSwift: hex #512DA8 public static let deepPurple700 = Color(hex: 0x512DA8)! /// SwifterSwift: hex #4527A0 public static let deepPurple800 = Color(hex: 0x4527A0)! /// SwifterSwift: hex #311B92 public static let deepPurple900 = Color(hex: 0x311B92)! /// SwifterSwift: hex #B388FF public static let deepPurpleA100 = Color(hex: 0xB388FF)! /// SwifterSwift: hex #7C4DFF public static let deepPurpleA200 = Color(hex: 0x7C4DFF)! /// SwifterSwift: hex #651FFF public static let deepPurpleA400 = Color(hex: 0x651FFF)! /// SwifterSwift: hex #6200EA public static let deepPurpleA700 = Color(hex: 0x6200EA)! /// SwifterSwift: color indigo500 public static let indigo = indigo500 /// SwifterSwift: hex #E8EAF6 public static let indigo50 = Color(hex: 0xE8EAF6)! /// SwifterSwift: hex #C5CAE9 public static let indigo100 = Color(hex: 0xC5CAE9)! /// SwifterSwift: hex #9FA8DA public static let indigo200 = Color(hex: 0x9FA8DA)! /// SwifterSwift: hex #7986CB public static let indigo300 = Color(hex: 0x7986CB)! /// SwifterSwift: hex #5C6BC0 public static let indigo400 = Color(hex: 0x5C6BC0)! /// SwifterSwift: hex #3F51B5 public static let indigo500 = Color(hex: 0x3F51B5)! /// SwifterSwift: hex #3949AB public static let indigo600 = Color(hex: 0x3949AB)! /// SwifterSwift: hex #303F9F public static let indigo700 = Color(hex: 0x303F9F)! /// SwifterSwift: hex #283593 public static let indigo800 = Color(hex: 0x283593)! /// SwifterSwift: hex #1A237E public static let indigo900 = Color(hex: 0x1A237E)! /// SwifterSwift: hex #8C9EFF public static let indigoA100 = Color(hex: 0x8C9EFF)! /// SwifterSwift: hex #536DFE public static let indigoA200 = Color(hex: 0x536DFE)! /// SwifterSwift: hex #3D5AFE public static let indigoA400 = Color(hex: 0x3D5AFE)! /// SwifterSwift: hex #304FFE public static let indigoA700 = Color(hex: 0x304FFE)! /// SwifterSwift: color blue500 public static let blue = blue500 /// SwifterSwift: hex #E3F2FD public static let blue50 = Color(hex: 0xE3F2FD)! /// SwifterSwift: hex #BBDEFB public static let blue100 = Color(hex: 0xBBDEFB)! /// SwifterSwift: hex #90CAF9 public static let blue200 = Color(hex: 0x90CAF9)! /// SwifterSwift: hex #64B5F6 public static let blue300 = Color(hex: 0x64B5F6)! /// SwifterSwift: hex #42A5F5 public static let blue400 = Color(hex: 0x42A5F5)! /// SwifterSwift: hex #2196F3 public static let blue500 = Color(hex: 0x2196F3)! /// SwifterSwift: hex #1E88E5 public static let blue600 = Color(hex: 0x1E88E5)! /// SwifterSwift: hex #1976D2 public static let blue700 = Color(hex: 0x1976D2)! /// SwifterSwift: hex #1565C0 public static let blue800 = Color(hex: 0x1565C0)! /// SwifterSwift: hex #0D47A1 public static let blue900 = Color(hex: 0x0D47A1)! /// SwifterSwift: hex #82B1FF public static let blueA100 = Color(hex: 0x82B1FF)! /// SwifterSwift: hex #448AFF public static let blueA200 = Color(hex: 0x448AFF)! /// SwifterSwift: hex #2979FF public static let blueA400 = Color(hex: 0x2979FF)! /// SwifterSwift: hex #2962FF public static let blueA700 = Color(hex: 0x2962FF)! /// SwifterSwift: color lightBlue500 public static let lightBlue = lightBlue500 /// SwifterSwift: hex #E1F5FE public static let lightBlue50 = Color(hex: 0xE1F5FE)! /// SwifterSwift: hex #B3E5FC public static let lightBlue100 = Color(hex: 0xB3E5FC)! /// SwifterSwift: hex #81D4FA public static let lightBlue200 = Color(hex: 0x81D4FA)! /// SwifterSwift: hex #4FC3F7 public static let lightBlue300 = Color(hex: 0x4FC3F7)! /// SwifterSwift: hex #29B6F6 public static let lightBlue400 = Color(hex: 0x29B6F6)! /// SwifterSwift: hex #03A9F4 public static let lightBlue500 = Color(hex: 0x03A9F4)! /// SwifterSwift: hex #039BE5 public static let lightBlue600 = Color(hex: 0x039BE5)! /// SwifterSwift: hex #0288D1 public static let lightBlue700 = Color(hex: 0x0288D1)! /// SwifterSwift: hex #0277BD public static let lightBlue800 = Color(hex: 0x0277BD)! /// SwifterSwift: hex #01579B public static let lightBlue900 = Color(hex: 0x01579B)! /// SwifterSwift: hex #80D8FF public static let lightBlueA100 = Color(hex: 0x80D8FF)! /// SwifterSwift: hex #40C4FF public static let lightBlueA200 = Color(hex: 0x40C4FF)! /// SwifterSwift: hex #00B0FF public static let lightBlueA400 = Color(hex: 0x00B0FF)! /// SwifterSwift: hex #0091EA public static let lightBlueA700 = Color(hex: 0x0091EA)! /// SwifterSwift: color cyan500 public static let cyan = cyan500 /// SwifterSwift: hex #E0F7FA public static let cyan50 = Color(hex: 0xE0F7FA)! /// SwifterSwift: hex #B2EBF2 public static let cyan100 = Color(hex: 0xB2EBF2)! /// SwifterSwift: hex #80DEEA public static let cyan200 = Color(hex: 0x80DEEA)! /// SwifterSwift: hex #4DD0E1 public static let cyan300 = Color(hex: 0x4DD0E1)! /// SwifterSwift: hex #26C6DA public static let cyan400 = Color(hex: 0x26C6DA)! /// SwifterSwift: hex #00BCD4 public static let cyan500 = Color(hex: 0x00BCD4)! /// SwifterSwift: hex #00ACC1 public static let cyan600 = Color(hex: 0x00ACC1)! /// SwifterSwift: hex #0097A7 public static let cyan700 = Color(hex: 0x0097A7)! /// SwifterSwift: hex #00838F public static let cyan800 = Color(hex: 0x00838F)! /// SwifterSwift: hex #006064 public static let cyan900 = Color(hex: 0x006064)! /// SwifterSwift: hex #84FFFF public static let cyanA100 = Color(hex: 0x84FFFF)! /// SwifterSwift: hex #18FFFF public static let cyanA200 = Color(hex: 0x18FFFF)! /// SwifterSwift: hex #00E5FF public static let cyanA400 = Color(hex: 0x00E5FF)! /// SwifterSwift: hex #00B8D4 public static let cyanA700 = Color(hex: 0x00B8D4)! /// SwifterSwift: color teal500 public static let teal = teal500 /// SwifterSwift: hex #E0F2F1 public static let teal50 = Color(hex: 0xE0F2F1)! /// SwifterSwift: hex #B2DFDB public static let teal100 = Color(hex: 0xB2DFDB)! /// SwifterSwift: hex #80CBC4 public static let teal200 = Color(hex: 0x80CBC4)! /// SwifterSwift: hex #4DB6AC public static let teal300 = Color(hex: 0x4DB6AC)! /// SwifterSwift: hex #26A69A public static let teal400 = Color(hex: 0x26A69A)! /// SwifterSwift: hex #009688 public static let teal500 = Color(hex: 0x009688)! /// SwifterSwift: hex #00897B public static let teal600 = Color(hex: 0x00897B)! /// SwifterSwift: hex #00796B public static let teal700 = Color(hex: 0x00796B)! /// SwifterSwift: hex #00695C public static let teal800 = Color(hex: 0x00695C)! /// SwifterSwift: hex #004D40 public static let teal900 = Color(hex: 0x004D40)! /// SwifterSwift: hex #A7FFEB public static let tealA100 = Color(hex: 0xA7FFEB)! /// SwifterSwift: hex #64FFDA public static let tealA200 = Color(hex: 0x64FFDA)! /// SwifterSwift: hex #1DE9B6 public static let tealA400 = Color(hex: 0x1DE9B6)! /// SwifterSwift: hex #00BFA5 public static let tealA700 = Color(hex: 0x00BFA5)! /// SwifterSwift: color green500 public static let green = green500 /// SwifterSwift: hex #E8F5E9 public static let green50 = Color(hex: 0xE8F5E9)! /// SwifterSwift: hex #C8E6C9 public static let green100 = Color(hex: 0xC8E6C9)! /// SwifterSwift: hex #A5D6A7 public static let green200 = Color(hex: 0xA5D6A7)! /// SwifterSwift: hex #81C784 public static let green300 = Color(hex: 0x81C784)! /// SwifterSwift: hex #66BB6A public static let green400 = Color(hex: 0x66BB6A)! /// SwifterSwift: hex #4CAF50 public static let green500 = Color(hex: 0x4CAF50)! /// SwifterSwift: hex #43A047 public static let green600 = Color(hex: 0x43A047)! /// SwifterSwift: hex #388E3C public static let green700 = Color(hex: 0x388E3C)! /// SwifterSwift: hex #2E7D32 public static let green800 = Color(hex: 0x2E7D32)! /// SwifterSwift: hex #1B5E20 public static let green900 = Color(hex: 0x1B5E20)! /// SwifterSwift: hex #B9F6CA public static let greenA100 = Color(hex: 0xB9F6CA)! /// SwifterSwift: hex #69F0AE public static let greenA200 = Color(hex: 0x69F0AE)! /// SwifterSwift: hex #00E676 public static let greenA400 = Color(hex: 0x00E676)! /// SwifterSwift: hex #00C853 public static let greenA700 = Color(hex: 0x00C853)! /// SwifterSwift: color lightGreen500 public static let lightGreen = lightGreen500 /// SwifterSwift: hex #F1F8E9 public static let lightGreen50 = Color(hex: 0xF1F8E9)! /// SwifterSwift: hex #DCEDC8 public static let lightGreen100 = Color(hex: 0xDCEDC8)! /// SwifterSwift: hex #C5E1A5 public static let lightGreen200 = Color(hex: 0xC5E1A5)! /// SwifterSwift: hex #AED581 public static let lightGreen300 = Color(hex: 0xAED581)! /// SwifterSwift: hex #9CCC65 public static let lightGreen400 = Color(hex: 0x9CCC65)! /// SwifterSwift: hex #8BC34A public static let lightGreen500 = Color(hex: 0x8BC34A)! /// SwifterSwift: hex #7CB342 public static let lightGreen600 = Color(hex: 0x7CB342)! /// SwifterSwift: hex #689F38 public static let lightGreen700 = Color(hex: 0x689F38)! /// SwifterSwift: hex #558B2F public static let lightGreen800 = Color(hex: 0x558B2F)! /// SwifterSwift: hex #33691E public static let lightGreen900 = Color(hex: 0x33691E)! /// SwifterSwift: hex #CCFF90 public static let lightGreenA100 = Color(hex: 0xCCFF90)! /// SwifterSwift: hex #B2FF59 public static let lightGreenA200 = Color(hex: 0xB2FF59)! /// SwifterSwift: hex #76FF03 public static let lightGreenA400 = Color(hex: 0x76FF03)! /// SwifterSwift: hex #64DD17 public static let lightGreenA700 = Color(hex: 0x64DD17)! /// SwifterSwift: color lime500 public static let lime = lime500 /// SwifterSwift: hex #F9FBE7 public static let lime50 = Color(hex: 0xF9FBE7)! /// SwifterSwift: hex #F0F4C3 public static let lime100 = Color(hex: 0xF0F4C3)! /// SwifterSwift: hex #E6EE9C public static let lime200 = Color(hex: 0xE6EE9C)! /// SwifterSwift: hex #DCE775 public static let lime300 = Color(hex: 0xDCE775)! /// SwifterSwift: hex #D4E157 public static let lime400 = Color(hex: 0xD4E157)! /// SwifterSwift: hex #CDDC39 public static let lime500 = Color(hex: 0xCDDC39)! /// SwifterSwift: hex #C0CA33 public static let lime600 = Color(hex: 0xC0CA33)! /// SwifterSwift: hex #AFB42B public static let lime700 = Color(hex: 0xAFB42B)! /// SwifterSwift: hex #9E9D24 public static let lime800 = Color(hex: 0x9E9D24)! /// SwifterSwift: hex #827717 public static let lime900 = Color(hex: 0x827717)! /// SwifterSwift: hex #F4FF81 public static let limeA100 = Color(hex: 0xF4FF81)! /// SwifterSwift: hex #EEFF41 public static let limeA200 = Color(hex: 0xEEFF41)! /// SwifterSwift: hex #C6FF00 public static let limeA400 = Color(hex: 0xC6FF00)! /// SwifterSwift: hex #AEEA00 public static let limeA700 = Color(hex: 0xAEEA00)! /// SwifterSwift: color yellow500 public static let yellow = yellow500 /// SwifterSwift: hex #FFFDE7 public static let yellow50 = Color(hex: 0xFFFDE7)! /// SwifterSwift: hex #FFF9C4 public static let yellow100 = Color(hex: 0xFFF9C4)! /// SwifterSwift: hex #FFF59D public static let yellow200 = Color(hex: 0xFFF59D)! /// SwifterSwift: hex #FFF176 public static let yellow300 = Color(hex: 0xFFF176)! /// SwifterSwift: hex #FFEE58 public static let yellow400 = Color(hex: 0xFFEE58)! /// SwifterSwift: hex #FFEB3B public static let yellow500 = Color(hex: 0xFFEB3B)! /// SwifterSwift: hex #FDD835 public static let yellow600 = Color(hex: 0xFDD835)! /// SwifterSwift: hex #FBC02D public static let yellow700 = Color(hex: 0xFBC02D)! /// SwifterSwift: hex #F9A825 public static let yellow800 = Color(hex: 0xF9A825)! /// SwifterSwift: hex #F57F17 public static let yellow900 = Color(hex: 0xF57F17)! /// SwifterSwift: hex #FFFF8D public static let yellowA100 = Color(hex: 0xFFFF8D)! /// SwifterSwift: hex #FFFF00 public static let yellowA200 = Color(hex: 0xFFFF00)! /// SwifterSwift: hex #FFEA00 public static let yellowA400 = Color(hex: 0xFFEA00)! /// SwifterSwift: hex #FFD600 public static let yellowA700 = Color(hex: 0xFFD600)! /// SwifterSwift: color amber500 public static let amber = amber500 /// SwifterSwift: hex #FFF8E1 public static let amber50 = Color(hex: 0xFFF8E1)! /// SwifterSwift: hex #FFECB3 public static let amber100 = Color(hex: 0xFFECB3)! /// SwifterSwift: hex #FFE082 public static let amber200 = Color(hex: 0xFFE082)! /// SwifterSwift: hex #FFD54F public static let amber300 = Color(hex: 0xFFD54F)! /// SwifterSwift: hex #FFCA28 public static let amber400 = Color(hex: 0xFFCA28)! /// SwifterSwift: hex #FFC107 public static let amber500 = Color(hex: 0xFFC107)! /// SwifterSwift: hex #FFB300 public static let amber600 = Color(hex: 0xFFB300)! /// SwifterSwift: hex #FFA000 public static let amber700 = Color(hex: 0xFFA000)! /// SwifterSwift: hex #FF8F00 public static let amber800 = Color(hex: 0xFF8F00)! /// SwifterSwift: hex #FF6F00 public static let amber900 = Color(hex: 0xFF6F00)! /// SwifterSwift: hex #FFE57F public static let amberA100 = Color(hex: 0xFFE57F)! /// SwifterSwift: hex #FFD740 public static let amberA200 = Color(hex: 0xFFD740)! /// SwifterSwift: hex #FFC400 public static let amberA400 = Color(hex: 0xFFC400)! /// SwifterSwift: hex #FFAB00 public static let amberA700 = Color(hex: 0xFFAB00)! /// SwifterSwift: color orange500 public static let orange = orange500 /// SwifterSwift: hex #FFF3E0 public static let orange50 = Color(hex: 0xFFF3E0)! /// SwifterSwift: hex #FFE0B2 public static let orange100 = Color(hex: 0xFFE0B2)! /// SwifterSwift: hex #FFCC80 public static let orange200 = Color(hex: 0xFFCC80)! /// SwifterSwift: hex #FFB74D public static let orange300 = Color(hex: 0xFFB74D)! /// SwifterSwift: hex #FFA726 public static let orange400 = Color(hex: 0xFFA726)! /// SwifterSwift: hex #FF9800 public static let orange500 = Color(hex: 0xFF9800)! /// SwifterSwift: hex #FB8C00 public static let orange600 = Color(hex: 0xFB8C00)! /// SwifterSwift: hex #F57C00 public static let orange700 = Color(hex: 0xF57C00)! /// SwifterSwift: hex #EF6C00 public static let orange800 = Color(hex: 0xEF6C00)! /// SwifterSwift: hex #E65100 public static let orange900 = Color(hex: 0xE65100)! /// SwifterSwift: hex #FFD180 public static let orangeA100 = Color(hex: 0xFFD180)! /// SwifterSwift: hex #FFAB40 public static let orangeA200 = Color(hex: 0xFFAB40)! /// SwifterSwift: hex #FF9100 public static let orangeA400 = Color(hex: 0xFF9100)! /// SwifterSwift: hex #FF6D00 public static let orangeA700 = Color(hex: 0xFF6D00)! /// SwifterSwift: color deepOrange500 public static let deepOrange = deepOrange500 /// SwifterSwift: hex #FBE9E7 public static let deepOrange50 = Color(hex: 0xFBE9E7)! /// SwifterSwift: hex #FFCCBC public static let deepOrange100 = Color(hex: 0xFFCCBC)! /// SwifterSwift: hex #FFAB91 public static let deepOrange200 = Color(hex: 0xFFAB91)! /// SwifterSwift: hex #FF8A65 public static let deepOrange300 = Color(hex: 0xFF8A65)! /// SwifterSwift: hex #FF7043 public static let deepOrange400 = Color(hex: 0xFF7043)! /// SwifterSwift: hex #FF5722 public static let deepOrange500 = Color(hex: 0xFF5722)! /// SwifterSwift: hex #F4511E public static let deepOrange600 = Color(hex: 0xF4511E)! /// SwifterSwift: hex #E64A19 public static let deepOrange700 = Color(hex: 0xE64A19)! /// SwifterSwift: hex #D84315 public static let deepOrange800 = Color(hex: 0xD84315)! /// SwifterSwift: hex #BF360C public static let deepOrange900 = Color(hex: 0xBF360C)! /// SwifterSwift: hex #FF9E80 public static let deepOrangeA100 = Color(hex: 0xFF9E80)! /// SwifterSwift: hex #FF6E40 public static let deepOrangeA200 = Color(hex: 0xFF6E40)! /// SwifterSwift: hex #FF3D00 public static let deepOrangeA400 = Color(hex: 0xFF3D00)! /// SwifterSwift: hex #DD2C00 public static let deepOrangeA700 = Color(hex: 0xDD2C00)! /// SwifterSwift: color brown500 public static let brown = brown500 /// SwifterSwift: hex #EFEBE9 public static let brown50 = Color(hex: 0xEFEBE9)! /// SwifterSwift: hex #D7CCC8 public static let brown100 = Color(hex: 0xD7CCC8)! /// SwifterSwift: hex #BCAAA4 public static let brown200 = Color(hex: 0xBCAAA4)! /// SwifterSwift: hex #A1887F public static let brown300 = Color(hex: 0xA1887F)! /// SwifterSwift: hex #8D6E63 public static let brown400 = Color(hex: 0x8D6E63)! /// SwifterSwift: hex #795548 public static let brown500 = Color(hex: 0x795548)! /// SwifterSwift: hex #6D4C41 public static let brown600 = Color(hex: 0x6D4C41)! /// SwifterSwift: hex #5D4037 public static let brown700 = Color(hex: 0x5D4037)! /// SwifterSwift: hex #4E342E public static let brown800 = Color(hex: 0x4E342E)! /// SwifterSwift: hex #3E2723 public static let brown900 = Color(hex: 0x3E2723)! /// SwifterSwift: color grey500 public static let grey = grey500 /// SwifterSwift: hex #FAFAFA public static let grey50 = Color(hex: 0xFAFAFA)! /// SwifterSwift: hex #F5F5F5 public static let grey100 = Color(hex: 0xF5F5F5)! /// SwifterSwift: hex #EEEEEE public static let grey200 = Color(hex: 0xEEEEEE)! /// SwifterSwift: hex #E0E0E0 public static let grey300 = Color(hex: 0xE0E0E0)! /// SwifterSwift: hex #BDBDBD public static let grey400 = Color(hex: 0xBDBDBD)! /// SwifterSwift: hex #9E9E9E public static let grey500 = Color(hex: 0x9E9E9E)! /// SwifterSwift: hex #757575 public static let grey600 = Color(hex: 0x757575)! /// SwifterSwift: hex #616161 public static let grey700 = Color(hex: 0x616161)! /// SwifterSwift: hex #424242 public static let grey800 = Color(hex: 0x424242)! /// SwifterSwift: hex #212121 public static let grey900 = Color(hex: 0x212121)! /// SwifterSwift: color blueGrey500 public static let blueGrey = blueGrey500 /// SwifterSwift: hex #ECEFF1 public static let blueGrey50 = Color(hex: 0xECEFF1)! /// SwifterSwift: hex #CFD8DC public static let blueGrey100 = Color(hex: 0xCFD8DC)! /// SwifterSwift: hex #B0BEC5 public static let blueGrey200 = Color(hex: 0xB0BEC5)! /// SwifterSwift: hex #90A4AE public static let blueGrey300 = Color(hex: 0x90A4AE)! /// SwifterSwift: hex #78909C public static let blueGrey400 = Color(hex: 0x78909C)! /// SwifterSwift: hex #607D8B public static let blueGrey500 = Color(hex: 0x607D8B)! /// SwifterSwift: hex #546E7A public static let blueGrey600 = Color(hex: 0x546E7A)! /// SwifterSwift: hex #455A64 public static let blueGrey700 = Color(hex: 0x455A64)! /// SwifterSwift: hex #37474F public static let blueGrey800 = Color(hex: 0x37474F)! /// SwifterSwift: hex #263238 public static let blueGrey900 = Color(hex: 0x263238)! /// SwifterSwift: hex #000000 public static let black = Color(hex: 0x000000)! /// SwifterSwift: hex #FFFFFF public static let white = Color(hex: 0xFFFFFF)! } } // MARK: - CSS colors public extension Color { /// SwifterSwift: CSS colors. public struct CSS { // http://www.w3schools.com/colors/colors_names.asp /// SwifterSwift: hex #F0F8FF public static let aliceBlue = Color(hex: 0xF0F8FF)! /// SwifterSwift: hex #FAEBD7 public static let antiqueWhite = Color(hex: 0xFAEBD7)! /// SwifterSwift: hex #00FFFF public static let aqua = Color(hex: 0x00FFFF)! /// SwifterSwift: hex #7FFFD4 public static let aquamarine = Color(hex: 0x7FFFD4)! /// SwifterSwift: hex #F0FFFF public static let azure = Color(hex: 0xF0FFFF)! /// SwifterSwift: hex #F5F5DC public static let beige = Color(hex: 0xF5F5DC)! /// SwifterSwift: hex #FFE4C4 public static let bisque = Color(hex: 0xFFE4C4)! /// SwifterSwift: hex #000000 public static let black = Color(hex: 0x000000)! /// SwifterSwift: hex #FFEBCD public static let blanchedAlmond = Color(hex: 0xFFEBCD)! /// SwifterSwift: hex #0000FF public static let blue = Color(hex: 0x0000FF)! /// SwifterSwift: hex #8A2BE2 public static let blueViolet = Color(hex: 0x8A2BE2)! /// SwifterSwift: hex #A52A2A public static let brown = Color(hex: 0xA52A2A)! /// SwifterSwift: hex #DEB887 public static let burlyWood = Color(hex: 0xDEB887)! /// SwifterSwift: hex #5F9EA0 public static let cadetBlue = Color(hex: 0x5F9EA0)! /// SwifterSwift: hex #7FFF00 public static let chartreuse = Color(hex: 0x7FFF00)! /// SwifterSwift: hex #D2691E public static let chocolate = Color(hex: 0xD2691E)! /// SwifterSwift: hex #FF7F50 public static let coral = Color(hex: 0xFF7F50)! /// SwifterSwift: hex #6495ED public static let cornflowerBlue = Color(hex: 0x6495ED)! /// SwifterSwift: hex #FFF8DC public static let cornsilk = Color(hex: 0xFFF8DC)! /// SwifterSwift: hex #DC143C public static let crimson = Color(hex: 0xDC143C)! /// SwifterSwift: hex #00FFFF public static let cyan = Color(hex: 0x00FFFF)! /// SwifterSwift: hex #00008B public static let darkBlue = Color(hex: 0x00008B)! /// SwifterSwift: hex #008B8B public static let darkCyan = Color(hex: 0x008B8B)! /// SwifterSwift: hex #B8860B public static let darkGoldenRod = Color(hex: 0xB8860B)! /// SwifterSwift: hex #A9A9A9 public static let darkGray = Color(hex: 0xA9A9A9)! /// SwifterSwift: hex #A9A9A9 public static let darkGrey = Color(hex: 0xA9A9A9)! /// SwifterSwift: hex #006400 public static let darkGreen = Color(hex: 0x006400)! /// SwifterSwift: hex #BDB76B public static let darkKhaki = Color(hex: 0xBDB76B)! /// SwifterSwift: hex #8B008B public static let darkMagenta = Color(hex: 0x8B008B)! /// SwifterSwift: hex #556B2F public static let darkOliveGreen = Color(hex: 0x556B2F)! /// SwifterSwift: hex #FF8C00 public static let darkOrange = Color(hex: 0xFF8C00)! /// SwifterSwift: hex #9932CC public static let darkOrchid = Color(hex: 0x9932CC)! /// SwifterSwift: hex #8B0000 public static let darkRed = Color(hex: 0x8B0000)! /// SwifterSwift: hex #E9967A public static let darkSalmon = Color(hex: 0xE9967A)! /// SwifterSwift: hex #8FBC8F public static let darkSeaGreen = Color(hex: 0x8FBC8F)! /// SwifterSwift: hex #483D8B public static let darkSlateBlue = Color(hex: 0x483D8B)! /// SwifterSwift: hex #2F4F4F public static let darkSlateGray = Color(hex: 0x2F4F4F)! /// SwifterSwift: hex #2F4F4F public static let darkSlateGrey = Color(hex: 0x2F4F4F)! /// SwifterSwift: hex #00CED1 public static let darkTurquoise = Color(hex: 0x00CED1)! /// SwifterSwift: hex #9400D3 public static let darkViolet = Color(hex: 0x9400D3)! /// SwifterSwift: hex #FF1493 public static let deepPink = Color(hex: 0xFF1493)! /// SwifterSwift: hex #00BFFF public static let deepSkyBlue = Color(hex: 0x00BFFF)! /// SwifterSwift: hex #696969 public static let dimGray = Color(hex: 0x696969)! /// SwifterSwift: hex #696969 public static let dimGrey = Color(hex: 0x696969)! /// SwifterSwift: hex #1E90FF public static let dodgerBlue = Color(hex: 0x1E90FF)! /// SwifterSwift: hex #B22222 public static let fireBrick = Color(hex: 0xB22222)! /// SwifterSwift: hex #FFFAF0 public static let floralWhite = Color(hex: 0xFFFAF0)! /// SwifterSwift: hex #228B22 public static let forestGreen = Color(hex: 0x228B22)! /// SwifterSwift: hex #FF00FF public static let fuchsia = Color(hex: 0xFF00FF)! /// SwifterSwift: hex #DCDCDC public static let gainsboro = Color(hex: 0xDCDCDC)! /// SwifterSwift: hex #F8F8FF public static let ghostWhite = Color(hex: 0xF8F8FF)! /// SwifterSwift: hex #FFD700 public static let gold = Color(hex: 0xFFD700)! /// SwifterSwift: hex #DAA520 public static let goldenRod = Color(hex: 0xDAA520)! /// SwifterSwift: hex #808080 public static let gray = Color(hex: 0x808080)! /// SwifterSwift: hex #808080 public static let grey = Color(hex: 0x808080)! /// SwifterSwift: hex #008000 public static let green = Color(hex: 0x008000)! /// SwifterSwift: hex #ADFF2F public static let greenYellow = Color(hex: 0xADFF2F)! /// SwifterSwift: hex #F0FFF0 public static let honeyDew = Color(hex: 0xF0FFF0)! /// SwifterSwift: hex #FF69B4 public static let hotPink = Color(hex: 0xFF69B4)! /// SwifterSwift: hex #CD5C5C public static let indianRed = Color(hex: 0xCD5C5C)! /// SwifterSwift: hex #4B0082 public static let indigo = Color(hex: 0x4B0082)! /// SwifterSwift: hex #FFFFF0 public static let ivory = Color(hex: 0xFFFFF0)! /// SwifterSwift: hex #F0E68C public static let khaki = Color(hex: 0xF0E68C)! /// SwifterSwift: hex #E6E6FA public static let lavender = Color(hex: 0xE6E6FA)! /// SwifterSwift: hex #FFF0F5 public static let lavenderBlush = Color(hex: 0xFFF0F5)! /// SwifterSwift: hex #7CFC00 public static let lawnGreen = Color(hex: 0x7CFC00)! /// SwifterSwift: hex #FFFACD public static let lemonChiffon = Color(hex: 0xFFFACD)! /// SwifterSwift: hex #ADD8E6 public static let lightBlue = Color(hex: 0xADD8E6)! /// SwifterSwift: hex #F08080 public static let lightCoral = Color(hex: 0xF08080)! /// SwifterSwift: hex #E0FFFF public static let lightCyan = Color(hex: 0xE0FFFF)! /// SwifterSwift: hex #FAFAD2 public static let lightGoldenRodYellow = Color(hex: 0xFAFAD2)! /// SwifterSwift: hex #D3D3D3 public static let lightGray = Color(hex: 0xD3D3D3)! /// SwifterSwift: hex #D3D3D3 public static let lightGrey = Color(hex: 0xD3D3D3)! /// SwifterSwift: hex #90EE90 public static let lightGreen = Color(hex: 0x90EE90)! /// SwifterSwift: hex #FFB6C1 public static let lightPink = Color(hex: 0xFFB6C1)! /// SwifterSwift: hex #FFA07A public static let lightSalmon = Color(hex: 0xFFA07A)! /// SwifterSwift: hex #20B2AA public static let lightSeaGreen = Color(hex: 0x20B2AA)! /// SwifterSwift: hex #87CEFA public static let lightSkyBlue = Color(hex: 0x87CEFA)! /// SwifterSwift: hex #778899 public static let lightSlateGray = Color(hex: 0x778899)! /// SwifterSwift: hex #778899 public static let lightSlateGrey = Color(hex: 0x778899)! /// SwifterSwift: hex #B0C4DE public static let lightSteelBlue = Color(hex: 0xB0C4DE)! /// SwifterSwift: hex #FFFFE0 public static let lightYellow = Color(hex: 0xFFFFE0)! /// SwifterSwift: hex #00FF00 public static let lime = Color(hex: 0x00FF00)! /// SwifterSwift: hex #32CD32 public static let limeGreen = Color(hex: 0x32CD32)! /// SwifterSwift: hex #FAF0E6 public static let linen = Color(hex: 0xFAF0E6)! /// SwifterSwift: hex #FF00FF public static let magenta = Color(hex: 0xFF00FF)! /// SwifterSwift: hex #800000 public static let maroon = Color(hex: 0x800000)! /// SwifterSwift: hex #66CDAA public static let mediumAquaMarine = Color(hex: 0x66CDAA)! /// SwifterSwift: hex #0000CD public static let mediumBlue = Color(hex: 0x0000CD)! /// SwifterSwift: hex #BA55D3 public static let mediumOrchid = Color(hex: 0xBA55D3)! /// SwifterSwift: hex #9370DB public static let mediumPurple = Color(hex: 0x9370DB)! /// SwifterSwift: hex #3CB371 public static let mediumSeaGreen = Color(hex: 0x3CB371)! /// SwifterSwift: hex #7B68EE public static let mediumSlateBlue = Color(hex: 0x7B68EE)! /// SwifterSwift: hex #00FA9A public static let mediumSpringGreen = Color(hex: 0x00FA9A)! /// SwifterSwift: hex #48D1CC public static let mediumTurquoise = Color(hex: 0x48D1CC)! /// SwifterSwift: hex #C71585 public static let mediumVioletRed = Color(hex: 0xC71585)! /// SwifterSwift: hex #191970 public static let midnightBlue = Color(hex: 0x191970)! /// SwifterSwift: hex #F5FFFA public static let mintCream = Color(hex: 0xF5FFFA)! /// SwifterSwift: hex #FFE4E1 public static let mistyRose = Color(hex: 0xFFE4E1)! /// SwifterSwift: hex #FFE4B5 public static let moccasin = Color(hex: 0xFFE4B5)! /// SwifterSwift: hex #FFDEAD public static let navajoWhite = Color(hex: 0xFFDEAD)! /// SwifterSwift: hex #000080 public static let navy = Color(hex: 0x000080)! /// SwifterSwift: hex #FDF5E6 public static let oldLace = Color(hex: 0xFDF5E6)! /// SwifterSwift: hex #808000 public static let olive = Color(hex: 0x808000)! /// SwifterSwift: hex #6B8E23 public static let oliveDrab = Color(hex: 0x6B8E23)! /// SwifterSwift: hex #FFA500 public static let orange = Color(hex: 0xFFA500)! /// SwifterSwift: hex #FF4500 public static let orangeRed = Color(hex: 0xFF4500)! /// SwifterSwift: hex #DA70D6 public static let orchid = Color(hex: 0xDA70D6)! /// SwifterSwift: hex #EEE8AA public static let paleGoldenRod = Color(hex: 0xEEE8AA)! /// SwifterSwift: hex #98FB98 public static let paleGreen = Color(hex: 0x98FB98)! /// SwifterSwift: hex #AFEEEE public static let paleTurquoise = Color(hex: 0xAFEEEE)! /// SwifterSwift: hex #DB7093 public static let paleVioletRed = Color(hex: 0xDB7093)! /// SwifterSwift: hex #FFEFD5 public static let papayaWhip = Color(hex: 0xFFEFD5)! /// SwifterSwift: hex #FFDAB9 public static let peachPuff = Color(hex: 0xFFDAB9)! /// SwifterSwift: hex #CD853F public static let peru = Color(hex: 0xCD853F)! /// SwifterSwift: hex #FFC0CB public static let pink = Color(hex: 0xFFC0CB)! /// SwifterSwift: hex #DDA0DD public static let plum = Color(hex: 0xDDA0DD)! /// SwifterSwift: hex #B0E0E6 public static let powderBlue = Color(hex: 0xB0E0E6)! /// SwifterSwift: hex #800080 public static let purple = Color(hex: 0x800080)! /// SwifterSwift: hex #663399 public static let rebeccaPurple = Color(hex: 0x663399)! /// SwifterSwift: hex #FF0000 public static let red = Color(hex: 0xFF0000)! /// SwifterSwift: hex #BC8F8F public static let rosyBrown = Color(hex: 0xBC8F8F)! /// SwifterSwift: hex #4169E1 public static let royalBlue = Color(hex: 0x4169E1)! /// SwifterSwift: hex #8B4513 public static let saddleBrown = Color(hex: 0x8B4513)! /// SwifterSwift: hex #FA8072 public static let salmon = Color(hex: 0xFA8072)! /// SwifterSwift: hex #F4A460 public static let sandyBrown = Color(hex: 0xF4A460)! /// SwifterSwift: hex #2E8B57 public static let seaGreen = Color(hex: 0x2E8B57)! /// SwifterSwift: hex #FFF5EE public static let seaShell = Color(hex: 0xFFF5EE)! /// SwifterSwift: hex #A0522D public static let sienna = Color(hex: 0xA0522D)! /// SwifterSwift: hex #C0C0C0 public static let silver = Color(hex: 0xC0C0C0)! /// SwifterSwift: hex #87CEEB public static let skyBlue = Color(hex: 0x87CEEB)! /// SwifterSwift: hex #6A5ACD public static let slateBlue = Color(hex: 0x6A5ACD)! /// SwifterSwift: hex #708090 public static let slateGray = Color(hex: 0x708090)! /// SwifterSwift: hex #708090 public static let slateGrey = Color(hex: 0x708090)! /// SwifterSwift: hex #FFFAFA public static let snow = Color(hex: 0xFFFAFA)! /// SwifterSwift: hex #00FF7F public static let springGreen = Color(hex: 0x00FF7F)! /// SwifterSwift: hex #4682B4 public static let steelBlue = Color(hex: 0x4682B4)! /// SwifterSwift: hex #D2B48C public static let tan = Color(hex: 0xD2B48C)! /// SwifterSwift: hex #008080 public static let teal = Color(hex: 0x008080)! /// SwifterSwift: hex #D8BFD8 public static let thistle = Color(hex: 0xD8BFD8)! /// SwifterSwift: hex #FF6347 public static let tomato = Color(hex: 0xFF6347)! /// SwifterSwift: hex #40E0D0 public static let turquoise = Color(hex: 0x40E0D0)! /// SwifterSwift: hex #EE82EE public static let violet = Color(hex: 0xEE82EE)! /// SwifterSwift: hex #F5DEB3 public static let wheat = Color(hex: 0xF5DEB3)! /// SwifterSwift: hex #FFFFFF public static let white = Color(hex: 0xFFFFFF)! /// SwifterSwift: hex #F5F5F5 public static let whiteSmoke = Color(hex: 0xF5F5F5)! /// SwifterSwift: hex #FFFF00 public static let yellow = Color(hex: 0xFFFF00)! /// SwifterSwift: hex #9ACD32 public static let yellowGreen = Color(hex: 0x9ACD32)! } } // MARK: - Flat UI colors public extension Color { /// SwifterSwift: Flat UI colors public struct FlatUI { // http://flatuicolors.com. /// SwifterSwift: hex #1ABC9C public static let turquoise = Color(hex: 0x1ABC9C)! /// SwifterSwift: hex #16A085 public static let greenSea = Color(hex: 0x16A085)! /// SwifterSwift: hex #2ECC71 public static let emerald = Color(hex: 0x2ECC71)! /// SwifterSwift: hex #27AE60 public static let nephritis = Color(hex: 0x27AE60)! /// SwifterSwift: hex #3498DB public static let peterRiver = Color(hex: 0x3498DB)! /// SwifterSwift: hex #2980B9 public static let belizeHole = Color(hex: 0x2980B9)! /// SwifterSwift: hex #9B59B6 public static let amethyst = Color(hex: 0x9B59B6)! /// SwifterSwift: hex #8E44AD public static let wisteria = Color(hex: 0x8E44AD)! /// SwifterSwift: hex #34495E public static let wetAsphalt = Color(hex: 0x34495E)! /// SwifterSwift: hex #2C3E50 public static let midnightBlue = Color(hex: 0x2C3E50)! /// SwifterSwift: hex #F1C40F public static let sunFlower = Color(hex: 0xF1C40F)! /// SwifterSwift: hex #F39C12 public static let flatOrange = Color(hex: 0xF39C12)! /// SwifterSwift: hex #E67E22 public static let carrot = Color(hex: 0xE67E22)! /// SwifterSwift: hex #D35400 public static let pumkin = Color(hex: 0xD35400)! /// SwifterSwift: hex #E74C3C public static let alizarin = Color(hex: 0xE74C3C)! /// SwifterSwift: hex #C0392B public static let pomegranate = Color(hex: 0xC0392B)! /// SwifterSwift: hex #ECF0F1 public static let clouds = Color(hex: 0xECF0F1)! /// SwifterSwift: hex #BDC3C7 public static let silver = Color(hex: 0xBDC3C7)! /// SwifterSwift: hex #7F8C8D public static let asbestos = Color(hex: 0x7F8C8D)! /// SwifterSwift: hex #95A5A6 public static let concerte = Color(hex: 0x95A5A6)! } } #endif
mit
29b913580d513601e6f2ef0c58307e99
36.270687
125
0.546877
3.985269
false
false
false
false
TG908/iOS
TUM Campus App/BulkRequest.swift
1
777
// // BulkRequest.swift // TUM Campus App // // Created by Mathias Quintero on 12/6/15. // Copyright © 2015 LS1 TUM. All rights reserved. // import Foundation class BulkRequest: TumDataReceiver { var receiver: TumDataReceiver? let sorter: DataSorter? typealias DataSorter = (DataElement) -> (Int) init(receiver: TumDataReceiver, sorter: DataSorter? = nil) { self.receiver = receiver self.sorter = sorter } var data = [DataElement]() func receiveData(_ data: [DataElement]) { self.data.append(contentsOf: data) if let sorter = sorter { self.data.sort { return sorter($0) < sorter($1) } } receiver?.receiveData(self.data) } }
gpl-3.0
64ab5d4d0e417ac797f40b5953b52b94
21.171429
64
0.585052
3.959184
false
false
false
false
kaideyi/KDYSample
Charting/Charting/ViewController.swift
1
1655
// // ViewController.swift // Charting // // Created by kaideyi on 2017/3/5. // Copyright © 2017年 kaideyi.com. All rights reserved. // import UIKit class ViewController: UIViewController { public lazy var tableView: UITableView = { let tb = UITableView() tb.frame = CGRect(x: 0, y: 0, width: self.view.width, height: self.view.height) tb.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "cell") tb.tableFooterView = UIView() tb.dataSource = self tb.delegate = self self.view.addSubview(tb) return tb }() var data: NSArray = ["1.柱形图", "2.折线图", "3.饼状图"] override func viewDidLoad() { super.viewDidLoad() self.title = "Charting" tableView.reloadData() } } // MARK: - extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = data[indexPath.row] as? String return cell } } extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let controller = SubViewController(indexPath.row) self.navigationController?.pushViewController(controller, animated: true) } }
mit
b4c507fc6c187272ae9bf1bce0b5a21a
28.178571
100
0.653611
4.489011
false
false
false
false
MikeEmery/Swift-iOS-Rotten-Tomatoes
SwiftTomatoes/MovieListViewController.swift
1
2544
// // MovieListViewController.swift // SwiftTomatoes // // Created by Michael Emery on 6/11/14. // Copyright (c) 2014 Michael Emery. All rights reserved. // import UIKit class MovieListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var movieList = MovieList() let operationQueue = NSOperationQueue(); @IBOutlet var movieListTableView : UITableView init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) println("lousy piece of junk") } override func viewDidLoad() { super.viewDidLoad() var customNib = UINib(nibName: "MovieEntryTableViewCell", bundle: nil) self.movieListTableView.registerNib(customNib, forCellReuseIdentifier: "foo") println("loaded"); self.loadMoviesFromNetwork() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let rows = self.movieList.size() return rows } func tableView(tableView: UITableView, didSelectRowAtIndexPath: NSIndexPath?) { let movie = self.movieList.get(didSelectRowAtIndexPath!.item) let movieDetail = MovieDetailViewController(movie: movie) self.navigationController.pushViewController(movieDetail, animated: true) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("foo", forIndexPath: indexPath) as MovieEntryTableViewCell let movie = movieList.get(indexPath.item) cell.titleLabelView.text = movie.title cell.thumnailUrl = movie.thumbnailUrl return cell; } func loadMoviesFromNetwork() { let url = "http://api.rottentomatoes.com/api/public/v1.0/lists/dvds/top_rentals.json?apikey=" let request = NSURLRequest(URL: NSURL(string: url)) NSURLConnection.sendAsynchronousRequest(request, queue: self.operationQueue, completionHandler: {(response, data, error) in self.movieList = MovieList(jsonData: data) dispatch_async(dispatch_get_main_queue(), { self.movieListTableView.reloadData() }) println("I kill you scum") }); } }
mit
dd94b2ff5fcea776ed73fa58e2d1f74a
32.038961
131
0.689465
4.959064
false
false
false
false
luckymore0520/GreenTea
Loyalty/Protocal/ViewControllerPresentable.swift
1
1297
// // ViewControllerPresentable.swift // Loyalty // // Created by WangKun on 16/4/18. // Copyright © 2016年 WangKun. All rights reserved. // import Foundation import UIKit //定义协议 protocol ViewControllerPresentable { func configureNavigationItem() } //协议扩展且限定遵循协议的是一个UIViewController extension ViewControllerPresentable where Self:UIViewController{ func configureNavigationItem(){ let leftButton = CancelButton.init(frame:CGRectMake(0, 0, 100, 40)) leftButton.setTitle("取消", forState: UIControlState.Normal) leftButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) leftButton.addTarget(leftButton, action: #selector(CancelButton.onCancelButtonClicked), forControlEvents: UIControlEvents.TouchUpInside) leftButton.titleLabel?.font = UIFont.systemFontOfSize(UIFont.systemFontSize()) leftButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left let leftBarBarItem = UIBarButtonItem.init(customView: leftButton) self.navigationItem.leftBarButtonItems = [leftBarBarItem] } } class CancelButton:UIButton { func onCancelButtonClicked(){ self.viewController()?.dismissViewControllerAnimated(true, completion: nil) } }
mit
a4154cfbcf02fdfbe51378cd60a05262
33.777778
144
0.761981
5.008
false
true
false
false
inloop/qlplayground
QLPlayground/QLPlayground/PreviewBuilder.swift
1
3613
// // PreviewBuilder.swift // QLPlayground // // Created by Jakub Petrík on 10/7/15. // Copyright © 2015 Inloop, s.r.o. All rights reserved. // import Foundation import QuickLook private extension NSData { convenience init(contentsOfResource resource: String, inBundle bundle: NSBundle) { if let resourceURL = bundle.URLForResource(resource, withExtension: nil) { self.init(contentsOfURL: resourceURL)! } else { self.init() } } } private extension String { var cid: String { return "cid:" + self } } @objc public class PreviewBuilder: NSObject { private let url: NSURL private let bundle = NSBundle(forClass: PreviewBuilder.self) private struct Attachment { static let coreCss = "shCore.css" static let themeCss = "theme.css" static let coreJs = "shCore.js" static let brushJs = "brush.js" } private struct MimeType { static let js = "text/javascript" static let css = "text/css" } public var resourceURL: NSURL? { return bundle.resourceURL } public init(url: NSURL) { self.url = url } private func buildData(useCid: Bool) -> CFDataRef? { guard let formatPath = bundle.pathForResource("format", ofType: "html"), let format = try? String(contentsOfFile: formatPath, encoding: NSUTF8StringEncoding) else { return nil } let source = PlaygroundParser.parsePlaygroundAtURL(url) let html: NSString if useCid { html = NSString(format: format, Attachment.coreCss.cid, Attachment.themeCss.cid, source, Attachment.coreJs.cid, Attachment.brushJs.cid) } else { html = NSString(format: format, Attachment.coreCss, Attachment.themeCss, source, Attachment.coreJs, Attachment.brushJs) } if let data = html.dataUsingEncoding(NSUTF8StringEncoding) { return data } return nil } public func buildDataForPreview() -> CFDataRef? { return buildData(true) as CFDataRef? } public func buildDataForThumbnail() -> NSData? { return buildData(false) } public func buildPreviewProperties() -> CFDictionaryRef { return [ kQLPreviewPropertyTextEncodingNameKey as String : "UTF-8", kQLPreviewPropertyMIMETypeKey as String : "text/html", kQLPreviewPropertyAttachmentsKey as String : [ Attachment.coreCss : [ kQLPreviewPropertyMIMETypeKey as String: MimeType.css, kQLPreviewPropertyAttachmentDataKey as String: NSData(contentsOfResource: Attachment.coreCss, inBundle: bundle) ], Attachment.themeCss : [ kQLPreviewPropertyMIMETypeKey as String: MimeType.css, kQLPreviewPropertyAttachmentDataKey as String: NSData(contentsOfResource: Attachment.themeCss, inBundle: bundle) ], Attachment.coreJs : [ kQLPreviewPropertyMIMETypeKey as String: MimeType.js, kQLPreviewPropertyAttachmentDataKey as String: NSData(contentsOfResource: Attachment.coreJs, inBundle: bundle) ], Attachment.brushJs : [ kQLPreviewPropertyMIMETypeKey as String: MimeType.js, kQLPreviewPropertyAttachmentDataKey as String: NSData(contentsOfResource: Attachment.brushJs, inBundle: bundle) ] ] ] as CFDictionaryRef } }
mit
3f994eb95fb616464457cd43d72a139c
31.241071
147
0.621158
4.67141
false
false
false
false
iOS-Connect/PushNotifications
Pods/PusherSwift/Source/PusherPresenceChannel.swift
1
6882
// // PusherPresenceChannel.swift // PusherSwift // // Created by Hamilton Chapman on 01/04/2016. // // public typealias PusherUserInfoObject = [String : AnyObject] open class PusherPresenceChannel: PusherChannel { open var members: [PusherPresenceChannelMember] open var onMemberAdded: ((PusherPresenceChannelMember) -> ())? open var onMemberRemoved: ((PusherPresenceChannelMember) -> ())? open var myId: String? = nil /** Initializes a new PusherPresenceChannel with a given name, conenction, and optional member added and member removed handler functions - parameter name: The name of the channel - parameter connection: The connection that this channel is relevant to - parameter onMemberAdded: A function that will be called with information about the member who has just joined the presence channel - parameter onMemberRemoved: A function that will be called with information about the member who has just left the presence channel - returns: A new PusherPresenceChannel instance */ init( name: String, connection: PusherConnection, onMemberAdded: ((PusherPresenceChannelMember) -> ())? = nil, onMemberRemoved: ((PusherPresenceChannelMember) -> ())? = nil) { self.members = [] self.onMemberAdded = onMemberAdded self.onMemberRemoved = onMemberRemoved super.init(name: name, connection: connection) } /** Add information about the member that has just joined to the members object for the presence channel and call onMemberAdded function, if provided - parameter memberJSON: A dictionary representing the member that has joined the presence channel */ internal func addMember(memberJSON: [String : AnyObject]) { let member: PusherPresenceChannelMember if let userId = memberJSON["user_id"] as? String { if let userInfo = memberJSON["user_info"] as? PusherUserInfoObject { member = PusherPresenceChannelMember(userId: userId, userInfo: userInfo as AnyObject?) } else { member = PusherPresenceChannelMember(userId: userId) } } else { if let userInfo = memberJSON["user_info"] as? PusherUserInfoObject { member = PusherPresenceChannelMember(userId: String.init(describing: memberJSON["user_id"]!), userInfo: userInfo as AnyObject?) } else { member = PusherPresenceChannelMember(userId: String.init(describing: memberJSON["user_id"]!)) } } members.append(member) self.onMemberAdded?(member) } /** Add information about the members that are already subscribed to the presence channel to the members object of the presence channel - parameter memberHash: A dictionary representing the members that were already subscribed to the presence channel */ internal func addExistingMembers(memberHash: [String : AnyObject]) { for (userId, userInfo) in memberHash { let member: PusherPresenceChannelMember if let userInfo = userInfo as? PusherUserInfoObject { member = PusherPresenceChannelMember(userId: userId, userInfo: userInfo as AnyObject?) } else { member = PusherPresenceChannelMember(userId: userId) } self.members.append(member) } } /** Remove information about the member that has just left from the members object for the presence channel and call onMemberRemoved function, if provided - parameter memberJSON: A dictionary representing the member that has left the presence channel */ internal func removeMember(memberJSON: [String : AnyObject]) { let id: String if let userId = memberJSON["user_id"] as? String { id = userId } else { id = String.init(describing: memberJSON["user_id"]!) } if let index = self.members.index(where: { $0.userId == id }) { let member = self.members[index] self.members.remove(at: index) self.onMemberRemoved?(member) } } /** Set the value of myId to the value of the user_id returned as part of the authorization of the subscription to the channel - parameter channelData: The channel data obtained from authorization of the subscription to the channel */ internal func setMyUserId(channelData: String) { if let channelDataObject = parse(channelData: channelData), let userId = channelDataObject["user_id"] { self.myId = String.init(describing: userId) } } /** Parse a string to extract the channel data object from it - parameter channelData: The channel data string received as part of authorization - returns: A dictionary of channel data */ fileprivate func parse(channelData: String) -> [String: AnyObject]? { let data = (channelData as NSString).data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false) do { if let jsonData = data, let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: AnyObject] { return jsonObject } else { print("Unable to parse string: \(channelData)") } } catch let error as NSError { print(error.localizedDescription) } return nil } /** Returns the PusherPresenceChannelMember object for the given user id - parameter userId: The user id of the PusherPresenceChannelMember for whom you want the PusherPresenceChannelMember object - returns: The PusherPresenceChannelMember object for the given user id */ open func findMember(userId: String) -> PusherPresenceChannelMember? { return self.members.filter({ $0.userId == userId }).first } /** Returns the connected user's PusherPresenceChannelMember object - returns: The connected user's PusherPresenceChannelMember object */ open func me() -> PusherPresenceChannelMember? { if let id = self.myId { return findMember(userId: id) } else { return nil } } } public class PusherPresenceChannelMember: NSObject { public let userId: String public let userInfo: Any? public init(userId: String, userInfo: Any? = nil) { self.userId = userId self.userInfo = userInfo } }
mit
2c8610f0f63535882643d8c5888866ec
37.022099
143
0.626417
5.265493
false
false
false
false