repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
fancymax/12306ForMac
12306ForMac/OrderViewControllers/OrderViewController.swift
1
6895
// // OrderViewController.swift // Train12306 // // Created by fancymax on 16/2/16. // Copyright © 2016年 fancy. All rights reserved. // import Cocoa class OrderViewController: BaseViewController{ @IBOutlet weak var orderListTable: NSTableView! @IBOutlet weak var payBtn: NSButton! var hasQuery = false dynamic var hasOrder = false lazy var payWindowController:PayWindowController = PayWindowController() var orderList = [OrderDTO]() override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(recvLogoutNotification(_:)), name: NSNotification.Name.App.DidLogout, object: nil) } override var nibName: String?{ return "OrderViewController" } override func viewDidAppear() { if ((!hasQuery) && (MainModel.isGetUserInfo)) { queryAllOrder() } } @IBAction func clickQueryOrder(_ sender: AnyObject?) { queryAllOrder() } func recvLogoutNotification(_ notification: Notification) { MainModel.noCompleteOrderList.removeAll() self.orderList.removeAll() self.orderListTable.reloadData() self.hasOrder = false } @IBAction func cancelOrder(_ sender: NSButton) { let alert = NSAlert() alert.alertStyle = NSAlertStyle.critical alert.messageText = "您确认取消订单吗?" alert.informativeText = "一天内3次取消订单,当日将不能再网上购票。" alert.addButton(withTitle: "确定") alert.addButton(withTitle: "取消") alert.beginSheetModal(for: self.view.window!, completionHandler: { reponse in if reponse == NSAlertFirstButtonReturn { if let sequence_no = MainModel.noCompleteOrderList[0].sequence_no { self.startLoadingTip("正在取消...") let successHandler = { MainModel.noCompleteOrderList.removeAll() self.orderList = MainModel.historyOrderList self.orderListTable.reloadData() self.stopLoadingTip() self.showTip("取消订单成功") self.hasOrder = false } let failureHandler = {(error:NSError)->() in self.stopLoadingTip() self.showTip(translate(error)) } Service.sharedInstance.cancelOrderWith(sequence_no, success: successHandler, failure:failureHandler) } } }) } @IBAction func payOrder(_ sender: NSButton) { logger.info("-> pay") payWindowController = PayWindowController() if let window = self.view.window { window.beginSheet(payWindowController.window!, completionHandler: {response in if response == NSModalResponseOK{ logger.info("<- pay") self.queryAllOrder() } }) } } func queryHistoryOrder(){ self.startLoadingTip("正在查询...") let successHandler = { self.orderList.append(contentsOf: MainModel.historyOrderList) self.orderListTable.reloadData() self.stopLoadingTip() } let failureHandler = {(error:NSError) -> () in self.stopLoadingTip() self.showTip(translate(error)) } Service.sharedInstance.queryHistoryOrderFlow(success: successHandler, failure: failureHandler) } func queryAllOrder(){ if !MainModel.isGetUserInfo { NotificationCenter.default.post(name: Notification.Name.App.DidLogin, object: nil) return } self.orderList = [OrderDTO]() self.orderListTable.reloadData() hasQuery = true self.startLoadingTip("正在查询...") let successHandler = { self.orderList = MainModel.noCompleteOrderList self.orderListTable.reloadData() self.stopLoadingTip() if self.orderList.count > 0 { self.hasOrder = true } else { self.hasOrder = false } self.queryHistoryOrder() } let failureHandler = { self.stopLoadingTip() self.hasOrder = false } Service.sharedInstance.queryNoCompleteOrderFlow(success: successHandler, failure: failureHandler) } // MARK: - Menu Action override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { if menuItem.action == #selector(clickRefresh(_:)) { return true } if orderList.count == 0 { return false } return true } @IBAction func clickRefresh(_ sender:AnyObject?) { self.queryAllOrder() } @IBAction func clickShareInfo(_ sender:AnyObject?) { let generalPasteboard = NSPasteboard.general() generalPasteboard.clearContents() let ticket = orderList[orderListTable.selectedRow] let shareInfo = "我已预订 \(ticket.start_train_date_page!) \(ticket.station_train_code!) \(ticket.startEndStation) \(ticket.seat_type_name!)(\(ticket.whereToSeat))" generalPasteboard.setString(shareInfo, forType:NSStringPboardType) showTip("车票信息已生成,可复制到其他App") } @IBAction func clickAdd2Calendar(_ sender:AnyObject?){ let ticket = orderList[orderListTable.selectedRow] let eventTitle = "\(ticket.station_train_code!) \(ticket.startEndStation) \(ticket.seat_type_name!)(\(ticket.whereToSeat))" let endDate = ticket.startTrainDate! let startDate = endDate.addingTimeInterval(-7200) let isSuccess = CalendarManager.sharedInstance.createEvent(title:eventTitle,startDate:startDate,endDate:endDate) if !isSuccess { self.showTip("添加日历失败,请到 系统偏好设置->安全性与隐私->隐私->日历 允许本程序的访问权限。") } else { self.showTip("添加日历成功。") } } @IBAction func clickRefund(_ sender:AnyObject?){ } } // MARK: - NSTableViewDataSource extension OrderViewController: NSTableViewDataSource{ func numberOfRows(in tableView: NSTableView) -> Int { return orderList.count } func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? { return orderList[row] } }
mit
efcb15ddcc8e804b1a71c05217c118de
31.38835
168
0.579137
4.997753
false
false
false
false
CoderAlexChan/AlexCocoa
String/String+extension.swift
1
15837
// // NSString+Regex.swift // IMTodo // // Created by 陈文强 on 16/4/5. // Copyright © 2016 CWQ. All rights reserved. // import Foundation import UIKit // MARK: - Length public extension String { /// Returns the length of string. var length: Int { return self.characters.count } /// Returns the length of string. var size: Int { return self.length } /// Returns the length of string. var count: Int { return self.length } } // MARK: - Properties public extension String { /// Check if string contain substring public func contains(subString: String?) -> Bool { guard subString != nil else { return false } return self.range(of: subString!) != nil } /// to pure digit func toPureDigit() -> String { let nonDidgit = NSCharacterSet.decimalDigits.inverted return (self.components(separatedBy: nonDidgit) as NSArray).componentsJoined(by: "") } /// CamelCase of string. public var camelCased: String { let source = lowercased() if source.characters.contains(" ") { let first = source.substring(to: source.index(after: source.startIndex)) let camel = source.capitalized.replacing(" ", with: "").replacing("\n", with: "") let rest = String(camel.characters.dropFirst()) return "\(first)\(rest)" } else { let first = source.lowercased().substring(to: source.index(after: source.startIndex)) let rest = String(source.characters.dropFirst()) return "\(first)\(rest)" } } /// Check if string contains one or more emojis. public var containEmoji: Bool { // http://stackoverflow.com/questions/30757193/find-out-if-character-in-string-is-emoji for scalar in unicodeScalars { switch scalar.value { case 0x3030, 0x00AE, 0x00A9, // Special Characters 0x1D000...0x1F77F, // Emoticons 0x2100...0x27BF, // Misc symbols and Dingbats 0xFE00...0xFE0F, // Variation Selectors 0x1F900...0x1F9FF: // Supplemental Symbols and Pictographs return true default: continue } } return false } public func at(_ idx: Int) -> String? { return Array(characters).map({String($0)})[idx] } /// First character of string (if applicable). public var firstCharacter: String? { return Array(characters).map({String($0)}).first } /// Check if string contains one or more letters. public var hasLetters: Bool { return rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil } /// Check if string contains one or more numbers. public var hasNumbers: Bool { return rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil } /// Check if string contains only letters. public var isAlphabetic: Bool { return hasLetters && !hasNumbers } /// Check if string contains at least one letter and one number. public var isAlphaNumeric: Bool { return components(separatedBy: CharacterSet.alphanumerics).joined(separator: "").characters.count == 0 && hasLetters && hasNumbers } /// Check if string is valid email format. public var isEmail: Bool { return self.match(Regex.email) } /// Check if string is https URL. public var isUrl: Bool { return self.match(Regex.url) } public var isHttpsUrl: Bool { guard start(with: "https://".lowercased()) else { return false } return URL(string: self) != nil } /// Check if string is http URL. public var isHttpUrl: Bool { guard start(with: "http://".lowercased()) else { return false } return URL(string: self) != nil } /// Check if string contains only numbers. public var isNumeric: Bool { return !hasLetters && hasNumbers } /// Last character of string (if applicable). public var lastCharacter: String? { guard let last = characters.last else { return nil } return String(last) } /// Latinized string. public var latinized: String { return folding(options: .diacriticInsensitive, locale: Locale.current) } /// Array of strings separated by new lines. public var lines: [String] { var result:[String] = [] enumerateLines { (line, stop) -> () in result.append(line) } return result } /// The most common character in string. public var mostCommonCharacter: String { var mostCommon = "" let charSet = Set(withoutSpacesAndNewLines.characters.map{String($0)}) var count = 0 for string in charSet { if self.count(of: string) > count { count = self.count(of: string) mostCommon = string } } return mostCommon } /// Reversed string. public var reversed: String { return String(characters.reversed()) } /// String with no spaces or new lines in beginning and end. public var trimmed: String { return trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } /// Array with unicodes for all characters in a string. public var unicodeArray: [Int] { return unicodeScalars.map({$0.hashValue}) } /// String without spaces and new lines. public var withoutSpacesAndNewLines: String { return replacing(" ", with: "").replacing("\n", with: "").replacing("\r", with: "") } public var containSpace: Bool { return self.contain(" ") } func clean(with: String, allOf: String...) -> String { var string = self for target in allOf { string = string.replacingOccurrences(of: target, with: with) } return string } func count(substring: String) -> Int { return components(separatedBy: substring).count-1 } func endsWith(suffix: String) -> Bool { return hasSuffix(suffix) } func startsWith(prefix: String) -> Bool { return hasPrefix(prefix) } func ensureLeft(prefix: String) -> String { if startsWith(prefix: prefix) { return self } else { return "\(prefix)\(self)" } } func ensureRight(suffix: String) -> String { if endsWith(suffix: suffix) { return self } else { return "\(self)\(suffix)" } } func isEmpty() -> Bool { return self.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines).characters.count == 0 } } // MARK: - Methods public extension String { /// Copy string to global pasteboard. func copyToPasteboard() { UIPasteboard.general.string = self } /// Converts string format to CamelCase. public mutating func camelize() { self = camelCased } /// Check if string contains one or more instance of substring. /// /// - Parameters: /// - string: substring to search for. /// - caseSensitive: set true for case sensitive search (default is true). /// - Returns: true if string contains one or more instance of substring. public func contain(_ string: String, caseSensitive: Bool = true) -> Bool { if !caseSensitive { return range(of: string, options: .caseInsensitive) != nil } return range(of: string) != nil } /// Count of substring in string. /// /// - Parameters: /// - string: substring to search for. /// - caseSensitive: set true for case sensitive search (default is true). /// - Returns: count of substring in string. public func count(of string: String, caseSensitive: Bool = true) -> Int { if !caseSensitive { return lowercased().components(separatedBy: string).count - 1 } return components(separatedBy: string).count - 1 } /// Check if string ends with substring. /// /// - Parameters: /// - suffix: substring to search if string ends with. /// - caseSensitive: set true for case sensitive search (default is true). /// - Returns: true if string ends with substring. public func end(with suffix: String, caseSensitive: Bool = true) -> Bool { if !caseSensitive { return lowercased().hasSuffix(suffix.lowercased()) } return hasSuffix(suffix) } /// First index of substring in string. /// /// - Parameter string: substring to search for. /// - Returns: first index of substring in string (if applicable). public func firstIndex(of string: String) -> Int? { return Array(self.characters).map({String($0)}).index(of: string) } /// Latinize string. public mutating func latinize() { self = latinized } /// String by replacing part of string with another string. /// /// - Parameters: /// - substring: old substring to find and replace /// - newString: new string to insert in old string place /// - Returns: string after replacing substring with newString public func replacing(_ substring: String, with newString: String) -> String { return replacingOccurrences(of: substring, with: newString) } /// Reverse string. public mutating func reverse() { self = String(characters.reversed()) } /// Array of strings separated by given string. /// /// - Parameter separator: separator to split string by. /// - Returns: array of strings separated by given string. public func splited(by separator: Character) -> [String] { return characters.split{$0 == separator}.map(String.init) } /// Check if string starts with substring. /// /// - Parameters: /// - suffix: substring to search if string starts with. /// - caseSensitive: set true for case sensitive search (default is true). /// - Returns: true if string starts with substring. public func start(with prefix: String, caseSensitive: Bool = true) -> Bool { if !caseSensitive { return lowercased().hasPrefix(prefix.lowercased()) } return hasPrefix(prefix) } /// Date object from string of date format. /// /// - Parameter format: date format /// - Returns: Date object from string (if applicable). public func date(withFormat format: String) -> Date? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.date(from: self) } /// Removes spaces and new lines in beginning and end of string. public mutating func trim() { self = trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } /// Truncate string (cut it to a given number of characters). /// /// - Parameters: /// - toLength: maximum number of charachters before cutting. /// - trailing: string to add at the end of truncated string. public mutating func truncate(toLength: Int, trailing: String? = "...") { guard toLength > 0 else { return } if self.characters.count > toLength { self = self.substring(to: self.index(startIndex, offsetBy: toLength)) + (trailing ?? "") } } /// Truncated string (limited to a given number of characters). /// Truncated string (cut to a given number of characters). /// /// - Parameters: /// - toLength: maximum number of charachters before cutting. /// - trailing: string to add at the end of truncated string. /// - Returns: truncated string (this is an exa...). public func truncated(toLength: Int, trailing: String? = "...") -> String { guard self.characters.count > toLength, toLength > 0 else { return self } return self.substring(to: self.index(startIndex, offsetBy: toLength)) + (trailing ?? "") } } // MARK: - Operators public extension String { /// Repeat string multiple times. /// /// - Parameters: /// - lhs: string to repeat. /// - rhs: number of times to repeat character. /// - Returns: string with character repeated n times. static public func * (lhs: String, rhs: Int) -> String { var newString = "" for _ in 0 ..< rhs { newString += lhs } return newString } /// Repeat string multiple times. /// /// - Parameters: /// - lhs: number of times to repeat character. /// - rhs: string to repeat. /// - Returns: string with character repeated n times. static public func * (lhs: Int, rhs: String) -> String { var newString = "" for _ in 0 ..< lhs { newString += rhs } return newString } } // MARK: - NSAttributedString extensions public extension String { /// Bold string. public var bold: NSAttributedString { return NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)]) } /// Underlined string public var underline: NSAttributedString { return NSAttributedString(string: self, attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue]) } /// Strikethrough string. public var strikethrough: NSAttributedString { return NSAttributedString(string: self, attributes: [NSStrikethroughStyleAttributeName: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue as Int)]) } /// Italic string. public var italic: NSAttributedString { return NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)]) } /// Add color to string. /// /// - Parameter color: text color. /// - Returns: a NSAttributedString versions of string colored with given color. public func colored(with color: UIColor) -> NSAttributedString { return NSMutableAttributedString(string: self, attributes: [NSForegroundColorAttributeName: color]) } } //MARK: - NSString extensions public extension String { /// NSString from a string public var nsString: NSString { return NSString(string: self) } /// NSString lastPathComponent public var lastPathComponent: String { return (self as NSString).lastPathComponent } /// NSString pathExtension public var pathExtension: String { return (self as NSString).pathExtension } /// NSString deletingLastPathComponent public var deletingLastPathComponent: String { return (self as NSString).deletingLastPathComponent } /// NSString deletingPathExtension public var deletingPathExtension: String { return (self as NSString).deletingPathExtension } /// NSString pathComponents public var pathComponents: [String] { return (self as NSString).pathComponents } /// NSString appendingPathComponent(str: String) public func appendingPathComponent(_ str: String) -> String { return (self as NSString).appendingPathComponent(str) } /// NSString appendingPathExtension(str: String) (if applicable). public func appendingPathExtension(_ str: String) -> String? { return (self as NSString).appendingPathExtension(str) } }
mit
2d1936befc888f36e15a8b150b89db56
30.596806
159
0.606886
4.854339
false
false
false
false
EckoEdc/simpleDeadlines-iOS
Simple Deadlines/TaskDetailsViewController.swift
1
3412
// // TaskDetailsViewController.swift // Simple Deadlines // // Created by Edric MILARET on 17-01-12. // Copyright © 2017 Edric MILARET. All rights reserved. // import UIKit import LibSimpleDeadlines class TaskDetailsViewController: UIViewController { // MARK: - Outlets @IBOutlet weak var titleTextField: UITextField! @IBOutlet weak var categoryTextField: AutocompleteField! @IBOutlet weak var datePicker: UIDatePicker! @IBOutlet weak var counterView: CircleCounterView! // MARK: - Properties var task: Task? var newTask = true // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() self.edgesForExtendedLayout = .all if let t = task { newTask = false titleTextField.text = t.title categoryTextField.text = t.category?.name datePicker.setDate(Date(timeIntervalSince1970: t.date!.timeIntervalSince1970), animated: false) setupCircleCounter() NotificationHelper.sharedInstance.removeNotification(for: t.title!) } else { task = TasksService.sharedInstance.getNewTask() } if let category = TasksService.sharedInstance.getAllCategory() { categoryTextField.suggestions = category.map({ (category) -> String in return category.name! }) } titleTextField.becomeFirstResponder() } // MARK: - Actions @IBAction func onDateChanged(_ sender: Any) { task?.date = datePicker.date.dateFor(.startOfDay) as NSDate setupCircleCounter() } @IBAction func textFieldPrimaryActionTriggered(_ sender: Any) { view.endEditing(true) } @IBAction func categoryPrimaryActionTriggered(_ sender: AutocompleteField) { if let suggestion = sender.suggestion, !suggestion.isEmpty { sender.text = suggestion } view.endEditing(true) } @IBAction func onViewTap(_ sender: Any) { view.endEditing(true) } @IBAction func onCancelTapped(_ sender: Any) { if newTask { TasksService.sharedInstance.deleteTask(task: task!) } dismiss(animated: true, completion: nil) } @IBAction func onDoneTapped(_ sender: Any) { guard !titleTextField.text!.isEmpty else { TasksService.sharedInstance.deleteTask(task: task!) return } task!.title = titleTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) task!.date = datePicker.date.dateFor(.startOfDay) as NSDate if let catTitle = categoryTextField.text, !catTitle.isEmpty { let category = TasksService.sharedInstance.getOrCreateCategory(name: catTitle.trimmingCharacters(in: .whitespacesAndNewlines)) task?.category = category } (UIApplication.shared.delegate as! AppDelegate).sendReloadMsg() TasksService.sharedInstance.save() NotificationHelper.sharedInstance.setupNotification(for: task!) dismiss(animated: true, completion: nil) } // MARK: Circle func func setupCircleCounter() { let remainData = task!.getRemainingDaysAndColor() counterView.dayRemaining = remainData.0 counterView.color = remainData.1 } }
gpl-3.0
2e92134c0839d048701fb79f5b78e564
30.583333
138
0.635004
5.038405
false
false
false
false
yuxiuyu/TrendBet
TrendBetting_0531换首页/Pods/Charts/Source/Charts/Highlight/PieRadarHighlighter.swift
7
1675
// // PieRadarHighlighter.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics @objc(PieRadarChartHighlighter) open class PieRadarHighlighter: ChartHighlighter { open override func getHighlight(x: CGFloat, y: CGFloat) -> Highlight? { guard let chart = self.chart as? PieRadarChartViewBase else { return nil } let touchDistanceToCenter = chart.distanceToCenter(x: x, y: y) // check if a slice was touched guard touchDistanceToCenter <= chart.radius else { // if no slice was touched, highlight nothing return nil } var angle = chart.angleForPoint(x: x ,y: y) if chart is PieChartView { angle /= CGFloat(chart.chartAnimator.phaseY) } let index = chart.indexForAngle(angle) // check if the index could be found if index < 0 || index >= chart.data?.maxEntryCountSet?.entryCount ?? 0 { return nil } else { return closestHighlight(index: index, x: x, y: y) } } /// - returns: The closest Highlight object of the given objects based on the touch position inside the chart. /// - parameter index: /// - parameter x: /// - parameter y: @objc open func closestHighlight(index: Int, x: CGFloat, y: CGFloat) -> Highlight? { fatalError("closestHighlight(index, x, y) cannot be called on PieRadarChartHighlighter") } }
apache-2.0
e326790b48c05f0323a76aa7b20c7c68
26.916667
114
0.614328
4.490617
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Managers/MessageTextCacheManager.swift
1
3026
// // MessageTextCacheManager.swift // Rocket.Chat // // Created by Rafael Kellermann Streit on 02/05/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import Foundation final class MessageAttributedString { let string: NSAttributedString let theme: Theme? init(string: NSAttributedString, theme: Theme?) { self.string = string self.theme = theme } } final class MessageTextCacheManager { static let shared = MessageTextCacheManager() let cache = NSCache<NSString, MessageAttributedString>() internal func cachedKey(for identifier: String) -> NSString { return NSString(string: "\(identifier)-cachedattrstring") } func clear() { cache.removeAllObjects() } func remove(for message: Message) { guard let identifier = message.identifier else { return } cache.removeObject(forKey: cachedKey(for: identifier)) } @discardableResult func update(for message: UnmanagedMessage, with theme: Theme? = nil) -> NSMutableAttributedString? { let key = cachedKey(for: message.identifier) let text = NSMutableAttributedString(attributedString: NSAttributedString(string: message.textNormalized()).applyingCustomEmojis(CustomEmoji.emojiStrings) ) if message.isSystemMessage() { text.setFont(MessageTextFontAttributes.italicFont) text.setFontColor(MessageTextFontAttributes.systemFontColor(for: theme)) } else { text.setFont(MessageTextFontAttributes.defaultFont) text.setFontColor(MessageTextFontAttributes.defaultFontColor(for: theme)) text.setLineSpacing(MessageTextFontAttributes.defaultFont) } let mentions = message.mentions let channels = message.channels.compactMap { $0.name } let username = AuthManager.currentUser()?.username let attributedString = text.transformMarkdown(with: theme) let finalText = NSMutableAttributedString(attributedString: attributedString) finalText.trimCharacters(in: .whitespaces) finalText.highlightMentions(mentions, currentUsername: username) finalText.highlightChannels(channels) let cachedObject = MessageAttributedString(string: finalText, theme: theme) cache.setObject(cachedObject, forKey: key) return finalText } @discardableResult func message(for message: UnmanagedMessage, with theme: Theme? = nil) -> NSMutableAttributedString? { var resultText: NSAttributedString? let key = cachedKey(for: message.identifier) if let cachedVersion = cache.object(forKey: key), theme == nil || cachedVersion.theme == theme { resultText = cachedVersion.string } else if let result = update(for: message, with: theme) { resultText = result } if let resultText = resultText { return NSMutableAttributedString(attributedString: resultText) } return nil } }
mit
f93abddb64d47610405e9a98b9b58c7f
32.988764
123
0.68595
5.050083
false
false
false
false
ben-ng/swift
test/SILGen/foreach.swift
4
1769
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s class C {} // CHECK-LABEL: sil hidden @_TF7foreach13tupleElementsFGSaTCS_1CS0___T_ func tupleElements(_ xx: [(C, C)]) { // CHECK: [[PAYLOAD:%.*]] = unchecked_enum_data {{%.*}} : $Optional<(C, C)>, #Optional.some!enumelt.1 // CHECK: [[A:%.*]] = tuple_extract [[PAYLOAD]] : $(C, C), 0 // CHECK: [[B:%.*]] = tuple_extract [[PAYLOAD]] : $(C, C), 1 // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] for (a, b) in xx {} // CHECK: [[PAYLOAD:%.*]] = unchecked_enum_data {{%.*}} : $Optional<(C, C)>, #Optional.some!enumelt.1 // CHECK: [[A:%.*]] = tuple_extract [[PAYLOAD]] : $(C, C), 0 // CHECK: [[B:%.*]] = tuple_extract [[PAYLOAD]] : $(C, C), 1 // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] for (a, _) in xx {} // CHECK: [[PAYLOAD:%.*]] = unchecked_enum_data {{%.*}} : $Optional<(C, C)>, #Optional.some!enumelt.1 // CHECK: [[A:%.*]] = tuple_extract [[PAYLOAD]] : $(C, C), 0 // CHECK: [[B:%.*]] = tuple_extract [[PAYLOAD]] : $(C, C), 1 // CHECK: destroy_value [[A]] // CHECK: destroy_value [[B]] for (_, b) in xx {} // CHECK: [[PAYLOAD:%.*]] = unchecked_enum_data {{%.*}} : $Optional<(C, C)>, #Optional.some!enumelt.1 // CHECK: [[A:%.*]] = tuple_extract [[PAYLOAD]] : $(C, C), 0 // CHECK: [[B:%.*]] = tuple_extract [[PAYLOAD]] : $(C, C), 1 // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] for (_, _) in xx {} // CHECK: [[PAYLOAD:%.*]] = unchecked_enum_data {{%.*}} : $Optional<(C, C)>, #Optional.some!enumelt.1 // CHECK: [[A:%.*]] = tuple_extract [[PAYLOAD]] : $(C, C), 0 // CHECK: [[B:%.*]] = tuple_extract [[PAYLOAD]] : $(C, C), 1 // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] for _ in xx {} }
apache-2.0
0cfe8e31aa542fd323fc4d911f72832f
44.358974
103
0.520068
3.098074
false
false
false
false
335g/TwitterAPIKit
Sources/Models/RetweetIDs.swift
1
1104
// // RetweetIDs.swift // TwitterAPIKit // // Created by Yoshiki Kudo on 2015/07/06. // Copyright © 2015年 Yoshiki Kudo. All rights reserved. // import Foundation public struct RetweetIDs { public let previousCursor: Int public let previousCursorStr: String public let nextCursor: Int public let nextCursorStr: String public let ids: [Int]? public let idStrs: [String]? public init?(dictionary: [String: AnyObject]) { guard let previousCursor = dictionary["previous_cursor"] as? Int, previousCursorStr = dictionary["previous_cursor_str"] as? String, nextCursor = dictionary["next_cursor"] as? Int, nextCursorStr = dictionary["next_cursor_str"] as? String else{ return nil } self.previousCursor = previousCursor self.previousCursorStr = previousCursorStr self.nextCursor = nextCursor self.nextCursorStr = nextCursorStr self.ids = dictionary["ids"] as? [Int] self.idStrs = dictionary["ids"] as? [String] } }
mit
cec446f1930b0b164422cc960d9c2de5
29.611111
77
0.62852
4.351779
false
false
false
false
instacrate/tapcrate-api
Sources/api/Utility/Message+CusomJSONParsing.swift
1
1148
// // Message+CusomJSONParsing.swift // tapcrate-api // // Created by Hakon Hanesand on 11/21/16. // // import Foundation import HTTP import JSON import Vapor extension Message { func json() throws -> JSON { if let existing = storage["json"] as? JSON { return existing } guard let type = headers["Content-Type"] else { throw Abort.custom(status: .badRequest, message: "Missing Content-Type header.") } guard type.contains("application/json") else { throw Abort.custom(status: .badRequest, message: "Missing application/json from Content-Type header.") } guard case let .data(body) = body else { throw Abort.custom(status: .badRequest, message: "Incorrect encoding of body contents.") } var json: JSON! do { json = try JSON(bytes: body) } catch { throw Abort.custom(status: .badRequest, message: "Error parsing JSON in body. Parsing error : \(error)") } storage["json"] = json return json } }
mit
55ffff0354b832e08d084bb7c691a33b
25.090909
116
0.56446
4.432432
false
false
false
false
LoganWright/vapor
Sources/Vapor/Core/Application.swift
1
8917
import libc import MediaType public class Application { public static let VERSION = "0.8.0" /** The router driver is responsible for returning registered `Route` handlers for a given request. */ public lazy var router: RouterDriver = BranchRouter() /** The server driver is responsible for handling connections on the desired port. This property is constant since it cannot be changed after the server has been booted. */ public var server: Server? /** The session driver is responsible for storing and reading values written to the users session. */ public let session: SessionDriver /** Provides access to config settings. */ public lazy var config: Config = Config(application: self) /** Provides access to the underlying `HashDriver`. */ public let hash: Hash /** `Middleware` will be applied in the order it is set in this array. Make sure to append your custom `Middleware` if you don't want to overwrite default behavior. */ public var middleware: [Middleware] /** Provider classes that have been registered with this application */ public var providers: [Provider] /** Internal value populated the first time self.environment is computed */ private var detectedEnvironment: Environment? /** Current environment of the application */ public var environment: Environment { if let environment = self.detectedEnvironment { return environment } let environment = bootEnvironment() self.detectedEnvironment = environment return environment } /** Optional handler to be called when detecting the current environment. */ public var detectEnvironmentHandler: ((String) -> Environment)? /** The work directory of your application is the directory in which your Resources, Public, etc folders are stored. This is normally `./` if you are running Vapor using `.build/xxx/App` */ public var workDir = "./" { didSet { if self.workDir.characters.last != "/" { self.workDir += "/" } } } /** Resources directory relative to workDir */ public var resourcesDir: String { return workDir + "Resources/" } var scopedHost: String? var scopedMiddleware: [Middleware] = [] var scopedPrefix: String? var port: Int = 80 var ip: String = "0.0.0.0" var routes: [Route] = [] /** Initialize the Application. */ public init(sessionDriver: SessionDriver? = nil) { self.middleware = [ AbortMiddleware(), ValidationMiddleware() ] self.providers = [] let hash = Hash() self.session = sessionDriver ?? MemorySessionDriver(hash: hash) self.hash = hash self.middleware.append( SessionMiddleware(session: session) ) } public func bootProviders() { for provider in self.providers { provider.boot(with: self) } } func bootEnvironment() -> Environment { var environment: String if let value = Process.valueFor(argument: "env") { Log.info("Environment override: \(value)") environment = value } else { // TODO: This should default to "production" in release builds environment = "development" } if let handler = self.detectEnvironmentHandler { return handler(environment) } else { return Environment(id: environment) } } /** If multiple environments are passed, return value will be true if at least one of the passed in environment values matches the app environment and false if none of them match. If a single environment is passed, the return value will be true if the the passed in environment matches the app environment. */ public func inEnvironment(_ environments: Environment...) -> Bool { return environments.contains(self.environment) } func bootRoutes() { routes.forEach(router.register) } func bootArguments() { //grab process args if let workDir = Process.valueFor(argument: "workDir") { Log.info("Work dir override: \(workDir)") self.workDir = workDir } if let ip = Process.valueFor(argument: "ip") { Log.info("IP override: \(ip)") self.ip = ip } if let port = Process.valueFor(argument: "port")?.int { Log.info("Port override: \(port)") self.port = port } } /** Boots the chosen server driver and optionally runs on the supplied ip & port overrides */ public func start(ip: String? = nil, port: Int? = nil) { self.ip = ip ?? self.ip self.port = port ?? self.port bootArguments() bootProviders() bootRoutes() if environment == .Production { Log.info("Production mode detected, disabling information logs.") Log.enabledLevels = [.Error, .Fatal] } do { Log.info("Server starting on \(self.ip):\(self.port)") let server: Server if let presetServer = self.server { server = presetServer } else { server = try HTTPStreamServer<ServerSocket>( host: self.ip, port: self.port, responder: self ) self.server = server } try server.start() } catch { Log.error("Server start error: \(error)") } } func checkFileSystem(for request: Request) -> Request.Handler? { // Check in file system let filePath = self.workDir + "Public" + (request.uri.path ?? "") guard FileManager.fileAtPath(filePath).exists else { return nil } // File exists if let fileBody = try? FileManager.readBytesFromFile(filePath) { return Request.Handler { _ in var headers: Response.Headers = [:] if let fileExtension = filePath.split(byString: ".").last, let type = mediaType(forFileExtension: fileExtension) { headers["Content-Type"] = Response.Headers.Values(type.description) } return Response(status: .ok, headers: headers, body: Data(fileBody)) } } else { return Request.Handler { _ in Log.warning("Could not open file, returning 404") return Response(status: .notFound, text: "Page not found") } } } } extension Application: Responder { /** Returns a response to the given request - parameter request: received request - throws: error if something fails in finding response - returns: response if possible */ public func respond(to request: Request) throws -> Response { Log.info("\(request.method) \(request.uri.path ?? "/")") var responder: Responder var request = request request.parseData() // Check in routes if let (parameters, routerHandler) = router.route(request) { request.parameters = parameters responder = routerHandler } else if let fileHander = self.checkFileSystem(for: request) { responder = fileHander } else { // Default not found handler responder = Request.Handler { _ in return Response(status: .notFound, text: "Page not found") } } // Loop through middlewares in order for middleware in self.middleware { responder = middleware.chain(to: responder) } var response: Response do { response = try responder.respond(to: request) if response.headers["Content-Type"].first == nil { Log.warning("Response had no 'Content-Type' header.") } } catch { var error = "Server Error: \(error)" if environment == .Production { error = "Something went wrong" } response = Response(error: error) } response.headers["Date"] = Response.Headers.Values(Response.date) response.headers["Server"] = Response.Headers.Values("Vapor \(Application.VERSION)") return response } }
mit
4b8ac640804f87fef9e656a01c0f0b20
26.778816
92
0.5614
5.026494
false
false
false
false
chanhx/Octogit
iGithub/Views/StatusProvider/StatusProvider.swift
2
3969
// // StatusProvider.swift // // Created by MarioHahn on 23/08/16. // import Foundation import UIKit public enum StatusProviderType { struct Constants { static let loadingTag = 7023 static let errorTag = 7024 static let emptyTag = 7025 static let noneTag = 7026 } case loading case error(error: NSError?, retry: (()->Void)?) case empty case none static func allViewTags() -> [Int] { return [ Constants.loadingTag,Constants.errorTag,Constants.emptyTag,Constants.noneTag] } func viewTag() -> Int{ switch self { case .loading: return Constants.loadingTag case .error(_, _): return Constants.errorTag case .empty: return Constants.emptyTag case .none: return Constants.noneTag } } } public protocol StatusOnViewProvider { var onView: UIView { get } } public protocol StatusProvider: StatusOnViewProvider { var loadingView: UIView? { get } var errorView: ErrorStatusDisplaying? { get } var emptyView: UIView? { get } func show(statusType type: StatusProviderType) func hide(statusType type: StatusProviderType) } extension StatusOnViewProvider where Self: UIViewController { public var onView: UIView { return view } } extension StatusOnViewProvider where Self: UIView { public var onView: UIView { return self } } public protocol ErrorStatusDisplaying: class { var error: NSError? { set get } var retry: (()->Void)? { set get } } extension StatusProvider { public var loadingView: UIView? { get { #if os(tvOS) return LoadingStatusView(loadingStyle: .activity) #elseif os(iOS) return LoadingStatusView(loadingStyle: .labelWithActivity) #else return nil #endif } } public var errorView: ErrorStatusDisplaying? { get { return ErrorStatusView() } } public var emptyView: UIView? { get { return nil } } public func hide(statusType type: StatusProviderType) { remove(viewTag: type.viewTag()) } func remove(viewTag tag: Int){ onView.viewWithTag(tag)?.removeFromSuperview() } public func show(statusType type: StatusProviderType) { StatusProviderType.allViewTags().forEach({ remove(viewTag: $0) }) var statusView: UIView? = nil switch type { case let .error(error, retry): statusView = errorView as? UIView (statusView as? ErrorStatusDisplaying)?.error = error (statusView as? ErrorStatusDisplaying)?.retry = retry case .loading: statusView = loadingView case .empty: statusView = emptyView case .none: break } statusView?.tag = type.viewTag() addViewAndCenterConstraints(statusView) } fileprivate func addViewAndCenterConstraints(_ view: UIView?) { guard let view = view else { return } onView.insertSubview(view, at: 0) view.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ view.centerXAnchor.constraint(equalTo: onView.centerXAnchor), view.centerYAnchor.constraint(equalTo: onView.centerYAnchor), view.leadingAnchor.constraint(greaterThanOrEqualTo: onView.leadingAnchor), view.trailingAnchor.constraint(lessThanOrEqualTo: onView.trailingAnchor), view.topAnchor.constraint(greaterThanOrEqualTo: onView.topAnchor), view.bottomAnchor.constraint(lessThanOrEqualTo: onView.bottomAnchor) ]) } }
gpl-3.0
927f1da646ffe760f5367c29483ef5bc
26.184932
94
0.594104
5.0625
false
false
false
false
forwk1990/PropertyExchange
PropertyExchange/YPFilterCollectionViewCell.swift
1
1638
// // YPFilterCollectionViewCell.swift // PropertyExchange // // Created by itachi on 16/9/29. // Copyright © 2016年 com.itachi. All rights reserved. // import UIKit class YPFilterCollectionViewCell: UICollectionViewCell { public var isChecked:Bool = false { didSet{ if self.isChecked{ self.filterItemLabel.layer.borderWidth = 2 self.filterItemLabel.backgroundColor = UIColor.clear self.filterItemLabel.textColor = UIColor.colorWithHex(hex: 0x39404D) }else{ self.filterItemLabel.layer.borderWidth = 0 self.filterItemLabel.backgroundColor = UIColor.colorWithHex(hex: 0xF5F5F5) self.filterItemLabel.textColor = UIColor.colorWithHex(hex: 0x999999) } } } fileprivate lazy var filterItemLabel:UILabel = { let _label = UILabel() _label.textColor = UIColor.colorWithHex(hex: 0x999999) _label.backgroundColor = UIColor.colorWithHex(hex: 0xF5F5F5) _label.layer.borderColor = UIColor.colorWithHex(hex: 0x39404D).cgColor _label.font = UIFont.systemFont(ofSize: 14) _label.textAlignment = .center return _label }() public var model:String? { didSet{ guard let _model = self.model else {return} self.filterItemLabel.text = _model } } override init(frame: CGRect) { super.init(frame: frame) self.contentView.addSubview(self.filterItemLabel) self.filterItemLabel.snp.makeConstraints { (make) in make.top.left.right.bottom.equalTo(self.contentView) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
da2568811218b3fc3f91196ebf040a48
26.711864
82
0.689297
3.856132
false
false
false
false
prebid/prebid-mobile-ios
PrebidMobile/CacheManager.swift
1
1922
/* Copyright 2019-2020 Prebid.org, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit public class CacheManager: NSObject { public static let cacheManagerExpireInterval : TimeInterval = 300 /** * The class is created as a singleton object & used */ @objc public static let shared = CacheManager() /** * The initializer that needs to be created only once */ private override init() { super.init() } internal var savedValuesDict = [String : String]() weak var delegate: CacheExpiryDelegate? public func save(content: String, expireInterval: TimeInterval = CacheManager.cacheManagerExpireInterval) -> String? { if content.isEmpty { return nil } else { let cacheId = "Prebid_" + UUID().uuidString self.savedValuesDict[cacheId] = content DispatchQueue.main.asyncAfter(deadline: .now() + expireInterval, execute: { self.savedValuesDict.removeValue(forKey: cacheId) self.delegate?.cacheExpired() }) return cacheId } } public func isValid(cacheId: String) -> Bool{ return self.savedValuesDict.keys.contains(cacheId) } public func get(cacheId: String) -> String?{ return self.savedValuesDict[cacheId] } } protocol CacheExpiryDelegate : AnyObject{ func cacheExpired() }
apache-2.0
19728d8bb3a538baee2c8e19e5be5923
30
122
0.667534
4.554502
false
false
false
false
TakuSemba/DribbbleSwiftApp
Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesAPI.swift
1
9487
// // GitHubSearchRepositoriesAPI.swift // RxExample // // Created by Krunoslav Zaher on 10/18/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift #endif /** Parsed GitHub respository. */ struct Repository: CustomDebugStringConvertible { var name: String var url: String init(name: String, url: String) { self.name = name self.url = url } } extension Repository { var debugDescription: String { return "\(name) | \(url)" } } /** ServiceState state. */ enum ServiceState { case Online case Offline } /** Raw response from GitHub API */ enum SearchRepositoryResponse { /** New repositories just fetched */ case Repositories(repositories: [Repository], nextURL: NSURL?) /** In case there was some problem fetching data from service, this will be returned. It really doesn't matter if that is a failure in network layer, parsing error or something else. In case data can't be read and parsed properly, something is wrong with server response. */ case ServiceOffline /** This example uses unauthenticated GitHub API. That API does have throttling policy and you won't be able to make more then 10 requests per minute. That is actually an awesome scenario to demonstrate complex retries using alert views and combination of timers. Just search like mad, and everything will be handled right. */ case LimitExceeded } /** This is the final result of loading. Crème de la crème. */ struct RepositoriesState { /** List of parsed repositories ready to be shown in the UI. */ let repositories: [Repository] /** Current network state. */ let serviceState: ServiceState? /** Limit exceeded */ let limitExceeded: Bool static let empty = RepositoriesState(repositories: [], serviceState: nil, limitExceeded: false) } class GitHubSearchRepositoriesAPI { // ***************************************************************************************** // !!! This is defined for simplicity sake, using singletons isn't advised !!! // !!! This is just a simple way to move services to one location so you can see Rx code !!! // ***************************************************************************************** static let sharedAPI = GitHubSearchRepositoriesAPI(wireframe: DefaultWireframe(), reachabilityService: try! DefaultReachabilityService()) let activityIndicator = ActivityIndicator() // Why would network service have wireframe service? It's here to abstract promting user // Do we really want to make this example project factory/fascade/service competition? :) private let _wireframe: Wireframe private let _reachabilityService: ReachabilityService private init(wireframe: Wireframe, reachabilityService: ReachabilityService) { _wireframe = wireframe _reachabilityService = reachabilityService } } // MARK: Pagination extension GitHubSearchRepositoriesAPI { /** Public fascade for search. */ func search(query: String, loadNextPageTrigger: Observable<Void>) -> Observable<RepositoriesState> { let escapedQuery = query.URLEscaped let url = NSURL(string: "https://api.github.com/search/repositories?q=\(escapedQuery)")! return recursivelySearch([], loadNextURL: url, loadNextPageTrigger: loadNextPageTrigger) // Here we go again .startWith(RepositoriesState.empty) } private func recursivelySearch(loadedSoFar: [Repository], loadNextURL: NSURL, loadNextPageTrigger: Observable<Void>) -> Observable<RepositoriesState> { return loadSearchURL(loadNextURL).flatMap { searchResponse -> Observable<RepositoriesState> in switch searchResponse { /** If service is offline, that's ok, that means that this isn't the last thing we've heard from that API. It will retry until either battery drains, you become angry and close the app or evil machine comes back from the future, steals your device and Googles Sarah Connor's address. */ case .ServiceOffline: return Observable.just(RepositoriesState(repositories: loadedSoFar, serviceState: .Offline, limitExceeded: false)) case .LimitExceeded: return Observable.just(RepositoriesState(repositories: loadedSoFar, serviceState: .Online, limitExceeded: true)) case let .Repositories(newPageRepositories, maybeNextURL): var loadedRepositories = loadedSoFar loadedRepositories.appendContentsOf(newPageRepositories) let appenedRepositories = RepositoriesState(repositories: loadedRepositories, serviceState: .Online, limitExceeded: false) // if next page can't be loaded, just return what was loaded, and stop guard let nextURL = maybeNextURL else { return Observable.just(appenedRepositories) } return [ // return loaded immediately Observable.just(appenedRepositories), // wait until next page can be loaded Observable.never().takeUntil(loadNextPageTrigger), // load next page self.recursivelySearch(loadedRepositories, loadNextURL: nextURL, loadNextPageTrigger: loadNextPageTrigger) ].concat() } } } private func loadSearchURL(searchURL: NSURL) -> Observable<SearchRepositoryResponse> { return NSURLSession.sharedSession() .rx_response(NSURLRequest(URL: searchURL)) .retry(3) .trackActivity(self.activityIndicator) .observeOn(Dependencies.sharedDependencies.backgroundWorkScheduler) .map { data, httpResponse -> SearchRepositoryResponse in if httpResponse.statusCode == 403 { return .LimitExceeded } let jsonRoot = try GitHubSearchRepositoriesAPI.parseJSON(httpResponse, data: data) guard let json = jsonRoot as? [String: AnyObject] else { throw exampleError("Casting to dictionary failed") } let repositories = try GitHubSearchRepositoriesAPI.parseRepositories(json) let nextURL = try GitHubSearchRepositoriesAPI.parseNextURL(httpResponse) return .Repositories(repositories: repositories, nextURL: nextURL) } .retryOnBecomesReachable(.ServiceOffline, reachabilityService: _reachabilityService) } } // MARK: Parsing the response extension GitHubSearchRepositoriesAPI { private static let parseLinksPattern = "\\s*,?\\s*<([^\\>]*)>\\s*;\\s*rel=\"([^\"]*)\"" private static let linksRegex = try! NSRegularExpression(pattern: parseLinksPattern, options: [.AllowCommentsAndWhitespace]) private static func parseLinks(links: String) throws -> [String: String] { let length = (links as NSString).length let matches = GitHubSearchRepositoriesAPI.linksRegex.matchesInString(links, options: NSMatchingOptions(), range: NSRange(location: 0, length: length)) var result: [String: String] = [:] for m in matches { let matches = (1 ..< m.numberOfRanges).map { rangeIndex -> String in let range = m.rangeAtIndex(rangeIndex) let startIndex = links.startIndex.advancedBy(range.location) let endIndex = startIndex.advancedBy(range.length) let stringRange = startIndex ..< endIndex return links.substringWithRange(stringRange) } if matches.count != 2 { throw exampleError("Error parsing links") } result[matches[1]] = matches[0] } return result } private static func parseNextURL(httpResponse: NSHTTPURLResponse) throws -> NSURL? { guard let serializedLinks = httpResponse.allHeaderFields["Link"] as? String else { return nil } let links = try GitHubSearchRepositoriesAPI.parseLinks(serializedLinks) guard let nextPageURL = links["next"] else { return nil } guard let nextUrl = NSURL(string: nextPageURL) else { throw exampleError("Error parsing next url `\(nextPageURL)`") } return nextUrl } private static func parseJSON(httpResponse: NSHTTPURLResponse, data: NSData) throws -> AnyObject { if !(200 ..< 300 ~= httpResponse.statusCode) { throw exampleError("Call failed") } return try NSJSONSerialization.JSONObjectWithData(data ?? NSData(), options: []) } private static func parseRepositories(json: [String: AnyObject]) throws -> [Repository] { guard let items = json["items"] as? [[String: AnyObject]] else { throw exampleError("Can't find items") } return try items.map { item in guard let name = item["name"] as? String, url = item["url"] as? String else { throw exampleError("Can't parse repository") } return Repository(name: name, url: url) } } }
apache-2.0
775ceaf1fd044dd3ed36f01b151b4ae4
34.924242
158
0.630747
5.268889
false
false
false
false
akaralar/siesta
Examples/GithubBrowser/Source/UI/RepositoryListViewController.swift
1
4202
import UIKit import Siesta class RepositoryListViewController: UITableViewController, ResourceObserver { // MARK: Interesting Siesta stuff var repositoriesResource: Resource? { didSet { oldValue?.removeObservers(ownedBy: self) repositoriesResource? .addObserver(self) .addObserver(statusOverlay, owner: self) .loadIfNeeded() } } var repositories: [Repository] = [] { didSet { tableView.reloadData() } } var statusOverlay = ResourceStatusOverlay() func resourceChanged(_ resource: Resource, event: ResourceEvent) { // Siesta’s typedContent() infers from the type of the repositories property that // repositoriesResource should hold content of type [Repository]. repositories = repositoriesResource?.typedContent() ?? [] } // MARK: Standard table view stuff override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = SiestaTheme.darkColor statusOverlay.embed(in: self) } override func viewDidLayoutSubviews() { statusOverlay.positionToCoverParent() } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return repositories.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "repo", for: indexPath) if let cell = cell as? RepositoryTableViewCell { cell.repository = repositories[(indexPath as IndexPath).row] } return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "repoDetail" { if let repositoryVC = segue.destination as? RepositoryViewController, let cell = sender as? RepositoryTableViewCell { repositoryVC.repositoryResource = repositoriesResource?.optionalRelative( cell.repository?.url) } } } } class RepositoryTableViewCell: UITableViewCell { @IBOutlet weak var icon: RemoteImageView! @IBOutlet weak var userLabel: UILabel! @IBOutlet weak var repoLabel: UILabel! @IBOutlet weak var starCountLabel: UILabel! var repository: Repository? { didSet { userLabel.text = repository?.owner.login repoLabel.text = repository?.name starCountLabel.text = repository?.starCount?.description // Note how powerful this next line is: // // • RemoteImageView calls loadIfNeeded() when we set imageURL, so this automatically triggers a network // request for the image. However... // // • loadIfNeeded() won’t make redundant requests, so no need to worry about whether this avatar is used in // other table cells, or whether we’ve already requested it! Many cells sharing one image spawn one // request. One response updates _all_ the cells that image. // // • If imageURL was already set, RemoteImageView calls cancelLoadIfUnobserved() on the old image resource. // This means that if the user is scrolling fast and table cells are being reused: // // - a request in progress gets cancelled // - unless other cells are also waiting on the same image, in which case the request continues, and // - an image that we’ve already fetch stay available in memory, fully parsed & ready for instant resuse. // // Finally, note that all of this nice behavior is not special magic that’s specific to images. These are // basic Siesta behaviors you can use for resources of any kind. Look at the RemoteImageView source code // and study how it uses the core Siesta API. icon.imageURL = repository?.owner.avatarURL } } }
mit
72725d138b541a923ae04a619644318c
36.702703
119
0.635842
5.4
false
false
false
false
Bouke/HAP
Sources/COperatingSystem/libc.swift
1
2687
#if os(Linux) @_exported import Glibc #else @_exported import Darwin.C #endif public func posix(_ action: @autoclosure () -> Int32) throws { guard action() == 0 else { try throwError() } } public func throwError() throws -> Never { guard let error = PosixError(rawValue: errno) else { fatalError("Unknown errno \(errno)") } throw error } public enum PosixError: Int32, Error { case EPERM = 1 case ENOENT = 2 case ESRCH = 3 case EINTR = 4 case EIO = 5 case ENXIO = 6 case E2BIG = 7 case ENOEXEC = 8 case EBADF = 9 case ECHILD = 10 case EDEADLK = 11 case ENOMEM = 12 case EACCES = 13 case EFAULT = 14 case ENOTBLK = 15 case EBUSY = 16 case EEXIST = 17 case EXDEV = 18 case ENODEV = 19 case ENOTDIR = 20 case EISDIR = 21 case EINVAL = 22 case ENFILE = 23 case EMFILE = 24 case ENOTTY = 25 case ETXTBSY = 26 case EFBIG = 27 case ENOSPC = 28 case ESPIPE = 29 case EROFS = 30 case EMLINK = 31 case EPIPE = 32 case EDOM = 33 case ERANGE = 34 case EAGAIN = 35 case EINPROGRESS = 36 case EALREADY = 37 case ENOTSOCK = 38 case EDESTADDRREQ = 39 case EMSGSIZE = 40 case EPROTOTYPE = 41 case ENOPROTOOPT = 42 case EPROTONOSUPPORT = 43 case ESOCKTNOSUPPORT = 44 case ENOTSUP = 45 case EPFNOSUPPORT = 46 case EAFNOSUPPORT = 47 case EADDRINUSE = 48 case EADDRNOTAVAIL = 49 case ENETDOWN = 50 case ENETUNREACH = 51 case ENETRESET = 52 case ECONNABORTED = 53 case ECONNRESET = 54 case ENOBUFS = 55 case EISCONN = 56 case ENOTCONN = 57 case ESHUTDOWN = 58 case ETIMEDOUT = 60 case ECONNREFUSED = 61 case ELOOP = 62 case ENAMETOOLONG = 63 case EHOSTDOWN = 64 case EHOSTUNREACH = 65 case ENOTEMPTY = 66 case EPROCLIM = 67 case EUSERS = 68 case EDQUOT = 69 case ESTALE = 70 case EBADRPC = 72 case ERPCMISMATCH = 73 case EPROGUNAVAIL = 74 case EPROGMISMATCH = 75 case EPROCUNAVAIL = 76 case ENOLCK = 77 case ENOSYS = 78 case EFTYPE = 79 case EAUTH = 80 case ENEEDAUTH = 81 case EPWROFF = 82 case EDEVERR = 83 case EOVERFLOW = 84 case EBADEXEC = 85 case EBADARCH = 86 case ESHLIBVERS = 87 case EBADMACHO = 88 case ECANCELED = 89 case EIDRM = 90 case ENOMSG = 91 case EILSEQ = 92 case ENOATTR = 93 case EBADMSG = 94 case EMULTIHOP = 95 case ENODATA = 96 case ENOLINK = 97 case ENOSR = 98 case ENOSTR = 99 case EPROTO = 100 case ETIME = 101 case EOPNOTSUPP = 102 }
mit
76646561550ee22810631b2c2068cb2a
21.206612
62
0.606252
4.25832
false
false
false
false
Gaantz/SocketsIO---iOS
socket.io-client-swift-master/SocketIOClientSwift/SocketEngine.swift
3
22364
// // SocketEngine.swift // Socket.IO-Client-Swift // // Created by Erik Little on 3/3/15. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public final class SocketEngine: NSObject, WebSocketDelegate { private typealias Probe = (msg: String, type: PacketType, data: [NSData]?) private typealias ProbeWaitQueue = [Probe] private let allowedCharacterSet = NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]\" {}").invertedSet private let emitQueue = dispatch_queue_create("engineEmitQueue", DISPATCH_QUEUE_SERIAL) private let handleQueue = dispatch_queue_create("engineHandleQueue", DISPATCH_QUEUE_SERIAL) private let logType = "SocketEngine" private let parseQueue = dispatch_queue_create("engineParseQueue", DISPATCH_QUEUE_SERIAL) private let session: NSURLSession! private let workQueue = NSOperationQueue() private var closed = false private var extraHeaders: [String: String]? private var fastUpgrade = false private var forcePolling = false private var forceWebsockets = false private var pingInterval: Double? private var pingTimer: NSTimer? private var pingTimeout = 0.0 { didSet { pongsMissedMax = Int(pingTimeout / (pingInterval ?? 25)) } } private var pongsMissed = 0 private var pongsMissedMax = 0 private var postWait = [String]() private var probing = false private var probeWait = ProbeWaitQueue() private var waitingForPoll = false private var waitingForPost = false private var websocketConnected = false private(set) var connected = false private(set) var polling = true private(set) var websocket = false weak var client: SocketEngineClient? var cookies: [NSHTTPCookie]? var sid = "" var socketPath = "" var urlPolling: String? var urlWebSocket: String? var ws: WebSocket? @objc public enum PacketType: Int { case Open, Close, Ping, Pong, Message, Upgrade, Noop init?(str: String) { if let value = Int(str), raw = PacketType(rawValue: value) { self = raw } else { return nil } } } public init(client: SocketEngineClient, sessionDelegate: NSURLSessionDelegate?) { self.client = client self.session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: sessionDelegate, delegateQueue: workQueue) } public convenience init(client: SocketEngineClient, opts: NSDictionary?) { self.init(client: client, sessionDelegate: opts?["sessionDelegate"] as? NSURLSessionDelegate) forceWebsockets = opts?["forceWebsockets"] as? Bool ?? false forcePolling = opts?["forcePolling"] as? Bool ?? false cookies = opts?["cookies"] as? [NSHTTPCookie] socketPath = opts?["path"] as? String ?? "" extraHeaders = opts?["extraHeaders"] as? [String: String] } deinit { Logger.log("Engine is being deinit", type: logType) } public func close(fast fast: Bool) { Logger.log("Engine is being closed. Fast: %@", type: logType, args: fast) pingTimer?.invalidate() closed = true ws?.disconnect() if fast || polling { write("", withType: PacketType.Close, withData: nil) client?.engineDidClose("Disconnect") } stopPolling() } private func createBinaryDataForSend(data: NSData) -> (NSData?, String?) { if websocket { var byteArray = [UInt8](count: 1, repeatedValue: 0x0) byteArray[0] = 4 let mutData = NSMutableData(bytes: &byteArray, length: 1) mutData.appendData(data) return (mutData, nil) } else { var str = "b4" str += data.base64EncodedStringWithOptions( NSDataBase64EncodingOptions.Encoding64CharacterLineLength) return (nil, str) } } private func createURLs(params: [String: AnyObject]?) -> (String?, String?) { if client == nil { return (nil, nil) } let path = socketPath == "" ? "/socket.io" : socketPath let url = "\(client!.socketURL)\(path)/?transport=" var urlPolling: String var urlWebSocket: String if client!.secure { urlPolling = "https://" + url + "polling" urlWebSocket = "wss://" + url + "websocket" } else { urlPolling = "http://" + url + "polling" urlWebSocket = "ws://" + url + "websocket" } if params != nil { for (key, value) in params! { let keyEsc = key.stringByAddingPercentEncodingWithAllowedCharacters( allowedCharacterSet)! urlPolling += "&\(keyEsc)=" urlWebSocket += "&\(keyEsc)=" if value is String { let valueEsc = (value as! String).stringByAddingPercentEncodingWithAllowedCharacters( allowedCharacterSet)! urlPolling += "\(valueEsc)" urlWebSocket += "\(valueEsc)" } else { urlPolling += "\(value)" urlWebSocket += "\(value)" } } } return (urlPolling, urlWebSocket) } private func createWebsocket(andConnect connect: Bool) { let wsUrl = urlWebSocket! + (sid == "" ? "" : "&sid=\(sid)") ws = WebSocket(url: NSURL(string: wsUrl)!, cookies: cookies) if extraHeaders != nil { for (headerName, value) in extraHeaders! { ws?.headers[headerName] = value } } ws?.queue = handleQueue ws?.delegate = self if connect { ws?.connect() } } private func doFastUpgrade() { if waitingForPoll { Logger.error("Outstanding poll when switched to WebSockets," + "we'll probably disconnect soon. You should report this.", type: logType) } sendWebSocketMessage("", withType: PacketType.Upgrade, datas: nil) websocket = true polling = false fastUpgrade = false probing = false flushProbeWait() } private func doPoll() { if websocket || waitingForPoll || !connected { return } waitingForPoll = true let req = NSMutableURLRequest(URL: NSURL(string: urlPolling! + "&sid=\(sid)&b64=1")!) if cookies != nil { let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!) req.allHTTPHeaderFields = headers } if extraHeaders != nil { for (headerName, value) in extraHeaders! { req.setValue(value, forHTTPHeaderField: headerName) } } doRequest(req) } private func doRequest(req: NSMutableURLRequest) { if !polling { return } req.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData Logger.log("Doing polling request", type: logType) session.dataTaskWithRequest(req) {[weak self] data, res, err in if let this = self { if err != nil || data == nil { if this.polling { this.handlePollingFailed(err?.localizedDescription ?? "Error") } else { Logger.error(err?.localizedDescription ?? "Error", type: this.logType) } return } Logger.log("Got polling response", type: this.logType) if let str = NSString(data: data!, encoding: NSUTF8StringEncoding) as? String { dispatch_async(this.parseQueue) {[weak this] in this?.parsePollingMessage(str) } } this.waitingForPoll = false if this.fastUpgrade { this.doFastUpgrade() } else if !this.closed && this.polling { this.doPoll() } }}.resume() } private func flushProbeWait() { Logger.log("Flushing probe wait", type: logType) dispatch_async(emitQueue) {[weak self] in if let this = self { for waiter in this.probeWait { this.write(waiter.msg, withType: waiter.type, withData: waiter.data) } this.probeWait.removeAll(keepCapacity: false) if this.postWait.count != 0 { this.flushWaitingForPostToWebSocket() } } } } private func flushWaitingForPost() { if postWait.count == 0 || !connected { return } else if websocket { flushWaitingForPostToWebSocket() return } var postStr = "" for packet in postWait { let len = packet.characters.count postStr += "\(len):\(packet)" } postWait.removeAll(keepCapacity: false) let req = NSMutableURLRequest(URL: NSURL(string: urlPolling! + "&sid=\(sid)")!) if let cookies = cookies { let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies) req.allHTTPHeaderFields = headers } req.HTTPMethod = "POST" req.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type") let postData = postStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! req.HTTPBody = postData req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length") waitingForPost = true Logger.log("POSTing: %@", type: logType, args: postStr) session.dataTaskWithRequest(req) {[weak self] data, res, err in if let this = self { if err != nil && this.polling { this.handlePollingFailed(err?.localizedDescription ?? "Error") return } else if err != nil { NSLog(err?.localizedDescription ?? "Error") return } this.waitingForPost = false dispatch_async(this.emitQueue) {[weak this] in if !(this?.fastUpgrade ?? true) { this?.flushWaitingForPost() this?.doPoll() } } }}.resume() } // We had packets waiting for send when we upgraded // Send them raw private func flushWaitingForPostToWebSocket() { guard let ws = self.ws else {return} for msg in postWait { ws.writeString(msg) } postWait.removeAll(keepCapacity: true) } private func handleClose() { if let client = client where polling == true { client.engineDidClose("Disconnect") } } private func checkIfMessageIsBase64Binary(var message: String) { if message.hasPrefix("b4") { // binary in base64 string message.removeRange(Range<String.Index>(start: message.startIndex, end: message.startIndex.advancedBy(2))) if let data = NSData(base64EncodedString: message, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters) { client?.parseBinaryData(data) } } } private func handleMessage(message: String) { client?.parseSocketMessage(message) } private func handleNOOP() { doPoll() } private func handleOpen(openData: String) { let mesData = openData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! do { let json = try NSJSONSerialization.JSONObjectWithData(mesData, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary if let sid = json?["sid"] as? String { let upgradeWs: Bool self.sid = sid connected = true if let upgrades = json?["upgrades"] as? [String] { upgradeWs = upgrades.filter {$0 == "websocket"}.count != 0 } else { upgradeWs = false } if let pingInterval = json?["pingInterval"] as? Double, pingTimeout = json?["pingTimeout"] as? Double { self.pingInterval = pingInterval / 1000.0 self.pingTimeout = pingTimeout / 1000.0 } if !forcePolling && !forceWebsockets && upgradeWs { createWebsocket(andConnect: true) } } } catch { Logger.error("Error parsing open packet", type: logType) return } startPingTimer() if !forceWebsockets { doPoll() } } private func handlePong(pongMessage: String) { pongsMissed = 0 // We should upgrade if pongMessage == "3probe" { upgradeTransport() } } // A poll failed, tell the client about it private func handlePollingFailed(reason: String) { connected = false ws?.disconnect() pingTimer?.invalidate() waitingForPoll = false waitingForPost = false if !closed { client?.didError(reason) client?.engineDidClose(reason) } } public func open(opts: [String: AnyObject]? = nil) { if connected { Logger.error("Tried to open while connected", type: logType) client?.didError("Tried to open while connected") return } Logger.log("Starting engine", type: logType) Logger.log("Handshaking", type: logType) closed = false (urlPolling, urlWebSocket) = createURLs(opts) if forceWebsockets { polling = false websocket = true createWebsocket(andConnect: true) return } let reqPolling = NSMutableURLRequest(URL: NSURL(string: urlPolling! + "&b64=1")!) if cookies != nil { let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!) reqPolling.allHTTPHeaderFields = headers } if let extraHeaders = extraHeaders { for (headerName, value) in extraHeaders { reqPolling.setValue(value, forHTTPHeaderField: headerName) } } doRequest(reqPolling) } private func parsePollingMessage(str: String) { guard str.characters.count != 1 else { return } var reader = SocketStringReader(message: str) while reader.hasNext { let n = reader.readUntilStringOccurence(":") let str = reader.read(Int(n)!) dispatch_async(handleQueue) { self.parseEngineMessage(str, fromPolling: true) } } } private func parseEngineData(data: NSData) { Logger.log("Got binary data: %@", type: "SocketEngine", args: data) client?.parseBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1))) } private func parseEngineMessage(var message: String, fromPolling: Bool) { Logger.log("Got message: %@", type: logType, args: message) if fromPolling { fixDoubleUTF8(&message) } let type = PacketType(str: (message["^(\\d)"].groups()?[1]) ?? "") ?? { self.checkIfMessageIsBase64Binary(message) return .Noop }() switch type { case PacketType.Message: message.removeAtIndex(message.startIndex) handleMessage(message) case PacketType.Noop: handleNOOP() case PacketType.Pong: handlePong(message) case PacketType.Open: message.removeAtIndex(message.startIndex) handleOpen(message) case PacketType.Close: handleClose() default: Logger.log("Got unknown packet type", type: logType) } } private func probeWebSocket() { if websocketConnected { sendWebSocketMessage("probe", withType: PacketType.Ping) } } /// Send an engine message (4) public func send(msg: String, withData datas: [NSData]?) { if probing { probeWait.append((msg, PacketType.Message, datas)) } else { write(msg, withType: PacketType.Message, withData: datas) } } @objc private func sendPing() { //Server is not responding if pongsMissed > pongsMissedMax { pingTimer?.invalidate() client?.engineDidClose("Ping timeout") return } ++pongsMissed write("", withType: PacketType.Ping, withData: nil) } /// Send polling message. /// Only call on emitQueue private func sendPollMessage(var msg: String, withType type: PacketType, datas:[NSData]? = nil) { Logger.log("Sending poll: %@ as type: %@", type: logType, args: msg, type.rawValue) doubleEncodeUTF8(&msg) let strMsg = "\(type.rawValue)\(msg)" postWait.append(strMsg) for data in datas ?? [] { let (_, b64Data) = createBinaryDataForSend(data) postWait.append(b64Data!) } if !waitingForPost { flushWaitingForPost() } } /// Send message on WebSockets /// Only call on emitQueue private func sendWebSocketMessage(str: String, withType type: PacketType, datas:[NSData]? = nil) { Logger.log("Sending ws: %@ as type: %@", type: logType, args: str, type.rawValue) ws?.writeString("\(type.rawValue)\(str)") for data in datas ?? [] { let (data, _) = createBinaryDataForSend(data) if data != nil { ws?.writeData(data!) } } } // Starts the ping timer private func startPingTimer() { if let pingInterval = pingInterval { pingTimer?.invalidate() pingTimer = nil dispatch_async(dispatch_get_main_queue()) { self.pingTimer = NSTimer.scheduledTimerWithTimeInterval(pingInterval, target: self, selector: Selector("sendPing"), userInfo: nil, repeats: true) } } } func stopPolling() { session.invalidateAndCancel() } private func upgradeTransport() { if websocketConnected { Logger.log("Upgrading transport to WebSockets", type: logType) fastUpgrade = true sendPollMessage("", withType: PacketType.Noop) // After this point, we should not send anymore polling messages } } /** Write a message, independent of transport. */ public func write(msg: String, withType type: PacketType, withData data: [NSData]?) { dispatch_async(emitQueue) { if self.connected { if self.websocket { Logger.log("Writing ws: %@ has data: %@", type: self.logType, args: msg, data == nil ? false : true) self.sendWebSocketMessage(msg, withType: type, datas: data) } else { Logger.log("Writing poll: %@ has data: %@", type: self.logType, args: msg, data == nil ? false : true) self.sendPollMessage(msg, withType: type, datas: data) } } } } // Delagate methods public func websocketDidConnect(socket:WebSocket) { websocketConnected = true if !forceWebsockets { probing = true probeWebSocket() } else { connected = true probing = false polling = false } } public func websocketDidDisconnect(socket: WebSocket, error: NSError?) { websocketConnected = false probing = false if closed { client?.engineDidClose("Disconnect") return } if websocket { pingTimer?.invalidate() connected = false websocket = false let reason = error?.localizedDescription ?? "Socket Disconnected" if error != nil { client?.didError(reason) } client?.engineDidClose(reason) } else { flushProbeWait() } } public func websocketDidReceiveMessage(socket: WebSocket, text: String) { parseEngineMessage(text, fromPolling: false) } public func websocketDidReceiveData(socket: WebSocket, data: NSData) { parseEngineData(data) } }
mit
c1b22a9833303a69adcb7b8a9bbba0c4
31.040115
119
0.560544
5.246071
false
false
false
false
LesCoureurs/Courir
Courir/Courir/EventQueue.swift
1
4070
// // EventQueue.swift // Courir // // Created by Ian Ngiaw on 4/16/16. // Copyright © 2016 NUS CS3217. All rights reserved. // import Foundation class EventQueue { /// The type of an item in the `EventQueue` typealias Element = (event: GameEvent, playerNumber: Int, timeStep: Int, otherData: AnyObject?) private var queue = [Element]() /// The head of the `EventQueue`, the `Element` in the queue with the highest priority. var head: Element? { get { guard count > 0 else { return nil } return queue[0] } } /// The number of items in the `EventQueue`. var count: Int { return queue.count } /// Initializes the `EventQueue` with an initial list of `Element`s. convenience init(initialEvents: [Element]) { self.init() queue = initialEvents for i in (0...(queue.count / 2 - 1)).reverse() { shiftDown(i) } } /// Inserts an `Element` into the `EventQueue` with the provided `event`, `playerNumber`, /// `timeStep` and any `otherData`. func insert(event: GameEvent, playerNumber: Int, timeStep: Int, otherData: AnyObject?) { queue.append((event, playerNumber, timeStep, otherData)) shiftUp(count - 1) } /// Removes the `head` from the `EventQueue`. /// - Returns: The `Element` that was at the head of the queue. /// If the queue is empty, returns `nil`. func removeHead() -> Element? { guard count > 0 else { return nil } guard count != 1 else { return queue.removeLast() } let head = self.head! swap(indexA: 0, indexB: count - 1) queue.removeLast() shiftDown(0) return head } /// Gets the parent index for an item at `index` in the `queue` array. /// `index` must be greater than `0`. private func getParentIndex(index: Int) -> Int { assert(index > 0) return (index + 1) / 2 - 1 } /// Gets the child indexes for an item at `index` in the `queue` array. /// - Returns: A 2-tuple with left (the index of the left child) and /// right (the index of the right child). private func getChildIndexes(index: Int) -> (left: Int, right: Int) { let left = (index + 1) * 2 - 1 let right = (index + 1) * 2 return (left, right) } /// Shifts the `Element` found at `index` in the `queue` array up the `Element` is misplaced. private func shiftUp(index: Int) { guard index > 0 else { return } let parentIndex = getParentIndex(index) let currentVal = queue[index].timeStep let parentVal = queue[parentIndex].timeStep if currentVal < parentVal { swap(indexA: index, indexB: parentIndex) shiftUp(parentIndex) } } /// Shifts the `Element` found at `index` in the `queue` array down the `Element` is misplaced. private func shiftDown(index: Int) { let childIndexes = getChildIndexes(index) let currentVal = queue[index].timeStep let leftVal = childIndexes.left < count ? queue[childIndexes.left].timeStep : Int.max let rightVal = childIndexes.right < count ? queue[childIndexes.right].timeStep : Int.max let indexToSwap: Int if currentVal > leftVal && currentVal > rightVal { indexToSwap = leftVal < rightVal ? childIndexes.left : childIndexes.right } else if currentVal > leftVal { indexToSwap = childIndexes.left } else if currentVal > rightVal { indexToSwap = childIndexes.right } else { return } swap(indexA: index, indexB: indexToSwap) shiftDown(indexToSwap) } /// Swaps `indexA` and `indexB` in the `queue` array. private func swap(indexA a: Int, indexB b: Int) { let aData = queue[a] queue[a] = queue[b] queue[b] = aData } }
mit
be0f6feccbf30874064cd4db85f03636
32.360656
99
0.577783
4.020751
false
false
false
false
yzyzsun/arduino-bluetooth-music-player
iOS/ArduinoBluetoothMusicPlayer/ViewController.swift
1
2344
// // ViewController.swift // ArduinoBluetoothMusicPlayer // // Created by yzyzsun on 2015-08-28. // Copyright (c) 2015 yzyzsun. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() bleManager = BLEManager.sharedInstance } var bleManager: BLEManager! @IBOutlet weak var logView: UITextView! @IBOutlet weak var volumeSlider: UISlider! @IBOutlet weak var volumeStepper: UIStepper! @IBOutlet weak var pauseButton: UIButton! @IBOutlet weak var resumeButton: UIButton! let ModeMap = [ 0: BlunoCommand.ModeNormal, 1: BlunoCommand.ModeShuffle, 2: BlunoCommand.ModeRepeatList, 3: BlunoCommand.ModeRepeatSingle ] @IBAction func changeMode(sender: UISegmentedControl) { bleManager.sendCommand(ModeMap[sender.selectedSegmentIndex]!) } @IBAction func changeVolumeBySlider(sender: UISlider) { volumeStepper.value = Double(sender.value) bleManager.sendCommand(BlunoCommand.VolumeChange, changeVolumeTo: UInt8(sender.value)) } @IBAction func changeVolumeByStepper(sender: UIStepper) { let volumeUp: Bool = sender.value > Double(volumeSlider.value) volumeSlider.value = Float(sender.value) if (volumeUp) { bleManager.sendCommand(BlunoCommand.VolumeUp) } else { bleManager.sendCommand(BlunoCommand.VolumeDown) } } @IBAction func pause() { pauseButton.hidden = true resumeButton.hidden = false bleManager.sendCommand(BlunoCommand.Pause) } @IBAction func resume() { resumeButton.hidden = true pauseButton.hidden = false bleManager.sendCommand(BlunoCommand.Resume) } @IBAction func prev() { bleManager.sendCommand(BlunoCommand.Prev) } @IBAction func backward() { bleManager.sendCommand(BlunoCommand.Backward) } @IBAction func forward() { bleManager.sendCommand(BlunoCommand.Forward) } @IBAction func next() { bleManager.sendCommand(BlunoCommand.Next) } func appendToLog(message: String) { logView.text! += message logView.font = UIFont.systemFontOfSize(14) } }
mit
86c5dc11eb283204300382e58b7550d9
29.051282
94
0.652304
4.473282
false
false
false
false
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Transport/HTTP/HTTPTransport+Result.swift
1
1014
// // HTTPTransport+Result.swift // // // Created by Vladislav Fitc on 02/03/2020. // import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif extension Result where Success: Decodable, Failure == Error { init(data: Data?, response: URLResponse?, error: Swift.Error?) { if let error = error { self = .failure(TransportError.requestError(error)) return } if let httpError = HTTPError(response: response as? HTTPURLResponse, data: data) { self = .failure(TransportError.httpError(httpError)) return } guard let data = data else { self = .failure(TransportError.missingData) return } do { let jsonDecoder = JSONDecoder() jsonDecoder.dateDecodingStrategy = .custom(ClientDateCodingStrategy.decoding) let object = try jsonDecoder.decode(Success.self, from: data) self = .success(object) } catch let error { self = .failure(TransportError.decodingFailure(error)) } } }
mit
897b5c21d42c7cfe89150c30927dc967
22.581395
86
0.675542
4.278481
false
false
false
false
eneko/SwiftyJIRA
iOS/Pods/JSONRequest/Sources/JSONRequestVerbs.swift
1
6231
// // JSONRequestVerbs.swift // JSONRequest // // Created by Eneko Alonso on 1/11/16. // Copyright © 2016 Hathway. All rights reserved. // public enum JSONRequestHttpVerb: String { case GET = "GET" case POST = "POST" case PUT = "PUT" case PATCH = "PATCH" case DELETE = "DELETE" } // MARK: Instance HTTP Sync methods public extension JSONRequest { public func get(url: String, queryParams: JSONObject? = nil, headers: JSONObject? = nil) -> JSONResult { return submitSyncRequest(.GET, url: url, queryParams: queryParams, headers: headers) } public func post(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil, headers: JSONObject? = nil) -> JSONResult { return submitSyncRequest(.POST, url: url, queryParams: queryParams, payload: payload, headers: headers) } public func put(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil, headers: JSONObject? = nil) -> JSONResult { return submitSyncRequest(.PUT, url: url, queryParams: queryParams, payload: payload, headers: headers) } public func patch(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil, headers: JSONObject? = nil) -> JSONResult { return submitSyncRequest(.PATCH, url: url, queryParams: queryParams, payload: payload, headers: headers) } public func delete(url: String, queryParams: JSONObject? = nil, headers: JSONObject? = nil) -> JSONResult { return submitSyncRequest(.DELETE, url: url, queryParams: queryParams, headers: headers) } } // MARK: Instance HTTP Async methods public extension JSONRequest { public func get(url: String, queryParams: JSONObject? = nil, headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) { submitAsyncRequest(.GET, url: url, queryParams: queryParams, headers: headers, complete: complete) } public func post(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil, headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) { submitAsyncRequest(.POST, url: url, queryParams: queryParams, payload: payload, headers: headers, complete: complete) } public func put(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil, headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) { submitAsyncRequest(.PUT, url: url, queryParams: queryParams, payload: payload, headers: headers, complete: complete) } public func patch(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil, headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) { submitAsyncRequest(.PATCH, url: url, queryParams: queryParams, payload: payload, headers: headers, complete: complete) } public func delete(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil, headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) { submitAsyncRequest(.DELETE, url: url, queryParams: queryParams, headers: headers, complete: complete) } } // MARK: Class HTTP Sync methods public extension JSONRequest { public class func get(url: String, queryParams: JSONObject? = nil, headers: JSONObject? = nil) -> JSONResult { return JSONRequest().get(url, queryParams: queryParams, headers: headers) } public class func post(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil, headers: JSONObject? = nil) -> JSONResult { return JSONRequest().post(url, queryParams: queryParams, payload: payload, headers: headers) } public class func put(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil, headers: JSONObject? = nil) -> JSONResult { return JSONRequest().put(url, queryParams: queryParams, payload: payload, headers: headers) } public class func patch(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil, headers: JSONObject? = nil) -> JSONResult { return JSONRequest().patch(url, queryParams: queryParams, payload: payload, headers: headers) } public class func delete(url: String, queryParams: JSONObject? = nil, headers: JSONObject? = nil) -> JSONResult { return JSONRequest().delete(url, queryParams: queryParams, headers: headers) } } // MARK: Class HTTP Async methods public extension JSONRequest { public class func get(url: String, queryParams: JSONObject? = nil, headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) { JSONRequest().get(url, queryParams: queryParams, headers: headers, complete: complete) } public class func post(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil, headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) { JSONRequest().post(url, queryParams: queryParams, payload: payload, headers: headers, complete: complete) } public class func put(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil, headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) { JSONRequest().put(url, queryParams: queryParams, payload: payload, headers: headers, complete: complete) } public class func patch(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil, headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) { JSONRequest().patch(url, queryParams: queryParams, payload: payload, headers: headers, complete: complete) } public class func delete(url: String, queryParams: JSONObject? = nil, headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) { JSONRequest().delete(url, queryParams: queryParams, headers: headers, complete: complete) } }
mit
9875444320ccfd97f07f36a7cc42cdd6
37.9375
99
0.640289
4.46595
false
false
false
false
zzeleznick/piazza-clone
Pizzazz/Pizzazz/StaffViewCell.swift
1
1103
// // StaffViewCell.swift // Pizzazz // // Created by Zach Zeleznick on 5/6/16. // Copyright © 2016 zzeleznick. All rights reserved. // import Foundation import UIKit class StaffViewCell: UITableViewCell { var w: CGFloat! var names: [String]! { willSet(values) { for (idx, name) in values.enumerated() { let label = UILabel() let font = UIFont(name: "Helvetica-Bold", size: 12) label.font = font let y:CGFloat = 22*CGFloat(idx) + 5.0 let labelFrame = CGRect(x: 25, y: y, width: w-25, height: 20) contentView.addUIElement(label, text: name, frame: labelFrame) { _ in // print("Adding \(name)") } } } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) w = UIScreen.main.bounds.size.width } required init?(coder aDecoder: NSCoder) { fatalError("NSCoding not supported") } }
mit
bf82a7167980498dd73e118068b249dd
27.25641
85
0.556261
4.158491
false
false
false
false
TechnologySpeaks/smile-for-life
smile-for-life/CurrentRemindersCollectionViewController.swift
1
3657
// // CurrentRemindersCollectionViewController.swift // smile-for-life // // Created by Lisa Swanson on 1/21/17. // Copyright © 2017 Technology Speaks. All rights reserved. // import UIKit class CurrentRemindersCollectionViewController: UICollectionViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Register cell classes self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let cellHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "SetRemindersHeaderSection", for: indexPath) as! NotificationsCollectionReusableView return cellHeader } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of items return 1 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) cell.layer.borderColor = UIColor.black.cgColor cell.layer.borderWidth = 1.0 // Configure the cell return cell } // MARK: UICollectionViewDelegate /* // Uncomment this method to specify if the specified item should be highlighted during tracking override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { return true } */ /* // Uncomment this method to specify if the specified item should be selected override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { return true } */ /* // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool { return false } override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool { return false } override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) { } */ }
mit
a981cf0e4b9691919a065afce0d0e7ba
35.929293
188
0.722374
5.935065
false
false
false
false
euajudo/ios
euajudo/Controller/SettingsTableViewController.swift
1
1191
// // SettingsTableViewController.swift // euajudo // // Created by Rafael Kellermann Streit on 4/12/15. // Copyright (c) 2015 euajudo. All rights reserved. // import UIKit class SettingsTableViewController: UITableViewController { // MARK: - UITableViewDelegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 0 { let url = NSURL(string: "http://euajudo.meteor.com") UIApplication.sharedApplication().openURL(url!) self.dismissViewControllerAnimated(true, completion: nil) } else { API.connection.logoutWithCompletionHandler { (error) -> Void in self.dismissViewControllerAnimated(true, completion: nil) } } } override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { if section == 1 { return "1.0.0 (1)" } return nil } // MARK: - IBAction @IBAction func buttonClosePressed(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } }
mit
351fc0acd20ce84b23b571c5fd0a75b8
27.357143
102
0.632242
4.9625
false
false
false
false
achappell/dungeonsanddragonscharactersheet
DungeonsDragonsCC/Menu/FetchedResultsControllerDataSource.swift
1
4586
// // FetchedResultsControllerDataSource.swift // DungeonsDragonsCC // // Created by Amanda Chappell on 3/4/16. // Copyright © 2016 AmplifiedProjects. All rights reserved. // import UIKit import CoreData protocol FetchedResultsControllerDataSourceDelegate { func fetchedResultsControllerDataSource(_ configureCell: inout UITableViewCell, withObject: AnyObject) -> Void func fetchedResultsControllerDataSource(_ deleteObject: AnyObject) -> Void } class FetchedResultsControllerDataSource: NSObject, UITableViewDataSource, NSFetchedResultsControllerDelegate, UITableViewDelegate { var delegate: FetchedResultsControllerDataSourceDelegate? var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult> var reuseIdentifier: String var paused: Bool { didSet { if paused { fetchedResultsController.delegate = nil } else { fetchedResultsController.delegate = self do { try fetchedResultsController.performFetch() } catch { let fetchError = error as NSError print("\(fetchError), \(fetchError.userInfo)") } self.fetchedResultsController.delegate = self self.tableView?.dataSource = self self.tableView?.delegate = self self.tableView?.reloadData() } } } private weak var tableView: UITableView? init(tableView: UITableView?, fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>, reuseIdentifier: String) { self.tableView = tableView self.fetchedResultsController = fetchedResultsController self.reuseIdentifier = reuseIdentifier self.paused = false super.init() } func numberOfSections(in tableView: UITableView) -> Int { if let sections = fetchedResultsController.sections { return sections.count } return 0 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let sections = fetchedResultsController.sections { let sectionInfo = sections[section] return sectionInfo.numberOfObjects } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let object = fetchedResultsController.object(at: indexPath) var cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) if let delegate = delegate { delegate.fetchedResultsControllerDataSource(&cell, withObject: object) } return cell } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { if let delegate = delegate { delegate.fetchedResultsControllerDataSource(self.fetchedResultsController.object(at: indexPath)) } } } func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView?.beginUpdates() } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView?.endUpdates() } // codebeat:disable[ARITY] func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { if let indexPath = indexPath, let newIndexPath = newIndexPath, let tableView = tableView { if type == .insert { tableView.insertRows(at: [newIndexPath], with: .automatic) } else if type == .move { tableView.moveRow(at: indexPath, to: newIndexPath) } else if type == .delete { tableView.deleteRows(at: [indexPath], with: .automatic) } else if type == .update { tableView.reloadRows(at: [indexPath], with: .automatic) } } } // codebeat:enable[ARITY] func selectedItem() -> AnyObject? { if let tableView = tableView { if let path = tableView.indexPathForSelectedRow { return self.fetchedResultsController.object(at: path) } } return nil } }
mit
5c669d6c78691cc0e7f76785762be733
35.388889
200
0.654962
6.064815
false
false
false
false
to4iki/conference-app-2017-ios
conference-app-2017/data/util/Regex.swift
1
1419
import Foundation struct Regex { private let internalExpression: NSRegularExpression private let pattern: String init(_ pattern: String) { self.pattern = pattern do { self.internalExpression = try NSRegularExpression(pattern: pattern, options: [.caseInsensitive]) } catch let error as NSError { log.error(error.localizedDescription) self.internalExpression = NSRegularExpression() } } func isMatch(_ input: String) -> Bool { let matches = internalExpression.matches(in: input, options: [], range: NSRange(location: 0, length: input.characters.count)) return matches.count > 0 } func matches(_ input: String) -> [String]? { guard isMatch(input) else { return nil } let matches = internalExpression.matches(in: input, options: [], range: NSRange(location: 0, length: input.characters.count)) return (0..<matches.count).reduce([]) { (acc: [String], n: Int) -> [String] in acc + [(input as NSString).substring(with: matches[n].range)] } } func replace(input: String, after: String) -> String { guard let matches = matches(input) else { return input } return (0..<matches.count).reduce(input) { (acc: String, n: Int) -> String in acc.replacingOccurrences(of: matches[n], with: after, options: [], range: nil) } } }
apache-2.0
70f9e0b45a8c68713e96f5d5eb8c96ad
38.416667
133
0.622974
4.366154
false
false
false
false
jemartti/OnTheMap
OnTheMap/ParseConvenience.swift
1
3069
// // ParseConvenience.swift // OnTheMap // // Created by Jacob Marttinen on 3/5/17. // Copyright © 2017 Jacob Marttinen. All rights reserved. // import UIKit import Foundation import CoreLocation // MARK: - ParseClient (Convenient Resource Methods) extension ParseClient { // MARK: GET Convenience Methods func getStudentLocations( _ limit: Int, skip: Int, order: String, completionHandlerForGetStudentLocations: @escaping (_ error: NSError?) -> Void ) { /* Specify parameters */ let parameters = [ ParseClient.ParameterKeys.Limit: limit, ParseClient.ParameterKeys.Skip: skip, ParseClient.ParameterKeys.Order: order ] as [String : Any] /* Make the request */ let _ = taskForGETMethod(Methods.StudentLocation, parameters: parameters as [String:AnyObject]) { (results, error) in /* Send the desired value(s) to completion handler */ if let error = error { completionHandlerForGetStudentLocations(error) } else { if let results = results?[ParseClient.JSONResponseKeys.Results] as? [[String:AnyObject]] { StudentInformation.studentInformations = StudentInformation.studentInformationsFromResults(results) completionHandlerForGetStudentLocations(nil) } else { completionHandlerForGetStudentLocations(NSError( domain: "getStudentLocations parsing", code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not parse getStudentLocations"] )) } } } } // MARK: POST Convenience Methods func postStudentLocation( _ mapString: String, mediaURL: String, coordinates: CLLocationCoordinate2D, completionHandlerForPostSession: @escaping (_ error: NSError?) -> Void ) { /* Specify HTTP body */ let jsonBody = "{\"\(ParseClient.JSONResponseKeys.UniqueKey)\": \"\(UdacityClient.sharedInstance().user!.key)\", \"\(ParseClient.JSONResponseKeys.FirstName)\": \"\(UdacityClient.sharedInstance().user!.firstName)\", \"\(ParseClient.JSONResponseKeys.LastName)\": \"\(UdacityClient.sharedInstance().user!.lastName)\",\"\(ParseClient.JSONResponseKeys.MapString)\": \"\(mapString)\", \"\(ParseClient.JSONResponseKeys.MediaURL)\": \"\(mediaURL)\",\"\(ParseClient.JSONResponseKeys.Latitude)\": \(coordinates.latitude), \"\(ParseClient.JSONResponseKeys.Longitude)\": \(coordinates.longitude)}" /* Make the request */ let _ = taskForPOSTMethod(Methods.StudentLocation, parameters: [:], jsonBody: jsonBody) { (results, error) in if let error = error { completionHandlerForPostSession(error) return } completionHandlerForPostSession(nil) } } }
mit
6bb53b2eb4c779fbf228e8d54fe0510d
38.333333
593
0.601695
5.488372
false
false
false
false
Bunn/firefox-ios
Client/Frontend/Browser/TabTrayController.swift
1
49637
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import SnapKit import Storage import Shared struct TabTrayControllerUX { static let CornerRadius = CGFloat(6.0) static let TextBoxHeight = CGFloat(32.0) static let SearchBarHeight = CGFloat(64) static let FaviconSize = CGFloat(20) static let Margin = CGFloat(15) static let ToolbarButtonOffset = CGFloat(10.0) static let CloseButtonSize = CGFloat(32) static let CloseButtonMargin = CGFloat(6.0) static let CloseButtonEdgeInset = CGFloat(7) static let NumberOfColumnsThin = 1 static let NumberOfColumnsWide = 3 static let CompactNumberOfColumnsThin = 2 static let MenuFixedWidth: CGFloat = 320 } struct PrivateModeStrings { static let toggleAccessibilityLabel = NSLocalizedString("Private Mode", tableName: "PrivateBrowsing", comment: "Accessibility label for toggling on/off private mode") static let toggleAccessibilityHint = NSLocalizedString("Turns private mode on or off", tableName: "PrivateBrowsing", comment: "Accessiblity hint for toggling on/off private mode") static let toggleAccessibilityValueOn = NSLocalizedString("On", tableName: "PrivateBrowsing", comment: "Toggled ON accessibility value") static let toggleAccessibilityValueOff = NSLocalizedString("Off", tableName: "PrivateBrowsing", comment: "Toggled OFF accessibility value") } protocol TabTrayDelegate: AnyObject { func tabTrayDidDismiss(_ tabTray: TabTrayController) func tabTrayDidAddTab(_ tabTray: TabTrayController, tab: Tab) func tabTrayDidAddBookmark(_ tab: Tab) func tabTrayDidAddToReadingList(_ tab: Tab) -> ReadingListItem? func tabTrayRequestsPresentationOf(_ viewController: UIViewController) } class TabTrayController: UIViewController { let tabManager: TabManager let profile: Profile weak var delegate: TabTrayDelegate? var tabDisplayManager: TabDisplayManager! var tabCellIdentifer: TabDisplayer.TabCellIdentifer = TabCell.Identifier var otherBrowsingModeOffset = CGPoint.zero var collectionView: UICollectionView! let statusBarBG = UIView() lazy var toolbar: TrayToolbar = { let toolbar = TrayToolbar() toolbar.addTabButton.addTarget(self, action: #selector(didTapToolbarAddTab), for: .touchUpInside) toolbar.maskButton.addTarget(self, action: #selector(didTogglePrivateMode), for: .touchUpInside) toolbar.deleteButton.addTarget(self, action: #selector(didTapToolbarDelete), for: .touchUpInside) return toolbar }() lazy var searchBar: SearchBarTextField = { let searchBar = SearchBarTextField() searchBar.backgroundColor = UIColor.theme.tabTray.searchBackground searchBar.leftView = UIImageView(image: UIImage(named: "quickSearch")) searchBar.leftViewMode = .unlessEditing searchBar.textColor = UIColor.theme.tabTray.tabTitleText searchBar.attributedPlaceholder = NSAttributedString(string: Strings.TabSearchPlaceholderText, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tabTray.tabTitleText.withAlphaComponent(0.7)]) searchBar.clearButtonMode = .never searchBar.delegate = self searchBar.addTarget(self, action: #selector(textDidChange), for: .editingChanged) return searchBar }() var searchBarHolder = UIView() var roundedSearchBarHolder: UIView = { let roundedView = UIView() roundedView.backgroundColor = UIColor.theme.tabTray.searchBackground roundedView.layer.cornerRadius = 4 roundedView.layer.masksToBounds = true return roundedView }() lazy var cancelButton: UIButton = { let cancelButton = UIButton() cancelButton.setImage(UIImage.templateImageNamed("close-medium"), for: .normal) cancelButton.addTarget(self, action: #selector(didPressCancel), for: .touchUpInside) cancelButton.tintColor = UIColor.theme.tabTray.tabTitleText cancelButton.isHidden = true return cancelButton }() fileprivate lazy var emptyPrivateTabsView: EmptyPrivateTabsView = { let emptyView = EmptyPrivateTabsView() emptyView.learnMoreButton.addTarget(self, action: #selector(didTapLearnMore), for: .touchUpInside) return emptyView }() fileprivate lazy var tabLayoutDelegate: TabLayoutDelegate = { let delegate = TabLayoutDelegate(profile: self.profile, traitCollection: self.traitCollection, scrollView: self.collectionView) delegate.tabSelectionDelegate = self return delegate }() var numberOfColumns: Int { return tabLayoutDelegate.numberOfColumns } init(tabManager: TabManager, profile: Profile, tabTrayDelegate: TabTrayDelegate? = nil) { self.tabManager = tabManager self.profile = profile self.delegate = tabTrayDelegate super.init(nibName: nil, bundle: nil) collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) collectionView.register(TabCell.self, forCellWithReuseIdentifier: TabCell.Identifier) tabDisplayManager = TabDisplayManager(collectionView: self.collectionView, tabManager: self.tabManager, tabDisplayer: self, reuseID: TabCell.Identifier) collectionView.dataSource = tabDisplayManager collectionView.delegate = tabLayoutDelegate collectionView.contentInset = UIEdgeInsets(top: TabTrayControllerUX.SearchBarHeight, left: 0, bottom: 0, right: 0) // these will be animated during view show/hide transition statusBarBG.alpha = 0 searchBarHolder.alpha = 0 tabDisplayManager.tabDisplayCompletionDelegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.view.layoutIfNeeded() } deinit { tabManager.removeDelegate(self.tabDisplayManager) tabManager.removeDelegate(self) tabDisplayManager = nil } func focusTab() { guard let currentTab = tabManager.selectedTab, let index = self.tabDisplayManager.dataStore.index(of: currentTab), let rect = self.collectionView.layoutAttributesForItem(at: IndexPath(item: index, section: 0))?.frame else { return } self.collectionView.scrollRectToVisible(rect, animated: false) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func dynamicFontChanged(_ notification: Notification) { guard notification.name == .DynamicFontChanged else { return } } // MARK: View Controller Callbacks override func viewDidLoad() { super.viewDidLoad() tabManager.addDelegate(self) view.accessibilityLabel = NSLocalizedString("Tabs Tray", comment: "Accessibility label for the Tabs Tray view.") collectionView.alwaysBounceVertical = true collectionView.backgroundColor = UIColor.theme.tabTray.background collectionView.keyboardDismissMode = .onDrag collectionView.dragInteractionEnabled = true collectionView.dragDelegate = tabDisplayManager collectionView.dropDelegate = tabDisplayManager searchBarHolder.addSubview(roundedSearchBarHolder) searchBarHolder.addSubview(searchBar) searchBarHolder.backgroundColor = UIColor.theme.tabTray.toolbar [collectionView, toolbar, searchBarHolder, cancelButton].forEach { view.addSubview($0) } makeConstraints() // The statusBar needs a background color statusBarBG.backgroundColor = UIColor.theme.tabTray.toolbar view.addSubview(statusBarBG) statusBarBG.snp.makeConstraints { make in make.leading.trailing.top.equalTo(self.view) make.bottom.equalTo(self.view.safeArea.top) } view.insertSubview(emptyPrivateTabsView, aboveSubview: collectionView) emptyPrivateTabsView.snp.makeConstraints { make in make.top.left.right.equalTo(self.collectionView) make.bottom.equalTo(self.toolbar.snp.top) } if let tab = tabManager.selectedTab, tab.isPrivate { tabDisplayManager.togglePrivateMode(isOn: true, createTabOnEmptyPrivateMode: false) toolbar.applyUIMode(isPrivate: true) searchBar.applyUIMode(isPrivate: true) } if traitCollection.forceTouchCapability == .available { registerForPreviewing(with: self, sourceView: view) } emptyPrivateTabsView.isHidden = !privateTabsAreEmpty() NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActiveNotification), name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActiveNotification), name: UIApplication.didBecomeActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(dynamicFontChanged), name: .DynamicFontChanged, object: nil) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) // Update the trait collection we reference in our layout delegate tabLayoutDelegate.traitCollection = traitCollection } override var preferredStatusBarStyle: UIStatusBarStyle { //special case for iPad if UIDevice.current.userInterfaceIdiom == .pad && ThemeManager.instance.currentName == .normal { return .default } return ThemeManager.instance.statusBarStyle } fileprivate func makeConstraints() { collectionView.snp.makeConstraints { make in make.left.equalTo(view.safeArea.left) make.right.equalTo(view.safeArea.right) make.bottom.equalTo(toolbar.snp.top) make.top.equalTo(self.view.safeArea.top) } toolbar.snp.makeConstraints { make in make.left.right.bottom.equalTo(view) make.height.equalTo(UIConstants.BottomToolbarHeight) } cancelButton.snp.makeConstraints { make in make.centerY.equalTo(self.roundedSearchBarHolder.snp.centerY) make.trailing.equalTo(self.roundedSearchBarHolder.snp.trailing).offset(-8) } searchBarHolder.snp.makeConstraints { make in make.leading.equalTo(view.snp.leading) make.trailing.equalTo(view.snp.trailing) make.height.equalTo(TabTrayControllerUX.SearchBarHeight) self.tabLayoutDelegate.searchHeightConstraint = make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.top).constraint } roundedSearchBarHolder.snp.makeConstraints { make in make.top.equalTo(searchBarHolder).offset(15) make.leading.equalTo(view.safeArea.leading).offset(10) // we can just make the nested view conform to the safe area make.trailing.equalTo(view.safeArea.trailing).offset(-10) make.bottom.equalTo(searchBarHolder).offset(-10) } searchBar.snp.makeConstraints { make in make.edges.equalTo(roundedSearchBarHolder).inset(UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)) } } @objc func didTogglePrivateMode() { if tabDisplayManager.isDragging { return } toolbar.isUserInteractionEnabled = false let scaleDownTransform = CGAffineTransform(scaleX: 0.9, y: 0.9) let newOffset = CGPoint(x: 0.0, y: collectionView.contentOffset.y) if self.otherBrowsingModeOffset.y > 0 { collectionView.setContentOffset(self.otherBrowsingModeOffset, animated: false) } self.otherBrowsingModeOffset = newOffset let fromView: UIView if !privateTabsAreEmpty(), let snapshot = collectionView.snapshotView(afterScreenUpdates: false) { snapshot.frame = collectionView.frame view.insertSubview(snapshot, aboveSubview: collectionView) fromView = snapshot } else { fromView = emptyPrivateTabsView } tabDisplayManager.togglePrivateMode(isOn: !tabDisplayManager.isPrivate, createTabOnEmptyPrivateMode: false) tabManager.willSwitchTabMode(leavingPBM: tabDisplayManager.isPrivate) if tabDisplayManager.isPrivate, privateTabsAreEmpty() { UIView.animate(withDuration: 0.2) { self.searchBarHolder.alpha = 0 } } else { UIView.animate(withDuration: 0.2) { self.searchBarHolder.alpha = 1 } } if tabDisplayManager.searchActive { self.didPressCancel() } else { self.tabDisplayManager.refreshStore() } // If we are exiting private mode and we have the close private tabs option selected, make sure // we clear out all of the private tabs let exitingPrivateMode = !tabDisplayManager.isPrivate && tabManager.shouldClearPrivateTabs() toolbar.maskButton.setSelected(tabDisplayManager.isPrivate, animated: true) collectionView.layoutSubviews() let toView: UIView if !privateTabsAreEmpty(), let newSnapshot = collectionView.snapshotView(afterScreenUpdates: !exitingPrivateMode) { emptyPrivateTabsView.isHidden = true //when exiting private mode don't screenshot the collectionview (causes the UI to hang) newSnapshot.frame = collectionView.frame view.insertSubview(newSnapshot, aboveSubview: fromView) collectionView.alpha = 0 toView = newSnapshot } else { emptyPrivateTabsView.isHidden = false toView = emptyPrivateTabsView } toView.alpha = 0 toView.transform = scaleDownTransform UIView.animate(withDuration: 0.2, delay: 0, options: [], animations: { () -> Void in fromView.transform = scaleDownTransform fromView.alpha = 0 toView.transform = .identity toView.alpha = 1 }) { finished in if fromView != self.emptyPrivateTabsView { fromView.removeFromSuperview() } if toView != self.emptyPrivateTabsView { toView.removeFromSuperview() } self.collectionView.alpha = 1 self.toolbar.isUserInteractionEnabled = true // A final reload to ensure no animations happen while completing the transition. self.tabDisplayManager.refreshStore() } toolbar.applyUIMode(isPrivate: tabDisplayManager.isPrivate) searchBar.applyUIMode(isPrivate: tabDisplayManager.isPrivate) if let search = searchBar.text, !search.isEmpty { searchTabs(for: search) } } fileprivate func privateTabsAreEmpty() -> Bool { return tabDisplayManager.isPrivate && tabManager.privateTabs.isEmpty } @objc func didTapToolbarAddTab() { if tabDisplayManager.isDragging { return } openNewTab() } func openNewTab(_ request: URLRequest? = nil) { if tabDisplayManager.isDragging { return } // We dismiss the tab tray once we are done. So no need to re-enable the toolbar toolbar.isUserInteractionEnabled = false tabManager.selectTab(tabManager.addTab(request, isPrivate: tabDisplayManager.isPrivate)) } } extension TabTrayController: TabManagerDelegate { func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?, isRestoring: Bool) {} func tabManager(_ tabManager: TabManager, didAddTab tab: Tab, isRestoring: Bool) {} func tabManager(_ tabManager: TabManager, didRemoveTab tab: Tab, isRestoring: Bool) { if tabDisplayManager.isPrivate, privateTabsAreEmpty() { UIView.animate(withDuration: 0.2) { self.searchBarHolder.alpha = 0 } } } func tabManagerDidRestoreTabs(_ tabManager: TabManager) { self.emptyPrivateTabsView.isHidden = !self.privateTabsAreEmpty() } func tabManagerDidAddTabs(_ tabManager: TabManager) { if tabDisplayManager.isPrivate { UIView.animate(withDuration: 0.2) { self.searchBarHolder.alpha = 1 } } } func tabManagerDidRemoveAllTabs(_ tabManager: TabManager, toast: ButtonToast?) { // No need to handle removeAll toast in TabTray. // When closing all normal tabs we automatically focus a tab and show the BVC. Which will handle the Toast. // We don't show the removeAll toast in PBM } } extension TabTrayController: UITextFieldDelegate { @objc func didPressCancel() { clearSearch() UIView.animate(withDuration: 0.1) { self.cancelButton.isHidden = true } self.searchBar.resignFirstResponder() } @objc func textDidChange(textField: UITextField) { guard let text = textField.text, !text.isEmpty else { clearSearch() return } searchTabs(for: text) } func textFieldDidBeginEditing(_ textField: UITextField) { UIView.animate(withDuration: 0.1) { self.cancelButton.isHidden = false } } func searchTabs(for searchString: String) { let currentTabs = self.tabDisplayManager.isPrivate ? self.tabManager.privateTabs : self.tabManager.normalTabs let filteredTabs = currentTabs.filter { tab in if let url = tab.url, InternalURL.isValid(url: url) { return false } let title = tab.title ?? tab.lastTitle if title?.lowercased().range(of: searchString.lowercased()) != nil { return true } if tab.url?.absoluteString.lowercased().range(of: searchString.lowercased()) != nil { return true } return false } tabDisplayManager.searchedTabs = filteredTabs tabDisplayManager.searchTabsAnimated() } func clearSearch() { tabDisplayManager.searchedTabs = nil searchBar.text = "" tabDisplayManager.refreshStore() } } extension TabTrayController: TabDisplayer { func focusSelectedTab() { self.focusTab() } func cellFactory(for cell: UICollectionViewCell, using tab: Tab) -> UICollectionViewCell { guard let tabCell = cell as? TabCell else { return cell } tabCell.animator.delegate = self tabCell.delegate = self let selected = tab == tabManager.selectedTab tabCell.configureWith(tab: tab, is: selected) return tabCell } } extension TabTrayController { @objc func didTapLearnMore() { let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String if let langID = Locale.preferredLanguages.first { let learnMoreRequest = URLRequest(url: "https://support.mozilla.org/1/mobile/\(appVersion ?? "0.0")/iOS/\(langID)/private-browsing-ios".asURL!) openNewTab(learnMoreRequest) } } func closeTabsForCurrentTray() { tabDisplayManager.hideDisplayedTabs() { self.tabManager.removeTabsWithUndoToast(self.tabDisplayManager.dataStore.compactMap { $0 }) if self.tabDisplayManager.isPrivate { self.emptyPrivateTabsView.isHidden = !self.privateTabsAreEmpty() if !self.emptyPrivateTabsView.isHidden { // Fade in the empty private tabs message. This slow fade allows time for the closing tab animations to complete. self.emptyPrivateTabsView.alpha = 0 UIView.animate(withDuration: 0.5, animations: { self.emptyPrivateTabsView.alpha = 1 }, completion: nil) } } else if self.tabManager.normalTabs.count == 1, let tab = self.tabManager.normalTabs.first { self.tabManager.selectTab(tab) self.dismissTabTray() } } } func changePrivacyMode(_ isPrivate: Bool) { if isPrivate != tabDisplayManager.isPrivate { didTogglePrivateMode() } } func dismissTabTray() { collectionView.layer.removeAllAnimations() collectionView.cellForItem(at: IndexPath(row: 0, section: 0))?.layer.removeAllAnimations() _ = self.navigationController?.popViewController(animated: true) } } // MARK: - App Notifications extension TabTrayController { @objc func appWillResignActiveNotification() { if tabDisplayManager.isPrivate { collectionView.alpha = 0 searchBarHolder.alpha = 0 } } @objc func appDidBecomeActiveNotification() { // Re-show any components that might have been hidden because they were being displayed // as part of a private mode tab UIView.animate(withDuration: 0.2) { self.collectionView.alpha = 1 if self.tabDisplayManager.isPrivate, !self.privateTabsAreEmpty() { self.searchBarHolder.alpha = 1 } } } } extension TabTrayController: TabSelectionDelegate { func didSelectTabAtIndex(_ index: Int) { if let tab = tabDisplayManager.dataStore.at(index) { tabManager.selectTab(tab) dismissTabTray() } } } extension TabTrayController: PresentingModalViewControllerDelegate { func dismissPresentedModalViewController(_ modalViewController: UIViewController, animated: Bool) { dismiss(animated: animated, completion: { self.collectionView.reloadData() }) } } extension TabTrayController: UIScrollViewAccessibilityDelegate { func accessibilityScrollStatus(for scrollView: UIScrollView) -> String? { guard var visibleCells = collectionView.visibleCells as? [TabCell] else { return nil } var bounds = collectionView.bounds bounds = bounds.offsetBy(dx: collectionView.contentInset.left, dy: collectionView.contentInset.top) bounds.size.width -= collectionView.contentInset.left + collectionView.contentInset.right bounds.size.height -= collectionView.contentInset.top + collectionView.contentInset.bottom // visible cells do sometimes return also not visible cells when attempting to go past the last cell with VoiceOver right-flick gesture; so make sure we have only visible cells (yeah...) visibleCells = visibleCells.filter { !$0.frame.intersection(bounds).isEmpty } let cells = visibleCells.map { self.collectionView.indexPath(for: $0)! } let indexPaths = cells.sorted { (a: IndexPath, b: IndexPath) -> Bool in return a.section < b.section || (a.section == b.section && a.row < b.row) } guard !indexPaths.isEmpty else { return NSLocalizedString("No tabs", comment: "Message spoken by VoiceOver to indicate that there are no tabs in the Tabs Tray") } let firstTab = indexPaths.first!.row + 1 let lastTab = indexPaths.last!.row + 1 let tabCount = collectionView.numberOfItems(inSection: 0) if firstTab == lastTab { let format = NSLocalizedString("Tab %@ of %@", comment: "Message spoken by VoiceOver saying the position of the single currently visible tab in Tabs Tray, along with the total number of tabs. E.g. \"Tab 2 of 5\" says that tab 2 is visible (and is the only visible tab), out of 5 tabs total.") return String(format: format, NSNumber(value: firstTab as Int), NSNumber(value: tabCount as Int)) } else { let format = NSLocalizedString("Tabs %@ to %@ of %@", comment: "Message spoken by VoiceOver saying the range of tabs that are currently visible in Tabs Tray, along with the total number of tabs. E.g. \"Tabs 8 to 10 of 15\" says tabs 8, 9 and 10 are visible, out of 15 tabs total.") return String(format: format, NSNumber(value: firstTab as Int), NSNumber(value: lastTab as Int), NSNumber(value: tabCount as Int)) } } } extension TabTrayController: SwipeAnimatorDelegate { func swipeAnimator(_ animator: SwipeAnimator, viewWillExitContainerBounds: UIView) { guard let tabCell = animator.animatingView as? TabCell, let indexPath = collectionView.indexPath(for: tabCell) else { return } if let tab = tabDisplayManager.dataStore.at(indexPath.item) { self.removeByButtonOrSwipe(tab: tab, cell: tabCell) UIAccessibility.post(notification: UIAccessibility.Notification.announcement, argument: NSLocalizedString("Closing tab", comment: "Accessibility label (used by assistive technology) notifying the user that the tab is being closed.")) } } // Disable swipe delete while drag reordering func swipeAnimatorIsAnimateAwayEnabled(_ animator: SwipeAnimator) -> Bool { return !tabDisplayManager.isDragging } } extension TabTrayController: TabCellDelegate { func tabCellDidClose(_ cell: TabCell) { if let indexPath = collectionView.indexPath(for: cell), let tab = tabDisplayManager.dataStore.at(indexPath.item) { removeByButtonOrSwipe(tab: tab, cell: cell) } } } extension TabTrayController: TabPeekDelegate { func tabPeekDidAddBookmark(_ tab: Tab) { delegate?.tabTrayDidAddBookmark(tab) } func tabPeekDidAddToReadingList(_ tab: Tab) -> ReadingListItem? { return delegate?.tabTrayDidAddToReadingList(tab) } func tabPeekDidCloseTab(_ tab: Tab) { if let index = tabDisplayManager.dataStore.index(of: tab), let cell = self.collectionView?.cellForItem(at: IndexPath(item: index, section: 0)) as? TabCell { cell.close() } } func tabPeekRequestsPresentationOf(_ viewController: UIViewController) { delegate?.tabTrayRequestsPresentationOf(viewController) } } extension TabTrayController: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let collectionView = collectionView else { return nil } let convertedLocation = self.view.convert(location, to: collectionView) guard let indexPath = collectionView.indexPathForItem(at: convertedLocation), let cell = collectionView.cellForItem(at: indexPath) else { return nil } guard let tab = tabDisplayManager.dataStore.at(indexPath.row) else { return nil } let tabVC = TabPeekViewController(tab: tab, delegate: self) if let browserProfile = profile as? BrowserProfile { tabVC.setState(withProfile: browserProfile, clientPickerDelegate: self) } previewingContext.sourceRect = self.view.convert(cell.frame, from: collectionView) return tabVC } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { guard let tpvc = viewControllerToCommit as? TabPeekViewController else { return } tabManager.selectTab(tpvc.tab) navigationController?.popViewController(animated: true) delegate?.tabTrayDidDismiss(self) } } extension TabTrayController: TabDisplayCompletionDelegate { func completedAnimation(for type: TabAnimationType) { emptyPrivateTabsView.isHidden = !privateTabsAreEmpty() switch type { case .addTab: dismissTabTray() LeanPlumClient.shared.track(event: .openedNewTab, withParameters: ["Source": "Tab Tray"]) case .removedLastTab: // when removing the last tab (only in normal mode) we will automatically open a new tab. // When that happens focus it by dismissing the tab tray if !tabDisplayManager.isPrivate { self.dismissTabTray() } case .removedNonLastTab, .updateTab, .moveTab: break } } } extension TabTrayController { func removeByButtonOrSwipe(tab: Tab, cell: TabCell) { tabDisplayManager.tabDisplayCompletionDelegate = self tabDisplayManager.closeActionPerformed(forCell: cell) } } extension TabTrayController { @objc func didTapToolbarDelete(_ sender: UIButton) { if tabDisplayManager.isDragging { return } let controller = AlertController(title: nil, message: nil, preferredStyle: .actionSheet) controller.addAction(UIAlertAction(title: Strings.AppMenuCloseAllTabsTitleString, style: .default, handler: { _ in self.closeTabsForCurrentTray() }), accessibilityIdentifier: "TabTrayController.deleteButton.closeAll") controller.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label for Cancel button"), style: .cancel, handler: nil), accessibilityIdentifier: "TabTrayController.deleteButton.cancel") controller.popoverPresentationController?.sourceView = sender controller.popoverPresentationController?.sourceRect = sender.bounds present(controller, animated: true, completion: nil) } } fileprivate class TabLayoutDelegate: NSObject, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate { weak var tabSelectionDelegate: TabSelectionDelegate? var searchHeightConstraint: Constraint? let scrollView: UIScrollView var lastYOffset: CGFloat = 0 enum ScrollDirection { case up case down } fileprivate var scrollDirection: ScrollDirection = .down fileprivate var traitCollection: UITraitCollection fileprivate var numberOfColumns: Int { // iPhone 4-6+ portrait if traitCollection.horizontalSizeClass == .compact && traitCollection.verticalSizeClass == .regular { return TabTrayControllerUX.CompactNumberOfColumnsThin } else { return TabTrayControllerUX.NumberOfColumnsWide } } init(profile: Profile, traitCollection: UITraitCollection, scrollView: UIScrollView) { self.scrollView = scrollView self.traitCollection = traitCollection super.init() } func clamp(_ y: CGFloat, min: CGFloat, max: CGFloat) -> CGFloat { if y >= max { return max } else if y <= min { return min } return y } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if decelerate { if scrollDirection == .up { hideSearch() } } } func checkRubberbandingForDelta(_ delta: CGFloat, for scrollView: UIScrollView) -> Bool { if scrollView.contentOffset.y < 0 { return true } else { return false } } func scrollViewDidScroll(_ scrollView: UIScrollView) { let float = scrollView.contentOffset.y defer { self.lastYOffset = float } let delta = lastYOffset - float if delta > 0 { scrollDirection = .down } else if delta < 0 { scrollDirection = .up } if checkRubberbandingForDelta(delta, for: scrollView) { let offset = clamp(abs(scrollView.contentOffset.y), min: 0, max: TabTrayControllerUX.SearchBarHeight) searchHeightConstraint?.update(offset: offset) if scrollDirection == .down { scrollView.contentInset = UIEdgeInsets(top: offset, left: 0, bottom: 0, right: 0) } } else { self.hideSearch() } } func showSearch() { searchHeightConstraint?.update(offset: TabTrayControllerUX.SearchBarHeight) scrollView.contentInset = UIEdgeInsets(top: TabTrayControllerUX.SearchBarHeight, left: 0, bottom: 0, right: 0) } func hideSearch() { searchHeightConstraint?.update(offset: 0) scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) } fileprivate func cellHeightForCurrentDevice() -> CGFloat { let shortHeight = TabTrayControllerUX.TextBoxHeight * 6 if self.traitCollection.verticalSizeClass == .compact { return shortHeight } else if self.traitCollection.horizontalSizeClass == .compact { return shortHeight } else { return TabTrayControllerUX.TextBoxHeight * 8 } } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } @objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return TabTrayControllerUX.Margin } @objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let cellWidth = floor((collectionView.bounds.width - TabTrayControllerUX.Margin * CGFloat(numberOfColumns + 1)) / CGFloat(numberOfColumns)) return CGSize(width: cellWidth, height: self.cellHeightForCurrentDevice()) } @objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(equalInset: TabTrayControllerUX.Margin) } @objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return TabTrayControllerUX.Margin } @objc func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { tabSelectionDelegate?.didSelectTabAtIndex(indexPath.row) } } private struct EmptyPrivateTabsViewUX { static let TitleFont = UIFont.systemFont(ofSize: 22, weight: UIFont.Weight.medium) static let DescriptionFont = UIFont.systemFont(ofSize: 17) static let LearnMoreFont = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium) static let TextMargin: CGFloat = 18 static let LearnMoreMargin: CGFloat = 30 static let MaxDescriptionWidth: CGFloat = 250 static let MinBottomMargin: CGFloat = 10 } // View we display when there are no private tabs created fileprivate class EmptyPrivateTabsView: UIView { fileprivate lazy var titleLabel: UILabel = { let label = UILabel() label.textColor = UIColor.Photon.White100 label.font = EmptyPrivateTabsViewUX.TitleFont label.textAlignment = .center return label }() fileprivate var descriptionLabel: UILabel = { let label = UILabel() label.textColor = UIColor.Photon.White100 label.font = EmptyPrivateTabsViewUX.DescriptionFont label.textAlignment = .center label.numberOfLines = 0 label.preferredMaxLayoutWidth = EmptyPrivateTabsViewUX.MaxDescriptionWidth return label }() fileprivate var learnMoreButton: UIButton = { let button = UIButton(type: .system) button.setTitle( NSLocalizedString("Learn More", tableName: "PrivateBrowsing", comment: "Text button displayed when there are no tabs open while in private mode"), for: []) button.setTitleColor(UIColor.theme.tabTray.privateModeLearnMore, for: []) button.titleLabel?.font = EmptyPrivateTabsViewUX.LearnMoreFont return button }() fileprivate var iconImageView: UIImageView = { let imageView = UIImageView(image: UIImage.templateImageNamed("largePrivateMask")) imageView.tintColor = UIColor.Photon.Grey60 return imageView }() override init(frame: CGRect) { super.init(frame: frame) titleLabel.text = NSLocalizedString("Private Browsing", tableName: "PrivateBrowsing", comment: "Title displayed for when there are no open tabs while in private mode") descriptionLabel.text = NSLocalizedString("Firefox won’t remember any of your history or cookies, but new bookmarks will be saved.", tableName: "PrivateBrowsing", comment: "Description text displayed when there are no open tabs while in private mode") addSubview(titleLabel) addSubview(descriptionLabel) addSubview(iconImageView) addSubview(learnMoreButton) titleLabel.snp.makeConstraints { make in make.center.equalTo(self) } iconImageView.snp.makeConstraints { make in make.bottom.equalTo(titleLabel.snp.top) make.height.width.equalTo(120) make.centerX.equalTo(self) } descriptionLabel.snp.makeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(EmptyPrivateTabsViewUX.TextMargin) make.centerX.equalTo(self) } learnMoreButton.snp.makeConstraints { (make) -> Void in make.top.equalTo(descriptionLabel.snp.bottom).offset(EmptyPrivateTabsViewUX.LearnMoreMargin).priority(10) make.bottom.lessThanOrEqualTo(self).offset(-EmptyPrivateTabsViewUX.MinBottomMargin).priority(1000) make.centerX.equalTo(self) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension TabTrayController: DevicePickerViewControllerDelegate { func devicePickerViewController(_ devicePickerViewController: DevicePickerViewController, didPickDevices devices: [RemoteDevice]) { if let item = devicePickerViewController.shareItem { _ = self.profile.sendItem(item, toDevices: devices) } devicePickerViewController.dismiss(animated: true, completion: nil) } func devicePickerViewControllerDidCancel(_ devicePickerViewController: DevicePickerViewController) { devicePickerViewController.dismiss(animated: true, completion: nil) } } extension TabTrayController: UIAdaptivePresentationControllerDelegate, UIPopoverPresentationControllerDelegate { // Returning None here makes sure that the Popover is actually presented as a Popover and // not as a full-screen modal, which is the default on compact device classes. func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .none } } // MARK: - Toolbar class TrayToolbar: UIView, Themeable, PrivateModeUI { fileprivate let toolbarButtonSize = CGSize(width: 44, height: 44) lazy var addTabButton: UIButton = { let button = UIButton() button.setImage(UIImage.templateImageNamed("nav-add"), for: .normal) button.accessibilityLabel = NSLocalizedString("Add Tab", comment: "Accessibility label for the Add Tab button in the Tab Tray.") button.accessibilityIdentifier = "TabTrayController.addTabButton" return button }() lazy var deleteButton: UIButton = { let button = UIButton() button.setImage(UIImage.templateImageNamed("action_delete"), for: .normal) button.accessibilityLabel = Strings.TabTrayDeleteMenuButtonAccessibilityLabel button.accessibilityIdentifier = "TabTrayController.removeTabsButton" return button }() lazy var maskButton = PrivateModeButton() fileprivate let sideOffset: CGFloat = 32 fileprivate override init(frame: CGRect) { super.init(frame: frame) addSubview(addTabButton) var buttonToCenter: UIButton? addSubview(deleteButton) buttonToCenter = deleteButton maskButton.accessibilityIdentifier = "TabTrayController.maskButton" buttonToCenter?.snp.makeConstraints { make in make.centerX.equalTo(self) make.top.equalTo(self) make.size.equalTo(toolbarButtonSize) } addTabButton.snp.makeConstraints { make in make.top.equalTo(self) make.trailing.equalTo(self).offset(-sideOffset) make.size.equalTo(toolbarButtonSize) } addSubview(maskButton) maskButton.snp.makeConstraints { make in make.top.equalTo(self) make.leading.equalTo(self).offset(sideOffset) make.size.equalTo(toolbarButtonSize) } applyTheme() applyUIMode(isPrivate: false) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func applyUIMode(isPrivate: Bool) { maskButton.applyUIMode(isPrivate: isPrivate) } func applyTheme() { [addTabButton, deleteButton].forEach { $0.tintColor = UIColor.theme.tabTray.toolbarButtonTint } backgroundColor = UIColor.theme.tabTray.toolbar maskButton.offTint = UIColor.theme.tabTray.privateModeButtonOffTint maskButton.onTint = UIColor.theme.tabTray.privateModeButtonOnTint } } protocol TabCellDelegate: AnyObject { func tabCellDidClose(_ cell: TabCell) } class TabCell: UICollectionViewCell { enum Style { case light case dark } static let Identifier = "TabCellIdentifier" static let BorderWidth: CGFloat = 3 let backgroundHolder: UIView = { let view = UIView() view.layer.cornerRadius = TabTrayControllerUX.CornerRadius view.clipsToBounds = true view.backgroundColor = UIColor.theme.tabTray.cellBackground return view }() let screenshotView: UIImageViewAligned = { let view = UIImageViewAligned() view.contentMode = .scaleAspectFill view.clipsToBounds = true view.isUserInteractionEnabled = false view.alignLeft = true view.alignTop = true view.backgroundColor = UIColor.theme.browser.background return view }() let titleText: UILabel = { let label = UILabel() label.isUserInteractionEnabled = false label.numberOfLines = 1 label.font = DynamicFontHelper.defaultHelper.DefaultSmallFontBold label.textColor = UIColor.theme.tabTray.tabTitleText return label }() let favicon: UIImageView = { let favicon = UIImageView() favicon.backgroundColor = UIColor.clear favicon.layer.cornerRadius = 2.0 favicon.layer.masksToBounds = true return favicon }() let closeButton: UIButton = { let button = UIButton() button.setImage(UIImage.templateImageNamed("tab_close"), for: []) button.imageView?.contentMode = .scaleAspectFit button.contentMode = .center button.tintColor = UIColor.theme.tabTray.cellCloseButton button.imageEdgeInsets = UIEdgeInsets(equalInset: TabTrayControllerUX.CloseButtonEdgeInset) return button }() var title = UIVisualEffectView(effect: UIBlurEffect(style: UIColor.theme.tabTray.tabTitleBlur)) var animator: SwipeAnimator! weak var delegate: TabCellDelegate? // Changes depending on whether we're full-screen or not. var margin = CGFloat(0) override init(frame: CGRect) { super.init(frame: frame) self.animator = SwipeAnimator(animatingView: self) self.closeButton.addTarget(self, action: #selector(close), for: .touchUpInside) contentView.addSubview(backgroundHolder) backgroundHolder.addSubview(self.screenshotView) self.accessibilityCustomActions = [ UIAccessibilityCustomAction(name: NSLocalizedString("Close", comment: "Accessibility label for action denoting closing a tab in tab list (tray)"), target: self.animator, selector: #selector(SwipeAnimator.closeWithoutGesture)) ] backgroundHolder.addSubview(title) title.contentView.addSubview(self.closeButton) title.contentView.addSubview(self.titleText) title.contentView.addSubview(self.favicon) title.snp.makeConstraints { (make) in make.top.left.right.equalTo(backgroundHolder) make.height.equalTo(TabTrayControllerUX.TextBoxHeight) } favicon.snp.makeConstraints { make in make.leading.equalTo(title.contentView).offset(6) make.top.equalTo((TabTrayControllerUX.TextBoxHeight - TabTrayControllerUX.FaviconSize) / 2) make.size.equalTo(TabTrayControllerUX.FaviconSize) } titleText.snp.makeConstraints { (make) in make.leading.equalTo(favicon.snp.trailing).offset(6) make.trailing.equalTo(closeButton.snp.leading).offset(-6) make.centerY.equalTo(title.contentView) } closeButton.snp.makeConstraints { make in make.size.equalTo(TabTrayControllerUX.CloseButtonSize) make.centerY.trailing.equalTo(title.contentView) } } func setTabSelected(_ isPrivate: Bool) { // This creates a border around a tabcell. Using the shadow craetes a border _outside_ of the tab frame. layer.shadowColor = (isPrivate ? UIColor.theme.tabTray.privateModePurple : UIConstants.SystemBlueColor).cgColor layer.shadowOpacity = 1 layer.shadowRadius = 0 // A 0 radius creates a solid border instead of a gradient blur layer.masksToBounds = false // create a frame that is "BorderWidth" size bigger than the cell layer.shadowOffset = CGSize(width: -TabCell.BorderWidth, height: -TabCell.BorderWidth) let shadowPath = CGRect(width: layer.frame.width + (TabCell.BorderWidth * 2), height: layer.frame.height + (TabCell.BorderWidth * 2)) layer.shadowPath = UIBezierPath(roundedRect: shadowPath, cornerRadius: TabTrayControllerUX.CornerRadius+TabCell.BorderWidth).cgPath } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() backgroundHolder.frame = CGRect(x: margin, y: margin, width: frame.width, height: frame.height) screenshotView.frame = CGRect(size: backgroundHolder.frame.size) let shadowPath = CGRect(width: layer.frame.width + (TabCell.BorderWidth * 2), height: layer.frame.height + (TabCell.BorderWidth * 2)) layer.shadowPath = UIBezierPath(roundedRect: shadowPath, cornerRadius: TabTrayControllerUX.CornerRadius+TabCell.BorderWidth).cgPath } func configureWith(tab: Tab, is selected: Bool) { titleText.text = tab.displayTitle if !tab.displayTitle.isEmpty { accessibilityLabel = tab.displayTitle } else if let url = tab.url, let about = InternalURL(url)?.aboutComponent { accessibilityLabel = about } else { accessibilityLabel = "" } isAccessibilityElement = true accessibilityHint = NSLocalizedString("Swipe right or left with three fingers to close the tab.", comment: "Accessibility hint for tab tray's displayed tab.") if let favIcon = tab.displayFavicon, let url = URL(string: favIcon.url) { favicon.sd_setImage(with: url, placeholderImage: UIImage(named: "defaultFavicon"), options: [], completed: nil) } else { let defaultFavicon = UIImage(named: "defaultFavicon") if tab.isPrivate { favicon.image = defaultFavicon favicon.tintColor = UIColor.theme.tabTray.faviconTint } else { favicon.image = defaultFavicon } } if selected { setTabSelected(tab.isPrivate) } else { layer.shadowOffset = .zero layer.shadowPath = nil layer.shadowOpacity = 0 } screenshotView.image = tab.screenshot } override func prepareForReuse() { // Reset any close animations. super.prepareForReuse() backgroundHolder.transform = .identity backgroundHolder.alpha = 1 self.titleText.font = DynamicFontHelper.defaultHelper.DefaultSmallFontBold layer.shadowOffset = .zero layer.shadowPath = nil layer.shadowOpacity = 0 isHidden = false } override func accessibilityScroll(_ direction: UIAccessibilityScrollDirection) -> Bool { var right: Bool switch direction { case .left: right = false case .right: right = true default: return false } animator.close(right: right) return true } @objc func close() { delegate?.tabCellDidClose(self) } } class SearchBarTextField: UITextField, PrivateModeUI { static let leftInset = CGFloat(18) func applyUIMode(isPrivate: Bool) { tintColor = UIColor.theme.urlbar.textSelectionHighlight(isPrivate).textFieldMode } override func textRect(forBounds bounds: CGRect) -> CGRect { return bounds.insetBy(dx: SearchBarTextField.leftInset, dy: 0) } override func placeholderRect(forBounds bounds: CGRect) -> CGRect { return bounds.insetBy(dx: SearchBarTextField.leftInset, dy: 0) } override func editingRect(forBounds bounds: CGRect) -> CGRect { return bounds.insetBy(dx: SearchBarTextField.leftInset, dy: 0) } }
mpl-2.0
32676b451f2428558b233fb0c821fb2f
39.61784
304
0.681011
5.331937
false
false
false
false
gaolichuang/actor-platform
actor-apps/app-ios/ActorApp/WallpapperPreviewCell.swift
3
761
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation class WallpapperPreviewCell: UICollectionViewCell { private let imageView = UIImageView() override init(frame: CGRect) { super.init(frame: frame) imageView.contentMode = .ScaleAspectFill imageView.clipsToBounds = true self.contentView.addSubview(imageView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func bind(index: Int) { imageView.image = UIImage(named: "bg_\(index + 1).jpg") } override func layoutSubviews() { super.layoutSubviews() imageView.frame = contentView.bounds } }
mit
b6d1a78eac5d7964bc238b2f5be71cc4
22.090909
63
0.61498
4.668712
false
false
false
false
february29/Learning
swift/ReactiveCocoaDemo/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift
132
3231
// // SwitchIfEmpty.swift // RxSwift // // Created by sergdort on 23/12/2016. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Returns the elements of the specified sequence or `switchTo` sequence if the sequence is empty. - seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html) - parameter switchTo: Observable sequence being returned when source sequence is empty. - returns: Observable sequence that contains elements from switchTo sequence if source is empty, otherwise returns source sequence elements. */ public func ifEmpty(switchTo other: Observable<E>) -> Observable<E> { return SwitchIfEmpty(source: asObservable(), ifEmpty: other) } } final fileprivate class SwitchIfEmpty<Element>: Producer<Element> { private let _source: Observable<E> private let _ifEmpty: Observable<E> init(source: Observable<E>, ifEmpty: Observable<E>) { _source = source _ifEmpty = ifEmpty } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = SwitchIfEmptySink(ifEmpty: _ifEmpty, observer: observer, cancel: cancel) let subscription = sink.run(_source.asObservable()) return (sink: sink, subscription: subscription) } } final fileprivate class SwitchIfEmptySink<O: ObserverType>: Sink<O> , ObserverType { typealias E = O.E private let _ifEmpty: Observable<E> private var _isEmpty = true private let _ifEmptySubscription = SingleAssignmentDisposable() init(ifEmpty: Observable<E>, observer: O, cancel: Cancelable) { _ifEmpty = ifEmpty super.init(observer: observer, cancel: cancel) } func run(_ source: Observable<O.E>) -> Disposable { let subscription = source.subscribe(self) return Disposables.create(subscription, _ifEmptySubscription) } func on(_ event: Event<E>) { switch event { case .next: _isEmpty = false forwardOn(event) case .error: forwardOn(event) dispose() case .completed: guard _isEmpty else { forwardOn(.completed) dispose() return } let ifEmptySink = SwitchIfEmptySinkIter(parent: self) _ifEmptySubscription.setDisposable(_ifEmpty.subscribe(ifEmptySink)) } } } final fileprivate class SwitchIfEmptySinkIter<O: ObserverType> : ObserverType { typealias E = O.E typealias Parent = SwitchIfEmptySink<O> private let _parent: Parent init(parent: Parent) { _parent = parent } func on(_ event: Event<E>) { switch event { case .next: _parent.forwardOn(event) case .error: _parent.forwardOn(event) _parent.dispose() case .completed: _parent.forwardOn(event) _parent.dispose() } } }
mit
d7fae164d448f47ab69ddfb7231305aa
30.057692
145
0.611765
4.627507
false
false
false
false
sheepy1/SelectionOfZhihu
SelectionOfZhihu/UserInfoModel.swift
1
462
// // UserDetail.swift // SelectionOfZhihu // // Created by 杨洋 on 16/1/20. // Copyright © 2016年 Sheepy. All rights reserved. // import Foundation class UserInfoModel: NSObject { var name = "" var avatar = "" var signature = "" //var desc = "" //直接声明成 UserDetail 类型也没用,并不会自动转换成 UserDetail 类型 var detail: AnyObject! var star: AnyObject! var trend = [] var topanswers = [] }
mit
62c21980341771af33b3370225aa728e
18.714286
51
0.624697
3.5
false
false
false
false
codefellows/sea-b23-iOS
corelocationdemo/corelocationdemo/ViewController.swift
1
4810
// // ViewController.swift // corelocationdemo // // Created by Bradley Johnson on 11/3/14. // Copyright (c) 2014 Code Fellows. All rights reserved. // import UIKit import MapKit class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate { let locationManager = CLLocationManager() @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "reminderAdded:", name: "REMINDER_ADDED", object: nil) let longPress = UILongPressGestureRecognizer(target: self, action: "didLongPressMap:") self.mapView.addGestureRecognizer(longPress) self.locationManager.delegate = self self.mapView.delegate = self switch CLLocationManager.authorizationStatus() as CLAuthorizationStatus { case .Authorized: println("authorized") //self.locationManager.startUpdatingLocation() self.mapView.showsUserLocation = true case .NotDetermined: println("not determined") self.locationManager.requestAlwaysAuthorization() case .Restricted: println("restricted") case .Denied: println("denied") default: println("default") } // Do any additional setup after loading the view, typically from a nib. } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } func didLongPressMap(sender : UILongPressGestureRecognizer) { //println("long press!") if sender.state == UIGestureRecognizerState.Began { let touchPoint = sender.locationInView(self.mapView) let touchCoordinate = self.mapView.convertPoint(touchPoint, toCoordinateFromView: self.mapView) println("\(touchCoordinate.latitude) \(touchCoordinate.longitude)") var annotation = MKPointAnnotation() annotation.coordinate = touchCoordinate annotation.title = "Add Reminder" self.mapView.addAnnotation(annotation) } } func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "ANNOTATION") annotationView.animatesDrop = true annotationView.canShowCallout = true let addButton = UIButton.buttonWithType(UIButtonType.ContactAdd) as UIButton annotationView.rightCalloutAccessoryView = addButton return annotationView } func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) { let reminderVC = self.storyboard?.instantiateViewControllerWithIdentifier("REMINDER_VC") as AddReminderViewController reminderVC.locationManager = self.locationManager reminderVC.selectedAnnotation = view.annotation self.presentViewController(reminderVC, animated: true, completion: nil) } func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! { let renderer = MKCircleRenderer(overlay: overlay) renderer.fillColor = UIColor.purpleColor().colorWithAlphaComponent(0.20) renderer.strokeColor = UIColor.blackColor() renderer.lineWidth = 1.0 renderer.lineDashPattern = [1,3] return renderer } func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) { println("great success!") } func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!) { println("left region") } func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { switch status { case .Authorized: println("changed to authorized") //self.locationManager.startUpdatingLocation() default: println("default on authorization change") } } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { println("we got a location update!") if let location = locations.last as? CLLocation { println(location.coordinate.latitude) } } func reminderAdded(notification : NSNotification) { let userInfo = notification.userInfo! let geoRegion = userInfo["region"] as CLCircularRegion let overlay = MKCircle(centerCoordinate: geoRegion.center, radius: geoRegion.radius) self.mapView.addOverlay(overlay) } }
mit
e32219ebad277312fc7ff896d8732e1d
36.578125
131
0.668607
5.880196
false
false
false
false
almapp/uc-access-ios
uc-access/src/services/Siding.swift
1
1488
// // Siding.swift // uc-access // // Created by Patricio Lopez on 08-01-16. // Copyright © 2016 Almapp. All rights reserved. // import Foundation import Alamofire import PromiseKit public class Siding: Service { public static let ID = "SIDING" private static let URL = "https://intrawww.ing.puc.cl/siding/index.phtml" private let user: String private let password: String init(user: String, password: String) { self.user = user self.password = password super.init(name: "Siding", urls: URLs( basic: "http://www.ing.uc.cl", logged: "https://intrawww.ing.puc.cl/siding/dirdes/ingcursos/cursos/vista.phtml", failed: "https://www.ing.uc.cl" )) self.domain = "intrawww.ing.puc.cl" } override func login() -> Promise<[NSHTTPCookie]> { let params: [String: String] = [ "login": self.user, "passwd": self.password, "sw": "", "sh": "", "cd": "", ] return Request.POST(Siding.URL, parameters: params) .then { (response, _) -> [NSHTTPCookie] in self.addCookies(response) return self.cookies } } override func validate(request: NSURLRequest) -> Bool { if let headers = request.allHTTPHeaderFields { return Service.hasCookie("PHPSESSID", header: headers) } else { return false } } }
gpl-3.0
480ccc742ca63602286c99f7b592f068
26.537037
93
0.562878
3.793367
false
false
false
false
wscqs/FMDemo-
FMDemo/Classes/Module/Base/ViewControl/BaseTableViewController.swift
1
7551
// // BaseTableViewController.swift // ban // // Created by mba on 16/7/28. // Copyright © 2016年 mbalib. All rights reserved. // import UIKit import MJRefresh import ObjectMapper //import DZNEmptyDataSet fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } enum LoadAction { case loadNew // 加载最新 case loadMore // 加载更多 } class BaseTableViewController: BaseViewController { /// 默认的CellIdentifier var identifier:String = "reusableCellID" var tableView:UITableView! /// 动作标识 var action:LoadAction = .loadNew /// 当前页,如果后台是从0开始那这里就修改为0 // var page:Int = 1 var start: Int = 1 /// 每页加载多少条 // var pageSize:Int = 10 var num: Int = 10 /// 数据源集合 var dataList:[Mappable]? = [Mappable]() override func viewDidLoad() { super.viewDidLoad() //如果布局中没有tableView,则默认通过代码创建一个全屏的tableView if tableView == nil { let statusHeight = UIApplication.shared.statusBarFrame.height let navHeight = navigationController?.navigationBar.frame.height ?? 0 // 判断tabbar是否隐藏无效!!只能这样判断 var tabBarHeight:CGFloat = 0 if tabBarItem.title?.characters.count > 0 { tabBarHeight = tabBarController!.tabBar.frame.height } let y: CGFloat = (0 == navHeight) ? statusHeight : 0 tableView = RefreshBaseTableView(frame: CGRect(x: 0, y: y, width: self.view.frame.width, height: self.view.frame.height - statusHeight - navHeight - tabBarHeight), style: UITableViewStyle.plain) view.addSubview(tableView) tableView.tableHeaderView = UIView() tableView.tableFooterView = UIView() tableView.separatorStyle = UITableViewCellSeparatorStyle.none tableView.backgroundColor = UIColor.colorWithHexString(kGlobalBgColor) } tableView.delegate = self tableView.dataSource = self // tableView.emptyDataSetSource = self // tableView.emptyDataSetDelegate = self } /** 初始化参数 - parameter nibName: nib名 (nil 为默认,调试用) - parameter heightForRowAtIndexPath: 高度:( 0 为自动设置高度) - parameter canLoadRefresh: 是否可以刷新 - parameter canLoadMore: 是否可以加载 */ func initWithParams(_ nibName: String?, heightForRowAtIndexPath: CGFloat, canLoadRefresh:Bool, canLoadMore: Bool) { if let nib = nibName { tableView.register(UINib(nibName: nib, bundle: nil), forCellReuseIdentifier: identifier) }else { tableView.register(RefreshBaseTableViewCell.self, forCellReuseIdentifier: identifier) } if 0 == heightForRowAtIndexPath { tableView.estimatedRowHeight = 100 tableView.rowHeight = UITableViewAutomaticDimension } else { tableView.rowHeight = heightForRowAtIndexPath } if canLoadRefresh { //添加下拉刷新 tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(BaseTableViewController.loadRefresh)) } if canLoadMore { //添加上拉加载 // tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(BaseTableViewController.loadMore)) tableView.mj_footer = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(BaseTableViewController.loadMore)) } } /** 执行刷新 */ func loadRefresh(){ action = .loadNew start = 1 loadData() } /** 执行加载更多 */ func loadMore() { action = .loadMore start += num loadData() } /** 加载完成 */ func loadCompleted() { DispatchQueue.main.async { if self.action == .loadNew { self.tableView.mj_header.endRefreshing() } else { self.tableView.mj_footer.endRefreshing() } self.tableView.reloadData() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } // MARK: - UITableViewDelegate, UITableViewDataSource extension BaseTableViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataList?.count ?? 10 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as? RefreshBaseTableViewCell cell?.setContent(tableView, cellForRowAtIndexPath: indexPath, dataList: dataList!) return cell! } } extension BaseTableViewController { //去掉UItableview headerview黏性 func scrollViewDidScroll(_ scrollView: UIScrollView) { if (scrollView == tableView) { let sectionHeaderHeight = TABLEVIEW_TITLE_HEIGHT; if (scrollView.contentOffset.y<=sectionHeaderHeight && scrollView.contentOffset.y>=0) { scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0); } else if (scrollView.contentOffset.y >= sectionHeaderHeight) { scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0); } } } } //// MARK: - DZNEmptyDataSetSource, DZNEmptyDataSetDelegate //extension BaseTableViewController: DZNEmptyDataSetSource, DZNEmptyDataSetDelegate{ // // func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! { // return UIImage(named: "avator1") // } // // func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! { // let attributes = [ NSFontAttributeName: UIFont.boldSystemFont(ofSize: 15.0), NSForegroundColorAttributeName: UIColor.gray] // let text = "空数据,重新加载" // return NSAttributedString(string: text, attributes: attributes) // } // // func description(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! { // let attributes = [ NSFontAttributeName: UIFont.boldSystemFont(ofSize: 10.0), NSForegroundColorAttributeName: UIColor.gray] // let text = "空数据,重新加载" // return NSAttributedString(string: text, attributes: attributes) // } // // // func backgroundColorForEmptyDataSet(scrollView: UIScrollView!) -> UIColor! { // // // // } // // func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView!) -> Bool { // tableView.mj_footer = nil // return true // } //}
apache-2.0
16ec3d44301a7db335c18ebb1eaf7682
30.086207
206
0.618414
4.966942
false
false
false
false
muukii/StackScrollView
StackScrollView/StackScrollView.swift
1
13213
// StackScrollView.swift // // Copyright (c) 2016 muukii // // 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 open class StackScrollView: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { private enum LayoutKeys { static let top = "me.muukii.StackScrollView.top" static let right = "me.muukii.StackScrollView.right" static let left = "me.muukii.StackScrollView.left" static let bottom = "me.muukii.StackScrollView.bottom" static let width = "me.muukii.StackScrollView.width" static let height = "me.muukii.StackScrollView.height" } private static func defaultLayout() -> UICollectionViewFlowLayout { let layout = UICollectionViewFlowLayout() layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.sectionInset = .zero return layout } @available(*, unavailable) open override var dataSource: UICollectionViewDataSource? { didSet { } } @available(*, unavailable) open override var delegate: UICollectionViewDelegate? { didSet { } } private var direction: UICollectionView.ScrollDirection { (collectionViewLayout as! UICollectionViewFlowLayout).scrollDirection } // MARK: - Initializers public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) setup() } public convenience init(frame: CGRect) { self.init(frame: frame, collectionViewLayout: StackScrollView.defaultLayout()) setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private(set) public var views: [UIView] = [] private func identifier(_ v: UIView) -> String { return v.hashValue.description } private func setup() { backgroundColor = .white switch direction { case .vertical: alwaysBounceVertical = true case .horizontal: alwaysBounceHorizontal = true @unknown default: fatalError() } delaysContentTouches = false keyboardDismissMode = .interactive backgroundColor = .clear super.delegate = self super.dataSource = self } open override func touchesShouldCancel(in view: UIView) -> Bool { return true } open func append(view: UIView) { views.append(view) register(Cell.self, forCellWithReuseIdentifier: identifier(view)) reloadData() } open func append(views _views: [UIView]) { views += _views _views.forEach { view in register(Cell.self, forCellWithReuseIdentifier: identifier(view)) } reloadData() } @available(*, unavailable, message: "Unimplemented") func append(lazy: @escaping () -> UIView) { } open func insert(views _views: [UIView], at index: Int, animated: Bool, completion: @escaping () -> Void) { layoutIfNeeded() var _views = _views _views.removeAll(where: views.contains(_:)) views.insert(contentsOf: _views, at: index) _views.forEach { view in register(Cell.self, forCellWithReuseIdentifier: identifier(view)) } let batchUpdates: () -> Void = { self.performBatchUpdates({ self.insertItems(at: (index ..< index.advanced(by: _views.count)).map({ IndexPath(item: $0, section: 0) })) }, completion: { _ in completion() }) } if animated { UIView.animate( withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [ .beginFromCurrentState, .allowUserInteraction, .overrideInheritedCurve, .overrideInheritedOptions, .overrideInheritedDuration ], animations: batchUpdates, completion: nil) } else { UIView.performWithoutAnimation(batchUpdates) } } open func insert(views _views: [UIView], before view: UIView, animated: Bool, completion: @escaping () -> Void = {}) { guard let index = views.firstIndex(of: view) else { completion() return } insert(views: _views, at: index, animated: animated, completion: completion) } open func insert(views _views: [UIView], after view: UIView, animated: Bool, completion: @escaping () -> Void = {}) { guard let index = views.firstIndex(of: view)?.advanced(by: 1) else { completion() return } insert(views: _views, at: index, animated: animated, completion: completion) } open func remove(view: UIView, animated: Bool, completion: @escaping () -> Void = {}) { layoutIfNeeded() if let index = views.firstIndex(of: view) { views.remove(at: index) if animated { UIView.animate( withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [ .beginFromCurrentState, .allowUserInteraction, .overrideInheritedCurve, .overrideInheritedOptions, .overrideInheritedDuration ], animations: { self.performBatchUpdates({ self.deleteItems(at: [IndexPath(item: index, section: 0)]) }, completion: { _ in completion() }) }) { (finish) in } } else { UIView.performWithoutAnimation { performBatchUpdates({ self.deleteItems(at: [IndexPath(item: index, section: 0)]) }, completion: { _ in completion() }) } } } } open func remove(views: [UIView], animated: Bool, completion: @escaping () -> Void = {}) { layoutIfNeeded() var indicesForRemove: [Int] = [] for view in views { if let index = self.views.firstIndex(of: view) { indicesForRemove.append(index) } } // It seems that the layout is not updated properly unless the order is aligned. indicesForRemove.sort(by: >) for index in indicesForRemove { self.views.remove(at: index) } if animated { UIView.animate( withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [ .beginFromCurrentState, .allowUserInteraction, .overrideInheritedCurve, .overrideInheritedOptions, .overrideInheritedDuration ], animations: { self.performBatchUpdates({ self.deleteItems(at: indicesForRemove.map { IndexPath.init(item: $0, section: 0) }) }, completion: { _ in completion() }) }) } else { UIView.performWithoutAnimation { performBatchUpdates({ self.deleteItems(at: indicesForRemove.map { IndexPath.init(item: $0, section: 0) }) }, completion: { _ in completion() }) } } } /// This method might fail if the view is out of bounds. Use `func scroll(to view: UIView, at position: UICollectionView.ScrollPosition, animated: Bool)` instead @available(*, deprecated, message: "Use `scroll(to view: UIView, at position: UICollectionView.ScrollPosition, animated: Bool)` instead") open func scroll(to view: UIView, animated: Bool) { let targetRect = view.convert(view.bounds, to: self) scrollRectToVisible(targetRect, animated: true) } open func scroll(to view: UIView, at position: UICollectionView.ScrollPosition, animated: Bool) { if let index = views.firstIndex(of: view) { scrollToItem(at: IndexPath(item: index, section: 0), at: position, animated: animated) } } public func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return views.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let view = views[indexPath.item] let _identifier = identifier(view) let cell = collectionView.dequeueReusableCell(withReuseIdentifier: _identifier, for: indexPath) if view.superview == cell.contentView { return cell } precondition(cell.contentView.subviews.isEmpty) if view is ManualLayoutStackCellType { cell.contentView.addSubview(view) } else { view.translatesAutoresizingMaskIntoConstraints = false cell.contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight] cell.contentView.addSubview(view) let top = view.topAnchor.constraint(equalTo: cell.contentView.topAnchor) let right = view.rightAnchor.constraint(equalTo: cell.contentView.rightAnchor) let bottom = view.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor) let left = view.leftAnchor.constraint(equalTo: cell.contentView.leftAnchor) top.identifier = LayoutKeys.top right.identifier = LayoutKeys.right bottom.identifier = LayoutKeys.bottom left.identifier = LayoutKeys.left NSLayoutConstraint.activate([ top, right, bottom, left, ]) } return cell } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let view = views[indexPath.item] if let view = view as? ManualLayoutStackCellType { switch direction { case .vertical: return view.size(maxWidth: collectionView.bounds.width, maxHeight: nil) case .horizontal: return view.size(maxWidth: nil, maxHeight: collectionView.bounds.height) @unknown default: fatalError() } } else { switch direction { case .vertical: let width: NSLayoutConstraint = { guard let c = view.constraints.first(where: { $0.identifier == LayoutKeys.width }) else { let width = view.widthAnchor.constraint(equalToConstant: collectionView.bounds.width) width.identifier = LayoutKeys.width width.isActive = true return width } return c }() width.constant = collectionView.bounds.width let size = view.superview?.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) ?? view.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) return size case .horizontal: let heightConstraint: NSLayoutConstraint = { guard let c = view.constraints.first(where: { $0.identifier == LayoutKeys.height }) else { let heightConstraint = view.heightAnchor.constraint(equalToConstant: collectionView.bounds.height) heightConstraint.identifier = LayoutKeys.height heightConstraint.isActive = true return heightConstraint } return c }() heightConstraint.constant = collectionView.bounds.height let size = view.superview?.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) ?? view.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) return size @unknown default: fatalError() } } } public func updateLayout(animated: Bool) { if animated { UIView.animate( withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [ .beginFromCurrentState, .allowUserInteraction, .overrideInheritedCurve, .overrideInheritedOptions, .overrideInheritedDuration ], animations: { self.performBatchUpdates(nil, completion: nil) self.layoutIfNeeded() }) { (finish) in } } else { UIView.performWithoutAnimation { self.performBatchUpdates(nil, completion: nil) self.layoutIfNeeded() } } } final class Cell: UICollectionViewCell { override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { return layoutAttributes } } }
mit
8e536156b7aff63e7cdc6815cd8dcb86
29.515012
165
0.656475
4.915551
false
false
false
false
abeyuya/SwiftyHealthKit
Example/Tests/SwiftyHealthKitSpec.swift
1
8334
// https://github.com/Quick/Quick import Quick import Nimble import SwiftyHealthKit import HealthKit class SwiftyHealthKitSpec: QuickSpec { override func spec() { beforeSuite { let requireIDsForTest: [HKQuantityTypeIdentifier] = [.stepCount, .bodyMass] SwiftyHealthKit.setup(share: requireIDsForTest, read: []) guard SwiftyHealthKit.shouldRequestAuthorization == false else { fail("Need to authorize HealthKit permission before run test.") return } } describe("shouldRequestAuthorization") { beforeEach { SwiftyHealthKit.setup(share: [], read: []) } context("empty identifiers") { it("should be false") { expect(SwiftyHealthKit.shouldRequestAuthorization).to(beFalse()) } } } describe("stepCount") { beforeEach { SwiftyHealthKitSpec.delete(id: .stepCount) } context("when no data") { it("should return nil") { waitUntil { done in SwiftyHealthKit.stepCount(at: Date()) { result in switch result { case .failure(let error): fail("\(error)") case .success(let step): expect(step).to(beNil()) } done() } } } } context("when 10 steps") { it("should return 10") { let quantity = HKQuantity(unit: HKUnit.count(), doubleValue: 10) waitUntil { done in SwiftyHealthKit.writeSample(at: Date(), id: .stepCount, quantity: quantity) { result in if case .failure(let error) = result { fail("\(error)") } done() } } waitUntil { done in SwiftyHealthKit.stepCount(at: Date()) { result in switch result { case .failure(let error): fail("\(error)") case .success(let step): expect(step).to(equal(Int(10))) } done() } } } } } describe("write bodyMass") { beforeEach { SwiftyHealthKitSpec.delete(id: .bodyMass) } context("when no data") { it("should return nil") { waitUntil { done in SwiftyHealthKit.quantity(at: Date(), id: .bodyMass, option: .discreteMax) { result in switch result { case .failure(let error): fail("\(error)") case .success(let quantity): expect(quantity).to(beNil()) } done() } } } } context("when write 60kg") { it("should return 60kg") { let unit = HKUnit.gramUnit(with: .kilo) let quantity = HKQuantity(unit: unit, doubleValue: 60) waitUntil { done in SwiftyHealthKit.writeSample(at: Date(), id: .bodyMass, quantity: quantity) { result in if case .failure(let error) = result { fail("\(error)") } done() } } waitUntil { done in SwiftyHealthKit.quantity(at: Date(), id: .bodyMass, option: .discreteMax) { result in switch result { case .failure(let error): fail("\(error)") case .success(let quantity): expect(quantity?.doubleValue(for: unit)).to(equal(Double(60))) } done() } } } } } describe("overwrite bodyMass") { beforeEach { SwiftyHealthKitSpec.delete(id: .bodyMass) } context("when no data") { it("should return first record data") { let unit = HKUnit.gramUnit(with: .kilo) let quantity = HKQuantity(unit: unit, doubleValue: 60) waitUntil { done in SwiftyHealthKit.overwriteSample(at: Date(), id: .bodyMass, quantity: quantity) { result in switch result { case .failure(let error): fail("\(error)") case .success(let success): expect(success).to(beTrue()) } done() } } waitUntil { done in SwiftyHealthKit.quantity(at: Date(), id: .bodyMass, option: .discreteMax) { result in switch result { case .failure(let error): fail("\(error)") case .success(let quantity): expect(quantity?.doubleValue(for: unit)).to(equal(Double(60))) } done() } } } } context("when overwrite 1 record") { it("should return the new record") { let unit = HKUnit.gramUnit(with: .kilo) let oldQuantity = HKQuantity(unit: unit, doubleValue: 60) waitUntil { done in SwiftyHealthKit.writeSample(at: Date(), id: .bodyMass, quantity: oldQuantity) { result in if case .failure(let error) = result { fail("\(error)") } done() } } let newQuantity = HKQuantity(unit: unit, doubleValue: 55) waitUntil { done in SwiftyHealthKit.overwriteSample(at: Date(), id: .bodyMass, quantity: newQuantity) { result in switch result { case .failure(let error): fail("\(error)") case .success(let success): expect(success).to(beTrue()) } done() } } waitUntil { done in SwiftyHealthKit.quantity(at: Date(), id: .bodyMass, option: .discreteMax) { result in switch result { case .failure(let error): fail("\(error)") case .success(let quantity): expect(quantity?.doubleValue(for: unit)).to(equal(Double(55))) } done() } } } } } } } extension SwiftyHealthKitSpec { fileprivate static func delete(id: HKQuantityTypeIdentifier) { waitUntil { done in SwiftyHealthKit.deleteData(at: Date(), id: id) { result in if case .failure(let error) = result { fail("\(error)") } done() } } } }
mit
a095eabb27840a6efe412877cc0c29b4
38.49763
117
0.381449
6.381317
false
false
false
false
FutureKit/FutureKit
FutureKit/Utils/ExtensionVars.swift
1
9194
// // ExtensionVars.swift // Shimmer // // Created by Michael Gray on 11/25/14. // 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 // this class really SHOULD work, but it sometimes crashes the compiler // so we mostly use WeakAnyObject and feel angry about it class Weak<T: AnyObject> : ExpressibleByNilLiteral { weak var value : T? init (_ value: T?) { self.value = value } required init(nilLiteral: ()) { self.value = nil } } class WeakAnyObject : ExpressibleByNilLiteral { weak var value : AnyObject? init (_ value: AnyObject?) { self.value = value } required init(nilLiteral: ()) { self.value = nil } } // We use this to convert a Any value into an AnyObject // so it can be saved via objc_setAssociatedObject class Strong<T:Any> : ExpressibleByNilLiteral { var value : T? init (_ value: T?) { self.value = value } required init(nilLiteral: ()) { self.value = nil } } // So... you want to allocate stuff via UnsafeMutablePointer<T>, but don't want to have to remember // how to allocate and deallocate etc.. // let's make a utility class that allocates, initializes, and deallocates class UnSafeMutableContainer<T> { var unsafe_pointer : UnsafeMutablePointer<T> var memory : T { get { return unsafe_pointer.pointee } set(newValue) { unsafe_pointer.deinitialize(count: 1) unsafe_pointer.initialize(to: newValue) } } init() { unsafe_pointer = UnsafeMutablePointer<T>.allocate(capacity: 1) } init(_ initialValue: T) { unsafe_pointer = UnsafeMutablePointer<T>.allocate(capacity: 1) unsafe_pointer.initialize(to: initialValue) } deinit { #if swift(>=4.1) unsafe_pointer.deallocate() #else unsafe_pointer.deallocate(capacity: 1) #endif } } // Allocate a single static (module level var) ExtensionVarHandler for EACH extension variable you want to add // to a class public struct ExtensionVarHandlerFor<A : AnyObject> { fileprivate var keyValue = UnSafeMutableContainer<Int8>(0) fileprivate var key : UnsafeMutablePointer<Int8> { get { return keyValue.unsafe_pointer } } public init() { } // Two STRONG implementations - Any and AnyObject. // AnyObject will match NSObject compatible values // Any will match any class, using the Strong<T> to wrap the object in a class so it can be set correctly // This is the "default set". public func setStrongValueOn<T : Any>(_ object:A, value : T?) { // so we can't 'test' for AnyObject but we can seem to test for NSObject let policy = objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC if let v = value { objc_setAssociatedObject(object, key, Strong<T>(v), policy) } else { objc_setAssociatedObject(object, key, nil, policy) } } public func setStrongValueOn<T : AnyObject>(_ object:A, value : T?) { let policy = objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC objc_setAssociatedObject(object, key, value, policy) } // Any values cannot be captured weakly. so we don't supply a Weak setter for Any public func setWeakValueOn<T : AnyObject>(_ object:A, value : T?) { let policy = objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC if let v = value { let wp = WeakAnyObject(v) objc_setAssociatedObject(object, key, wp, policy) } else { objc_setAssociatedObject(object, key, nil, policy) } } public func setCopyValueOn<T : AnyObject>(_ object:A, value : T?) { let policy = objc_AssociationPolicy.OBJC_ASSOCIATION_COPY objc_setAssociatedObject(object, key, value, policy) } // convience - Set is always Strong by default public func setValueOn<T : Any>(_ object:A, value : T?) { self.setStrongValueOn(object, value: value) } public func setValueOn<T : AnyObject>(_ object:A, value : T?) { self.setStrongValueOn(object, value: value) } public func getValueFrom<T : Any>(_ object:A) -> T? { let v: AnyObject? = objc_getAssociatedObject(object,key) as AnyObject? switch v { case nil: return nil case let t as T: return t case let s as Strong<T>: return s.value case let w as WeakAnyObject: return w.value as? T default: assertionFailure("found unknown value \(String(describing: v)) in getExtensionVar") return nil } } public func getValueFrom<T : Any>(_ object:A, defaultvalue : T) -> T { let value: T? = getValueFrom(object) if let v = value { return v } else { self.setStrongValueOn(object,value: defaultvalue) return defaultvalue } } public func getValueFrom<T : Any>(_ object:A, defaultvalueblock : () -> T) -> T { let value: T? = getValueFrom(object) if let v = value { return v } else { let defaultvalue = defaultvalueblock() self.setStrongValueOn(object,value: defaultvalue) return defaultvalue } } public func clear(_ object:A) { let policy = objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC objc_setAssociatedObject(object, key, nil, policy) } } public typealias ExtensionVarHandler = ExtensionVarHandlerFor<AnyObject> /// EXAMPLE FOLLOWS : class __ExampleClass : NSObject { var regularVar : Int = 99 } private var exampleIntOptionalHandler = ExtensionVarHandler() private var exampleIntHandler = ExtensionVarHandler() private var exampleDelegateHandler = ExtensionVarHandler() private var exampleAnyObjectHandler = ExtensionVarHandler() private var exampleDictionaryHandler = ExtensionVarHandler() extension __ExampleClass { var intOptional : Int? { get { return exampleIntOptionalHandler.getValueFrom(self) } set(newValue) { exampleIntOptionalHandler.setValueOn(self, value: newValue) } } var intWithDefaultValue : Int { get { return exampleIntHandler.getValueFrom(self,defaultvalue: 55) } set(newValue) { exampleIntHandler.setValueOn(self, value: newValue) } } var weakDelegatePtr : NSObject? { get { return exampleDelegateHandler.getValueFrom(self) } set(newDelegate) { // note the use of WEAK! This will be a safe weak (zeroing weak ptr). Not an unsafe assign! exampleDelegateHandler.setWeakValueOn(self, value: newDelegate) } } var anyObjectOptional : AnyObject? { get { return exampleAnyObjectHandler.getValueFrom(self) } set(newValue) { exampleAnyObjectHandler.setValueOn(self, value: newValue) } } var dictionaryWithDefaultValues : [String : Int] { get { return exampleDictionaryHandler.getValueFrom(self,defaultvalue: ["Default" : 99, "Values" : 1]) } set(newValue) { exampleDictionaryHandler.setValueOn(self, value: newValue) } } } func _someExampleStuffs() { let e = __ExampleClass() e.regularVar = 22 // this isn't an extension var, but defined in the original class assert(e.intWithDefaultValue == 55, "default values should work!") e.intOptional = 5 e.intOptional = nil let value = e.dictionaryWithDefaultValues["Default"]! assert(value == 99, "default values should work!") e.weakDelegatePtr = e // won't cause a RETAIN LOOP! cause it's a weak ptr e.anyObjectOptional = e // this will cause a RETAIN LOOP! (bad idea, but legal) e.anyObjectOptional = nil // let's not leave that retain loop alive }
mit
6c1e10b7ef96f15fdc790acc42c90bab
30.486301
111
0.635523
4.37185
false
false
false
false
sschiau/swift
test/expr/closure/anonymous.swift
2
2153
// RUN: %target-typecheck-verify-swift func takeIntToInt(_ f: (Int) -> Int) { } func takeIntIntToInt(_ f: (Int, Int) -> Int) { } // Simple closures with anonymous arguments func simple() { takeIntToInt({return $0 + 1}) takeIntIntToInt({return $0 + $1 + 1}) } func takesIntArray(_: [Int]) { } func takesVariadicInt(_: (Int...) -> ()) { } func takesVariadicIntInt(_: (Int, Int...) -> ()) { } func takesVariadicGeneric<T>(_ f: (T...) -> ()) { } func variadic() { // These work // FIXME: Not anymore: rdar://41416758 takesVariadicInt({let _ = $0}) // expected-error@-1 {{cannot convert value of type '(_) -> ()' to expected argument type '(Int...) -> ()'}} takesVariadicInt({let _: [Int] = $0}) // expected-error@-1 {{cannot convert value of type '(_) -> ()' to expected argument type '(Int...) -> ()'}} let _: (Int...) -> () = {let _: [Int] = $0} // expected-error@-1 {{cannot convert value of type '(_) -> ()' to specified type '(Int...) -> ()'}} // FIXME: Make the rest work takesVariadicInt({takesIntArray($0)}) // expected-error@-1 {{cannot convert value of type '([Int]) -> ()' to expected argument type '(Int...) -> ()'}} let _: (Int...) -> () = {takesIntArray($0)} // expected-error@-1 {{cannot convert value of type '([Int]) -> ()' to specified type '(Int...) -> ()'}} // TODO(diagnostics): This requires special handling - variadic vs. array takesVariadicGeneric({takesIntArray($0)}) // expected-error@-1 {{cannot convert value of type 'Array<Element>' to expected argument type '[Int]'}} // expected-note@-2 {{arguments to generic parameter 'Element' ('Element' and 'Int') are expected to be equal}} takesVariadicGeneric({let _: [Int] = $0}) // expected-error@-1 {{cannot convert value of type '(_) -> ()' to expected argument type '(_...) -> ()'}} takesVariadicIntInt({_ = $0; takesIntArray($1)}) // expected-error@-1 {{cannot convert value of type '(_, _) -> ()' to expected argument type '(Int, Int...) -> ()'}} takesVariadicIntInt({_ = $0; let _: [Int] = $1}) // expected-error@-1 {{cannot convert value of type '(_, _) -> ()' to expected argument type '(Int, Int...) -> ()'}} }
apache-2.0
1b1e9034c3fff7b26058a0780a1ffc14
42.06
118
0.593126
3.824156
false
false
false
false
practicalswift/swift
stdlib/public/core/SmallString.swift
2
11500
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // The code units in _SmallString are always stored in memory in the same order // that they would be stored in an array. This means that on big-endian // platforms the order of the bytes in storage is reversed compared to // _StringObject whereas on little-endian platforms the order is the same. // // Memory layout: // // |0 1 2 3 4 5 6 7 8 9 A B C D E F| ← hexadecimal offset in bytes // | _storage.0 | _storage.1 | ← raw bits // | code units | | ← encoded layout // ↑ ↑ // first (leftmost) code unit discriminator (incl. count) // @_fixed_layout @usableFromInline internal struct _SmallString { @usableFromInline internal typealias RawBitPattern = (UInt64, UInt64) // Small strings are values; store them raw @usableFromInline internal var _storage: RawBitPattern @inlinable internal var rawBits: RawBitPattern { @inline(__always) get { return _storage } } @inlinable internal var leadingRawBits: UInt64 { @inline(__always) get { return _storage.0 } @inline(__always) set { _storage.0 = newValue } } @inlinable internal var trailingRawBits: UInt64 { @inline(__always) get { return _storage.1 } @inline(__always) set { _storage.1 = newValue } } @inlinable @inline(__always) internal init(rawUnchecked bits: RawBitPattern) { self._storage = bits } @inlinable @inline(__always) internal init(raw bits: RawBitPattern) { self.init(rawUnchecked: bits) _invariantCheck() } @inlinable @inline(__always) internal init(_ object: _StringObject) { _internalInvariant(object.isSmall) // On big-endian platforms the byte order is the reverse of _StringObject. let leading = object.rawBits.0.littleEndian let trailing = object.rawBits.1.littleEndian self.init(raw: (leading, trailing)) } @inlinable @inline(__always) internal init() { self.init(_StringObject(empty:())) } } extension _SmallString { @inlinable internal static var capacity: Int { @inline(__always) get { #if arch(i386) || arch(arm) return 10 #else return 15 #endif } } // Get an integer equivalent to the _StringObject.discriminatedObjectRawBits // computed property. @inlinable @inline(__always) internal var rawDiscriminatedObject: UInt64 { // Reverse the bytes on big-endian systems. return _storage.1.littleEndian } @inlinable internal var capacity: Int { @inline(__always) get { return _SmallString.capacity } } @inlinable internal var count: Int { @inline(__always) get { return _StringObject.getSmallCount(fromRaw: rawDiscriminatedObject) } } @inlinable internal var unusedCapacity: Int { @inline(__always) get { return capacity &- count } } @inlinable internal var isASCII: Bool { @inline(__always) get { return _StringObject.getSmallIsASCII(fromRaw: rawDiscriminatedObject) } } // Give raw, nul-terminated code units. This is only for limited internal // usage: it always clears the discriminator and count (in case it's full) @inlinable @inline(__always) internal var zeroTerminatedRawCodeUnits: RawBitPattern { let smallStringCodeUnitMask = ~UInt64(0xFF).bigEndian // zero last byte return (self._storage.0, self._storage.1 & smallStringCodeUnitMask) } internal func computeIsASCII() -> Bool { let asciiMask: UInt64 = 0x8080_8080_8080_8080 let raw = zeroTerminatedRawCodeUnits return (raw.0 | raw.1) & asciiMask == 0 } } // Internal invariants extension _SmallString { #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { _internalInvariant(count <= _SmallString.capacity) _internalInvariant(isASCII == computeIsASCII()) } #endif // INTERNAL_CHECKS_ENABLED internal func _dump() { #if INTERNAL_CHECKS_ENABLED print(""" smallUTF8: count: \(self.count), codeUnits: \( self.map { String($0, radix: 16) }.joined() ) """) #endif // INTERNAL_CHECKS_ENABLED } } // Provide a RAC interface extension _SmallString: RandomAccessCollection, MutableCollection { @usableFromInline internal typealias Index = Int @usableFromInline internal typealias Element = UInt8 @usableFromInline internal typealias SubSequence = _SmallString @inlinable internal var startIndex: Int { @inline(__always) get { return 0 } } @inlinable internal var endIndex: Int { @inline(__always) get { return count } } @inlinable internal subscript(_ idx: Int) -> UInt8 { @inline(__always) get { _internalInvariant(idx >= 0 && idx <= 15) if idx < 8 { return leadingRawBits._uncheckedGetByte(at: idx) } else { return trailingRawBits._uncheckedGetByte(at: idx &- 8) } } @inline(__always) set { _internalInvariant(idx >= 0 && idx <= 15) if idx < 8 { leadingRawBits._uncheckedSetByte(at: idx, to: newValue) } else { trailingRawBits._uncheckedSetByte(at: idx &- 8, to: newValue) } } } @inlinable // FIXME(inline-always) was usableFromInline // testable internal subscript(_ bounds: Range<Index>) -> SubSequence { @inline(__always) get { // TODO(String performance): In-vector-register operation return self.withUTF8 { utf8 in let rebased = UnsafeBufferPointer(rebasing: utf8[bounds]) return _SmallString(rebased)._unsafelyUnwrappedUnchecked } } } } extension _SmallString { @inlinable @inline(__always) internal func withUTF8<Result>( _ f: (UnsafeBufferPointer<UInt8>) throws -> Result ) rethrows -> Result { var raw = self.zeroTerminatedRawCodeUnits return try Swift.withUnsafeBytes(of: &raw) { rawBufPtr in let ptr = rawBufPtr.baseAddress._unsafelyUnwrappedUnchecked .assumingMemoryBound(to: UInt8.self) return try f(UnsafeBufferPointer(start: ptr, count: self.count)) } } // Overwrite stored code units, including uninitialized. `f` should return the // new count. @inline(__always) internal mutating func withMutableCapacity( _ f: (UnsafeMutableBufferPointer<UInt8>) throws -> Int ) rethrows { let len = try withUnsafeMutableBytes(of: &self._storage) { (rawBufPtr: UnsafeMutableRawBufferPointer) -> Int in let ptr = rawBufPtr.baseAddress._unsafelyUnwrappedUnchecked .assumingMemoryBound(to: UInt8.self) return try f(UnsafeMutableBufferPointer( start: ptr, count: _SmallString.capacity)) } _internalInvariant(len <= _SmallString.capacity) let (leading, trailing) = self.zeroTerminatedRawCodeUnits self = _SmallString(leading: leading, trailing: trailing, count: len) } } // Creation extension _SmallString { @inlinable @inline(__always) internal init(leading: UInt64, trailing: UInt64, count: Int) { _internalInvariant(count <= _SmallString.capacity) let isASCII = (leading | trailing) & 0x8080_8080_8080_8080 == 0 let discriminator = _StringObject.Nibbles .small(withCount: count, isASCII: isASCII) .littleEndian // reversed byte order on big-endian platforms _internalInvariant(trailing & discriminator == 0) self.init(raw: (leading, trailing | discriminator)) _internalInvariant(self.count == count) } // Direct from UTF-8 @inlinable @inline(__always) internal init?(_ input: UnsafeBufferPointer<UInt8>) { if input.isEmpty { self.init() return } let count = input.count guard count <= _SmallString.capacity else { return nil } // TODO(SIMD): The below can be replaced with just be a masked unaligned // vector load let ptr = input.baseAddress._unsafelyUnwrappedUnchecked let leading = _bytesToUInt64(ptr, Swift.min(input.count, 8)) let trailing = count > 8 ? _bytesToUInt64(ptr + 8, count &- 8) : 0 self.init(leading: leading, trailing: trailing, count: count) } @usableFromInline // @testable internal init?(_ base: _SmallString, appending other: _SmallString) { let totalCount = base.count + other.count guard totalCount <= _SmallString.capacity else { return nil } // TODO(SIMD): The below can be replaced with just be a couple vector ops var result = base var writeIdx = base.count for readIdx in 0..<other.count { result[writeIdx] = other[readIdx] writeIdx &+= 1 } _internalInvariant(writeIdx == totalCount) let (leading, trailing) = result.zeroTerminatedRawCodeUnits self.init(leading: leading, trailing: trailing, count: totalCount) } } #if _runtime(_ObjC) && !(arch(i386) || arch(arm)) // Cocoa interop extension _SmallString { // Resiliently create from a tagged cocoa string // @_effects(readonly) // @opaque @usableFromInline // testable internal init(taggedCocoa cocoa: AnyObject) { self.init() self.withMutableCapacity { let len = _bridgeTagged(cocoa, intoUTF8: $0) _internalInvariant(len != nil && len! < _SmallString.capacity, "Internal invariant violated: large tagged NSStrings") return len._unsafelyUnwrappedUnchecked } self._invariantCheck() } } #endif extension UInt64 { // Fetches the `i`th byte in memory order. On little-endian systems the byte // at i=0 is the least significant byte (LSB) while on big-endian systems the // byte at i=7 is the LSB. @inlinable @inline(__always) internal func _uncheckedGetByte(at i: Int) -> UInt8 { _internalInvariant(i >= 0 && i < MemoryLayout<UInt64>.stride) #if _endian(big) let shift = (7 - UInt64(truncatingIfNeeded: i)) &* 8 #else let shift = UInt64(truncatingIfNeeded: i) &* 8 #endif return UInt8(truncatingIfNeeded: (self &>> shift)) } // Sets the `i`th byte in memory order. On little-endian systems the byte // at i=0 is the least significant byte (LSB) while on big-endian systems the // byte at i=7 is the LSB. @inlinable @inline(__always) internal mutating func _uncheckedSetByte(at i: Int, to value: UInt8) { _internalInvariant(i >= 0 && i < MemoryLayout<UInt64>.stride) #if _endian(big) let shift = (7 - UInt64(truncatingIfNeeded: i)) &* 8 #else let shift = UInt64(truncatingIfNeeded: i) &* 8 #endif let valueMask: UInt64 = 0xFF &<< shift self = (self & ~valueMask) | (UInt64(truncatingIfNeeded: value) &<< shift) } } @inlinable @inline(__always) internal func _bytesToUInt64( _ input: UnsafePointer<UInt8>, _ c: Int ) -> UInt64 { // FIXME: This should be unified with _loadPartialUnalignedUInt64LE. // Unfortunately that causes regressions in literal concatenation tests. (Some // owned to guaranteed specializations don't get inlined.) var r: UInt64 = 0 var shift: Int = 0 for idx in 0..<c { r = r | (UInt64(input[idx]) &<< shift) shift = shift &+ 8 } // Convert from little-endian to host byte order. return r.littleEndian }
apache-2.0
ed77438ddf9aef7a9113871b0abea642
30.222826
80
0.667972
4.158523
false
false
false
false
SheffieldKevin/FirstMeeting
SheffieldSwift.playground/Contents.swift
1
12079
//: ![Sheffield Swift](Swift.png) //: ## Written for @SheffieldSwift 19 May 2015 //: [https://github.com/SheffieldKevin/FirstMeeting](https://github.com/SheffieldKevin/FirstMeeting) //: ### Swift is a powerful new language with some interesting features. //: I'll be discussing a few of those today //: * Swift is strictly typed with type inference //: * Mutability versus immutability //: * Difference between Class, Struct and enum instances and why that is important //: * Optionals //: * Enums //: ### Swift is strictly typed and does type inference var str = "Hello, playground" //: str is declared as a variable which means its value can be changed. str = "@SheffieldSwift says hello back" //: Variables can't have their type changed from the type determined when they were declared. // str = 3 //: #### So what is going on here? //: Swift is stricly typed so the compiler gives every variable or constant a specific type, the type cannot be changed after the variable is declared. This is different to ruby where a variable can be reassigned to an object of any type. If a type isn't specified but the type can be inferred from the assigned value when the variable or constant is declared then the compiler gives the variable or constant a type. If the type cannot be inferred the compiler will emit an error message. //: So the type of str is determined by the compiler at the point of decleration at compile time and is determined to be a string. I use the dynamicType property of a class or struct instance to inform us what the type is. print("str type is: \(str.dynamicType)") //: #### We can specify the type in the decleration let newString:String = "Hello lovely people" //: #### The types of str and newString are the same print("newString type is: \(newString.dynamicType)") //: #### Type inference works for any type the compiler can reasonably determine at compile time. let myNum = 2 print("\(myNum.dynamicType)") //: We can modify str let c = str.removeAtIndex(str.startIndex) str.append(c) //: but can we modify newString // newString.append(c) print(newString) //: So newString is a constant. newString is also a struct instance, not an object instance and I'll explain about why that is important later on. //: A variable or a constant does not have to have an initial value as long as the property is assigned a value before it is accessed. In this case though the decleration requires the type to be specified. The compiler will not attempt to look ahead to infer the type from later information. let theString:String if str == "Hello, playground" { theString = "Hello, playground" } else { theString = "Help me" } print(theString) //: ##### I would recommend that you prefer let over var. //: ### What is the difference between instances of Structs and Classes? class Person { var firstName = "" let lastName:String init(firstName:String, lastName:String = "Serious") { self.firstName = firstName self.lastName = lastName } func printName() { print("\(firstName) \(lastName)") } } let someone = Person(firstName: "Shayleen") //: So what happens when we try to change the person's name: let anotherPerson = someone someone.firstName = "Katerina" // someone.lastName = "SemiSerious" someone.printName() anotherPerson.printName() //: ##### Hey! someone has been declared as a constant but we can change their name. struct City { var name = "" let country:String var population:Int init(cityName:String, country:String = "UK", population:Int) { name = cityName self.country = country self.population = population } func printCity() { print("City: \(name) in \(country) has population: \(population)") } } let myCity = City(cityName:"Sheffield", population: 525000) // var myCity = City(cityName:"Sheffield", population: 525000) // myCity.name = "Chesterfield" myCity.printCity() let anotherValueOfSheffield = myCity //: So what is going on here. The difference is how Swift treats Struct or Class instances. Instances of structs are passed by value, whereas instances of classes are passed by reference. //: ##### What do we mean by this: //: When you assign a struct instance to another property the instance is copied. If the property is declared with a let then the value itself is constant. Whereas if you assign a class instance to a let property then what you are assigning is the reference to the class instance, not the class instance itself. What is constant is the reference to the instance, that reference can't refer to a different class instance. When declaring a new type deciding on whether that type should be a struct or class type is important. [Copy a class instance](http://t.co/KN34IMcqxj) //: Enum types behave like struct types. Instances of enum types are passed by value. //: You can't have sub structs or sub classes of a struct. // class BigCity: City { } //: The word 'instance' is a more general term used to refer to objects of classes or structs. What in 'C' would be considered to be a primitive type like integer or float in Swift has as their equivalent Int/Float which are types that are Structs and that you can call functions on. In this sense Swift is similar to Ruby. Not the same but similar. //: ### Optionals - An important feature of Swift but initially painful //: If a property can't be assigned when declared then its value will be either undefined or nil. Some APIs return an Optional value, in Objective-C this implies that the API could return nil. Swift formalizes how what are nil values in Objective-C are treated. //: An optional value either contains a value or contains nil. Optional values work exactly the same if the optional is a struct instance or a class instance. To indicate that a value might be an optional write a question mark after the type to mark the value as optional. //: You can create an optional value with an initial value, nil or Optional.None. The compiler will treat the property differently if the property has not been assigned. var optionalString:String? = "a string" let optionalString2:String? print(optionalString2.dynamicType) //: Optional.None is different to undefined. If you have not set a property prior to it being accessed it is not by default set to Optional.None. Instead the compiler reports an error. // print("\(optionalString2)") let optionalString3:String? = nil print(optionalString3) print(optionalString3.dynamicType) let optionalString4:String? = Optional.None print(optionalString3) print(optionalString3.dynamicType) //: You can unwrap the optional to access its value using ```if let``` like so: print(optionalString) if let aString = optionalString { print(aString) } //: In Swift 2 you can also unwrap the optional using guard let. //: You can't use guard at the top level of a playground. func printOptional(optionalString optionalString: String?) -> Void { guard let unwrappedString = optionalString else { print("optionalString is Optional.None \(optionalString)") return } print(unwrappedString) } printOptional(optionalString: optionalString) // printOptional(optionalString: .None) //: After an optional value has been assigned a value you can set it back to nil. optionalString = nil if let aString = optionalString { print(aString) } else { print("optionalString is nil") } //: And then back again. optionalString = "A new string" //: Optional is an enum, the enum value .Some has an associated value whilst the enum value .None does not. The value associated with .Some is the value returned from the optional value when the optional is unwrapped. Assigning an optional property with nil or .None does the same thing. optionalString = Optional.None //: You can abbreviate that to: optionalString = .None //: You can also assign using the Optional .Some value. optionalString = Optional.Some("An even newer string") //: You wouldn't normally do this but it demonstrates what an optional really is. struct WellHello { let name:String? let greeting:String init(message:String = "Well Hello!", name:String? = .None) { greeting = message self.name = name } func printMessage() { let theName = name ?? "Dolly" print("\(greeting) \(theName)") } } let hello1:WellHello? = WellHello() //: You can unwrap an optional using the ? operator. // let hello2:WellHello? = .None // hello2?.printMessage() let theGreeting = hello1?.greeting hello1?.printMessage() //: #### Did you notice in the printMessage function the use of ?? //: This is called the nil coalescing operator. Effectively what it does is it checks to see if the value is nil, if it is nil it returns the value after the operator, otherwise it returns the unwrapped optional value. //: If you know that an optional value will be valid at a certain point then you can use the ! operator. This operator does a forced unwrap of the optional value and if the value is nil/Optional.None then it will cause a crash. var hello2:WellHello? = Optional.None // hello2!.printMessage() print("Do we get here? - we shouldn't if the above line is uncommented as it causes a crash") hello2 = WellHello(name: "Louis", message: "It is nice to see you back here where you belong") //: Even though the following force unwraps the name property because hello2 is optionally unwrapped theName remains an optional. let theName = hello2?.name! print(theName) print("theName type: \(theName.dynamicType)") //: You can force unwrap both. let theName2 = hello2!.name! print(theName2) print("theName2 type: \(theName2.dynamicType)") //: You can add more than one optional unwrap in each if statement. See the printMessageFrom function. class GreetingsFrom { let country:String let greetingMessage:WellHello? init(country:String = "UK", greetingMessage:WellHello? = .None) { self.country = country self.greetingMessage = greetingMessage } func printMessageFrom() { if let theMessage = self.greetingMessage, let theName = theMessage.name { print("\(theName) from \(country) says: \(theMessage.greeting)") } else if let theMessage = self.greetingMessage { print("\(country) says: \(theMessage.greeting)") } else { print("Greetings from \(country)") } } } let greetingsFromUK:GreetingsFrom? = GreetingsFrom(greetingMessage: hello2) let greetingsFromUKName = greetingsFromUK?.greetingMessage?.name //: Because either of ? results can be operating on an optional without a value the result is also an optional but an optional of the type of name: String. print("Type of greetingsFromUKName: \(greetingsFromUKName.dynamicType)") greetingsFromUK!.printMessageFrom() //: ### Swift error handling and the ErrorType //: I am afraid is beyond the scope of this talk. I would recommend asking Luke Stringer @lukestringer90 to come give a talk one day on Swift 2 error handling. //: [Swift 2 error handling by @lukestringer90](https://github.com/SheffieldSwift/Materials/tree/master/21.07.15) //: If there is time we can touch on guard and defer. //: [@sketchyTech Deferring & delegating in Swift 2](http://sketchytech.blogspot.co.uk/2015/07/deferring-and-delegating-in-swift-2.html) //: ## What next //: There are a few more fundamental Swift topics which I'd like to cover but this is enough for today. //: * Functions as first class objects in Swift //: * Enums and associated values //: * Pattern matching on the enum and associated values (switch statements) //: * The Result type //: * The Swift 2 guard and defer statements. //: * The Swift 2 error handling. //: ## This playground was made for [@SheffieldSwift](https://twitter.com/SheffieldSwift) //: By [Kevin Meaney: @CocoaKevin](https://twitter.com/CocoaKevin) //: //: @CocoaKevin Creator of MovingImages at [Zukini](http://zukini.eu). A pre-release production. //: ![Sheffield Swift](Swift.png)
mit
c063dc5e8c5ca9d6092256efd91e3c01
38.864686
571
0.728703
4.136644
false
false
false
false
MadeByHecho/Timber
Timber/FileLogger.swift
1
8951
// // FileLogger.swift // Timber // // Created by Scott Petit on 9/7/14. // Copyright (c) 2014 Scott Petit. All rights reserved. // import Foundation public struct FileLogger: LoggerType { public init() { FileManager.purgeOldFiles() FileManager.purgeOldestFilesGreaterThanCount(5) print("Timber - Saving logs to \(FileManager.currentLogFilePath())") } //MARK: Logger public var messageFormatter: MessageFormatterType = MessageFormatter() public func logMessage(message: LogMessage) { let currentData = FileManager.currentLogFileData() let mutableData = NSMutableData(data: currentData) var messageToLog = messageFormatter.formatLogMessage(message) messageToLog += "\n" if let dataToAppend = messageToLog.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) { mutableData.appendData(dataToAppend) } if let filePath = FileManager.currentLogFilePath() { mutableData.writeToFile(filePath, atomically: false) } } } struct FileManager { static let userDefaultsKey = "com.Timber.currentLogFile" static let maximumLogFileSize = 1024 * 1024 // 1 mb static let maximumFileExsitenceInterval: NSTimeInterval = 60 * 60 * 24 * 180 // 180 days static func currentLogFilePath() -> String? { if let path: AnyObject = NSUserDefaults.standardUserDefaults().objectForKey(userDefaultsKey) { return path as? String } else { return createNewLogFilePath() } } static func shouldCreateNewLogFileForData(data: NSData) -> Bool { return data.length > maximumLogFileSize } static func createNewLogFilePath() -> String? { if let logsDirectory = defaultLogsDirectory() { let newLogFilePath = logsDirectory.stringByAppendingPathComponent(newLogFileName()) NSUserDefaults.standardUserDefaults().setObject(newLogFilePath, forKey: userDefaultsKey) NSUserDefaults.standardUserDefaults().synchronize() return newLogFilePath } return nil } static func newLogFileName() -> String { let appName = applicationName() let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy'-'MM'-'dd'_'HH'-'mm'" dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) let formattedDate = dateFormatter.stringFromDate(NSDate()) let newLogFileName = "\(appName)_\(formattedDate).log" return newLogFileName } static func applicationName() -> String { let processName = NSProcessInfo.processInfo().processName if processName.characters.count > 0 { return processName } else { return "<UnnamedApp>" } } static func defaultLogsDirectory() -> String? { // Update how we get file URLs per Apple Technical Note https://developer.apple.com/library/ios/technotes/tn2406/_index.html let cachesDirectoryPathURL = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask).last as NSURL! if cachesDirectoryPathURL.fileURL { if let cachesDirectoryPath = cachesDirectoryPathURL.path { let logsDirectory = cachesDirectoryPath.stringByAppendingPathComponent("Timber") if !NSFileManager.defaultManager().fileExistsAtPath(logsDirectory) { do { try NSFileManager.defaultManager().createDirectoryAtPath(logsDirectory, withIntermediateDirectories: true, attributes: nil) } catch _ { } } return logsDirectory } } return nil } static func currentLogFileData() -> NSData { if let filePath = currentLogFilePath() { if let data = NSData(contentsOfFile: filePath) { if shouldCreateNewLogFileForData(data) { createNewLogFilePath() } return data } } return NSData() } static func purgeOldFiles() { if let logsDirectory = defaultLogsDirectory() { TrashMan.takeOutFilesInDirectory(logsDirectory, withExtension: "log", notModifiedSince: NSDate(timeIntervalSinceNow: -maximumFileExsitenceInterval)) } } static func purgeOldestFilesGreaterThanCount(count: Int) { if let logsDirectory = defaultLogsDirectory() { TrashMan.takeOutOldestFilesInDirectory(logsDirectory, greaterThanCount: count) } } } struct TrashMan { static func takeOutFilesInDirectory(directoryPath: String, notModifiedSince minimumModifiedDate: NSDate) { takeOutFilesInDirectory(directoryPath, withExtension: nil, notModifiedSince: minimumModifiedDate) } static func takeOutFilesInDirectory(directoryPath: String, withExtension fileExtension: String?, notModifiedSince minimumModifiedDate: NSDate) { let fileURL = NSURL(fileURLWithPath: directoryPath, isDirectory: true) let fileManager = NSFileManager.defaultManager() let contents: [AnyObject]? do { contents = try fileManager.contentsOfDirectoryAtURL(fileURL, includingPropertiesForKeys: [NSURLAttributeModificationDateKey], options: .SkipsHiddenFiles) } catch _ { contents = nil } if let files = contents as? [NSURL] { for file in files { var fileDate: AnyObject? let haveDate: Bool do { try file.getResourceValue(&fileDate, forKey: NSURLAttributeModificationDateKey) haveDate = true } catch _ { haveDate = false } if !haveDate { continue } if fileDate?.timeIntervalSince1970 >= minimumModifiedDate.timeIntervalSince1970 { continue } if fileExtension != nil { if file.pathExtension != fileExtension! { continue } } do { try fileManager.removeItemAtURL(file) } catch _ { } } } } static func takeOutOldestFilesInDirectory(directoryPath: String, greaterThanCount count: Int) { let directoryURL = NSURL(fileURLWithPath: directoryPath, isDirectory: true) let contents: [AnyObject]? do { contents = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(directoryURL, includingPropertiesForKeys: [NSURLCreationDateKey], options: .SkipsHiddenFiles) } catch _ { contents = nil } if let files = contents as? [NSURL] { if count >= files.count { return } let sortedFiles = files.sort({ (firstFile: NSURL, secondFile: NSURL) -> Bool in var firstFileObject: AnyObject? let haveFirstDate: Bool do { try firstFile.getResourceValue(&firstFileObject, forKey: NSURLCreationDateKey) haveFirstDate = true } catch { haveFirstDate = false } if !haveFirstDate { return false } var secondFileObject: AnyObject? let haveSecondDate: Bool do { try secondFile.getResourceValue(&secondFileObject, forKey: NSURLCreationDateKey) haveSecondDate = true } catch { haveSecondDate = false } if !haveSecondDate { return true } let firstFileDate = firstFileObject as! NSDate let secondFileDate = secondFileObject as! NSDate let comparisonResult = firstFileDate.compare(secondFileDate) return comparisonResult == NSComparisonResult.OrderedDescending }) for (index, fileURL) in sortedFiles.enumerate() { if index >= count { do { try NSFileManager.defaultManager().removeItemAtURL(fileURL) } catch { } } } } } }
mit
c18e4ef96b356d38e38bc81f696b8b67
34.804
176
0.567311
6.023553
false
false
false
false
ExTEnS10N/CommonViewController
TEClassExtension.swift
1
5369
// // TEClassExtension.swift // // Created by macsjh on 16/3/7. // Copyright © 2016年 TurboExtension. All rights reserved. // import UIKit extension NSURL{ convenience init?(unSafeString:String){ guard unSafeString.characters.count > 0 else {return nil} var urlString:String? = "" if(unSafeString.rangeOfString(":") == nil){ urlString = "https://" + unSafeString } else {urlString = unSafeString} /* URLQueryAllowedCharacterSet() 相等 URLFragmentAllowedCharacterSet() URLQueryAllowedCharacterSet() 相交或相离 URLHostAllowedCharacterSet() URLQueryAllowedCharacterSet() 包含 URLPathAllowedCharacterSet() URLQueryAllowedCharacterSet() 包含 URLUserAllowedCharacterSet() URLQueryAllowedCharacterSet() 包含 URLPasswordAllowedCharacterSet() */ let allowSet = NSMutableCharacterSet() allowSet.addCharactersInString("#") allowSet.formUnionWithCharacterSet(NSCharacterSet.URLQueryAllowedCharacterSet()) allowSet.formUnionWithCharacterSet(NSCharacterSet.URLHostAllowedCharacterSet()) urlString = urlString?.stringByRemovingPercentEncoding urlString = urlString!.stringByAddingPercentEncodingWithAllowedCharacters(allowSet) guard urlString != nil else {return nil} self.init(string: urlString!) } static func URLIsEqual(url1: String, url2: String) -> Bool{ guard let u1 = NSURL(unSafeString: url1) else{return false} guard let u2 = NSURL(unSafeString: url2) else{return false} if u1 == u2 {return true} else if(u1.pathExtension?.characters.count > 0 || u2.pathExtension?.characters.count > 0){ return false } else { return u1.URLByAppendingPathComponent("") == u2.URLByAppendingPathComponent("") } } func domainName() -> String?{ guard let host = self.host else{return nil} let domains = host.componentsSeparatedByString(".") switch domains.count{ case 0: return nil case 1, 2: return domains[0] default: return domains[1] } } /// remove all path extension and standardlize url.(read-only) var URLWithoutPathExtension:NSURL?{ get { var tempURL:NSURL? = self while tempURL?.lastPathComponent?.characters.count > 0{ tempURL = tempURL?.URLByDeletingLastPathComponent?.standardizedURL } return tempURL } } } extension String { func subString(fromIndex:Int, length:Int) -> String { let temp = NSString(string: self) let tempFrom = NSString(string: temp.substringFromIndex(fromIndex)) return tempFrom.substringToIndex(length) } ///返回给定字符串在本串中的位置,不存在返回-1 func indexOf(string: String) -> Int { let range = NSString(string: self).rangeOfString(string) if(range.length < 1) { return -1 } return range.location } var intValue:Int? { get{ return NSNumberFormatter().numberFromString(self)?.integerValue } } ///将表示十六进制数据的字符串转换为对应的二进制数据 /// ///- Parameter string:形如“6E7C2F”的字符串 ///- Returns: 对应的二进制数据 public func hexStringToData() ->NSData? { let hexString:NSString = self.uppercaseString.stringByReplacingOccurrencesOfString(" ", withString:"") if (hexString.length % 2 != 0) { return nil } var tempbyt:[UInt8] = [0] let bytes = NSMutableData(capacity: hexString.length / 2) for(var i = 0; i < hexString.length; ++i) { let hex_char1:unichar = hexString.characterAtIndex(i) var int_ch1:Int if(hex_char1 >= 48 && hex_char1 <= 57) { int_ch1 = (Int(hex_char1) - 48) * 16 } else if(hex_char1 >= 65 && hex_char1 <= 70) { int_ch1 = (Int(hex_char1) - 55) * 16 } else { return nil; } i++; let hex_char2:unichar = hexString.characterAtIndex(i) var int_ch2:Int if(hex_char2 >= 48 && hex_char2 <= 57) { int_ch2 = (Int(hex_char2) - 48) } else if(hex_char2 >= 65 && hex_char2 <= 70) { int_ch2 = Int(hex_char2) - 55; } else { return nil; } tempbyt[0] = UInt8(int_ch1 + int_ch2) bytes!.appendBytes(tempbyt, length:1) } return bytes; } } extension UIColor{ /// Convert hexString to UIColor /// /// support: /// - "#012345" & "012345" /// - "#AABBCCEE" & "AABBCCEE" /// /// - parameter hexString: 16进制字符串 /// /// - returns: 如果成功,初始化UIColor, 否则返回nil convenience init?(hexString:String){ let hex:[Character] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"] let splitHex:(String) -> [CGFloat]? = { // (String) -> [Int] in var num:Int? = nil var hexqueue:[CGFloat] = [] for char in $0.characters{ let i = hex.indexOf(char) guard i >= 0 else {return nil} if num == nil {num = i! * 16} else {hexqueue.append(CGFloat(num! + i!) / 255); num = nil} } return hexqueue } var startIndex = 0 if hexString.characters.first == "#"{startIndex = 1} if hexString.characters.count == 8 + startIndex{ guard let hexcolors = splitHex(hexString.subString(startIndex, length: 8)) else {return nil} self.init(red: hexcolors[1], green: hexcolors[2], blue: hexcolors[3], alpha: hexcolors[0]) } else if hexString.characters.count == 6 + startIndex{ guard let hexcolors = splitHex(hexString.subString(startIndex, length: 6)) else {return nil} self.init(red: hexcolors[0], green: hexcolors[1], blue: hexcolors[2], alpha: 1) } else{return nil} } }
gpl-3.0
5fbbfde3d4a8da48b98eeebe4813e6b6
26.3
104
0.672194
3.207174
false
false
false
false
CNKCQ/oschina
OSCHINA/Utils/Utils/FileTool.swift
1
2461
// // Copyright © 2016年 Jack. All rights reserved. // Created by KingCQ on 16/8/3. // import UIKit class FileTool: NSObject { static let fileManager = FileManager.default /// 计算单个文件的大小 class func fileSize(_ path: String) -> Double { if fileManager.fileExists(atPath: path) { var dict = try? fileManager.attributesOfItem(atPath: path) if let fileSize = dict![FileAttributeKey.size] as? Int { return Double(fileSize) / 1024.0 / 1024.0 } } return 0.0 } /// 计算整个文件夹的大小 class func folderSize(_ path: String) -> Double { var folderSize: Double = 0 if fileManager.fileExists(atPath: path) { let chilerFiles = fileManager.subpaths(atPath: path) for fileName in chilerFiles! { let tmpPath = path as NSString let fileFullPathName = tmpPath.appendingPathComponent(fileName) folderSize += FileTool.fileSize(fileFullPathName) } return folderSize } return 0 } /// 清除文件 同步 class func cleanFolder(_ path: String, complete: () -> Void) { let chilerFiles = fileManager.subpaths(atPath: path) for fileName in chilerFiles! { let tmpPath = path as NSString let fileFullPathName = tmpPath.appendingPathComponent(fileName) if fileManager.fileExists(atPath: fileFullPathName) { do { try fileManager.removeItem(atPath: fileFullPathName) } catch _ { } } } complete() } /// 清除文件 异步 class func cleanFolderAsync(_ path: String, complete: @escaping () -> Void) { let queue = DispatchQueue(label: "cleanQueue", attributes: []) queue.async { () in let chilerFiles = self.fileManager.subpaths(atPath: path) for fileName in chilerFiles! { let tmpPath = path as NSString let fileFullPathName = tmpPath.appendingPathComponent(fileName) if self.fileManager.fileExists(atPath: fileFullPathName) { do { try self.fileManager.removeItem(atPath: fileFullPathName) } catch _ { } } } complete() } } }
mit
5b1de46bd2d6c620b80b3cc2bfa16183
29.717949
81
0.55217
4.981289
false
false
false
false
googlearchive/science-journal-ios
ScienceJournal/UI/DrawerPosition.swift
1
1997
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit /// Represents a position that the drawer can be open to. open class DrawerPosition: Equatable { public static func == (lhs: DrawerPosition, rhs: DrawerPosition) -> Bool { return lhs.panDistance == rhs.panDistance && lhs.canShowKeyboard == rhs.canShowKeyboard } /// The closure that calculates the position's content height. var contentHeightClosure: (() -> (CGFloat))? /// The visible content height of the position. var contentHeight: CGFloat { guard let contentHeightClosure = contentHeightClosure else { return 0 } return contentHeightClosure() } /// The pan distance that the drawer needs to be moved up the screen (negative view coordinate /// direction) to snap to this position. This is the negative of the content height. var panDistance: CGFloat { return -contentHeight } /// Whether or not a drawer position allows showing the keyboard. let canShowKeyboard: Bool /// Designated initializer. /// /// - Parameters: /// - canShowKeyboard: Whether or not a drawer position allows showing the keyboard. /// - contentHeightClosure: The closure that calculates the position's visible content height. public init(canShowKeyboard: Bool, contentHeightClosure: (() -> (CGFloat))? = nil) { self.canShowKeyboard = canShowKeyboard self.contentHeightClosure = contentHeightClosure } }
apache-2.0
606caf6fa14375b5852c5b171931be39
35.981481
98
0.725588
4.528345
false
false
false
false
tecgirl/firefox-ios
Client/Frontend/Browser/TopTabsViewController.swift
1
10351
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Storage import WebKit struct TopTabsUX { static let TopTabsViewHeight: CGFloat = 44 static let TopTabsBackgroundShadowWidth: CGFloat = 12 static let TabWidth: CGFloat = 190 static let FaderPading: CGFloat = 8 static let SeparatorWidth: CGFloat = 1 static let HighlightLineWidth: CGFloat = 3 static let TabNudge: CGFloat = 1 // Nudge the favicon and close button by 1px static let TabTitlePadding: CGFloat = 10 static let AnimationSpeed: TimeInterval = 0.1 static let SeparatorYOffset: CGFloat = 7 static let SeparatorHeight: CGFloat = 32 } protocol TopTabsDelegate: AnyObject { func topTabsDidPressTabs() func topTabsDidPressNewTab(_ isPrivate: Bool) func topTabsDidTogglePrivateMode() func topTabsDidChangeTab() } class TopTabsViewController: UIViewController { let tabManager: TabManager weak var delegate: TopTabsDelegate? fileprivate var tabDisplayManager: TabDisplayManager! var tabCellIdentifer: TabDisplayer.TabCellIdentifer = TopTabCell.Identifier lazy var collectionView: UICollectionView = { let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: TopTabsViewLayout()) collectionView.register(TopTabCell.self, forCellWithReuseIdentifier: TopTabCell.Identifier) collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.bounces = false collectionView.clipsToBounds = false collectionView.accessibilityIdentifier = "Top Tabs View" collectionView.semanticContentAttribute = .forceLeftToRight return collectionView }() fileprivate lazy var tabsButton: TabsButton = { let tabsButton = TabsButton.tabTrayButton() tabsButton.semanticContentAttribute = .forceLeftToRight tabsButton.addTarget(self, action: #selector(TopTabsViewController.tabsTrayTapped), for: .touchUpInside) tabsButton.accessibilityIdentifier = "TopTabsViewController.tabsButton" return tabsButton }() fileprivate lazy var newTab: UIButton = { let newTab = UIButton.newTabButton() newTab.semanticContentAttribute = .forceLeftToRight newTab.addTarget(self, action: #selector(TopTabsViewController.newTabTapped), for: .touchUpInside) newTab.accessibilityIdentifier = "TopTabsViewController.newTabButton" return newTab }() lazy var privateModeButton: PrivateModeButton = { let privateModeButton = PrivateModeButton() privateModeButton.semanticContentAttribute = .forceLeftToRight privateModeButton.accessibilityIdentifier = "TopTabsViewController.privateModeButton" privateModeButton.addTarget(self, action: #selector(TopTabsViewController.togglePrivateModeTapped), for: .touchUpInside) return privateModeButton }() fileprivate lazy var tabLayoutDelegate: TopTabsLayoutDelegate = { let delegate = TopTabsLayoutDelegate() delegate.tabSelectionDelegate = tabDisplayManager return delegate }() init(tabManager: TabManager) { self.tabManager = tabManager super.init(nibName: nil, bundle: nil) tabDisplayManager = TabDisplayManager(collectionView: self.collectionView, tabManager: self.tabManager, tabDisplayer: self) collectionView.dataSource = tabDisplayManager collectionView.delegate = tabLayoutDelegate [UICollectionElementKindSectionHeader, UICollectionElementKindSectionFooter].forEach { collectionView.register(TopTabsHeaderFooter.self, forSupplementaryViewOfKind: $0, withReuseIdentifier: "HeaderFooter") } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.tabDisplayManager.performTabUpdates() } override func viewDidLoad() { super.viewDidLoad() if #available(iOS 11.0, *) { collectionView.dragDelegate = tabDisplayManager collectionView.dropDelegate = tabDisplayManager } let topTabFader = TopTabFader() topTabFader.semanticContentAttribute = .forceLeftToRight view.addSubview(topTabFader) topTabFader.addSubview(collectionView) view.addSubview(tabsButton) view.addSubview(newTab) view.addSubview(privateModeButton) // Setup UIDropInteraction to handle dragging and dropping // links onto the "New Tab" button. if #available(iOS 11, *) { let dropInteraction = UIDropInteraction(delegate: tabDisplayManager) newTab.addInteraction(dropInteraction) } newTab.snp.makeConstraints { make in make.centerY.equalTo(view) make.trailing.equalTo(tabsButton.snp.leading).offset(-10) make.size.equalTo(view.snp.height) } tabsButton.snp.makeConstraints { make in make.centerY.equalTo(view) make.trailing.equalTo(view).offset(-10) make.size.equalTo(view.snp.height) } privateModeButton.snp.makeConstraints { make in make.centerY.equalTo(view) make.leading.equalTo(view).offset(10) make.size.equalTo(view.snp.height) } topTabFader.snp.makeConstraints { make in make.top.bottom.equalTo(view) make.leading.equalTo(privateModeButton.snp.trailing) make.trailing.equalTo(newTab.snp.leading) } collectionView.snp.makeConstraints { make in make.edges.equalTo(topTabFader) } tabsButton.applyTheme() applyUIMode(isPrivate: tabManager.selectedTab?.isPrivate ?? false) updateTabCount(tabDisplayManager.tabCount, animated: false) } func switchForegroundStatus(isInForeground reveal: Bool) { // Called when the app leaves the foreground to make sure no information is inadvertently revealed if let cells = self.collectionView.visibleCells as? [TopTabCell] { let alpha: CGFloat = reveal ? 1 : 0 for cell in cells { cell.titleText.alpha = alpha cell.favicon.alpha = alpha } } } func updateTabCount(_ count: Int, animated: Bool = true) { self.tabsButton.updateTabCount(count, animated: animated) } @objc func tabsTrayTapped() { delegate?.topTabsDidPressTabs() } @objc func newTabTapped() { if tabDisplayManager.pendingReloadData { return } self.delegate?.topTabsDidPressNewTab(self.tabDisplayManager.isPrivate) LeanPlumClient.shared.track(event: .openedNewTab, withParameters: ["Source": "Add tab button in the URL Bar on iPad"]) } @objc func togglePrivateModeTapped() { let currentMode = tabDisplayManager.isPrivate tabDisplayManager.togglePBM() if currentMode != tabDisplayManager.isPrivate { delegate?.topTabsDidTogglePrivateMode() } self.privateModeButton.setSelected(tabDisplayManager.isPrivate, animated: true) } func scrollToCurrentTab(_ animated: Bool = true, centerCell: Bool = false) { assertIsMainThread("Only animate on the main thread") guard let currentTab = tabManager.selectedTab, let index = tabDisplayManager.tabStore.index(of: currentTab), !collectionView.frame.isEmpty else { return } if let frame = collectionView.layoutAttributesForItem(at: IndexPath(row: index, section: 0))?.frame { if centerCell { collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .centeredHorizontally, animated: false) } else { // Padding is added to ensure the tab is completely visible (none of the tab is under the fader) let padFrame = frame.insetBy(dx: -(TopTabsUX.TopTabsBackgroundShadowWidth+TopTabsUX.FaderPading), dy: 0) if animated { UIView.animate(withDuration: TopTabsUX.AnimationSpeed, animations: { self.collectionView.scrollRectToVisible(padFrame, animated: true) }) } else { collectionView.scrollRectToVisible(padFrame, animated: false) } } } } } extension TopTabsViewController: TabDisplayer { func focusSelectedTab() { self.scrollToCurrentTab(true, centerCell: true) } func cellFactory(for cell: UICollectionViewCell, using tab: Tab) -> UICollectionViewCell { guard let tabCell = cell as? TopTabCell else { return UICollectionViewCell() } tabCell.delegate = self let isSelected = (tab == tabManager.selectedTab) tabCell.configureWith(tab: tab, isSelected: isSelected) return tabCell } } extension TopTabsViewController: TopTabCellDelegate { func tabCellDidClose(_ cell: UICollectionViewCell) { // Trying to remove tabs while animating can lead to crashes as indexes change. If updates are happening don't allow tabs to be removed. guard let index = collectionView.indexPath(for: cell)?.item else { return } if let tab = self.tabDisplayManager.tabStore[safe: index] { tabManager.removeTab(tab) } } } extension TopTabsViewController: Themeable, PrivateModeUI { func applyUIMode(isPrivate: Bool) { tabDisplayManager.isPrivate = isPrivate privateModeButton.onTint = UIColor.theme.topTabs.privateModeButtonOnTint privateModeButton.offTint = UIColor.theme.topTabs.privateModeButtonOffTint privateModeButton.applyUIMode(isPrivate: tabDisplayManager.isPrivate) } func applyTheme() { tabsButton.applyTheme() newTab.tintColor = UIColor.theme.topTabs.buttonTint view.backgroundColor = UIColor.theme.topTabs.background collectionView.backgroundColor = view.backgroundColor } }
mpl-2.0
12c1492fd1663e1227ff1fc34d339ae8
38.965251
153
0.68689
5.408046
false
false
false
false
vmachiel/swift
CalculatorV2/Calculator/CalculatorBrain.swift
1
12658
// // CalculatorBrain.swift // Calculator // // Created by Machiel van Dorst on 25-07-17. // Copyright © 2017 vmachiel. All rights reserved. // import Foundation // What does this model allow PUBLICLY? What does it allow the controller to do? // No need for inheritance. Will only be refferenced by one Controller. struct CalculatorBrain { // MARK: - Properties // A stack to collect all operations and operands and variables. Will keep everything, until you // press undo or clear private var stack = [Element]() // Public properties that return the result is availible, wether an operation is pending, and // a description. All are taken from the return tuple of the evaluate() method. // NOTICE: These are now deprecated as per the assignment inscructions. Searching online tells me // I should use @availible @available(*, deprecated, message: "Depricated, no longer useable") var result: Double? { return evaluate().result } @available(*, deprecated, message: "Depricated, no longer useable") var resultIsPending: Bool { return evaluate().isPending } @available(*, deprecated, message: "Depricated, no longer useable") var description: String? { return evaluate().description } // MARK: - Basic operation // The options for to use in the evalute function, which handles variables ('x') as well. // Use asso. values to pass actual values along, define types here. private enum Element { case operation(String) case operand(Double) case variable(String) } // The different kinds of operations the evaluatie method can handle. Defined types in asso. values. private enum Operation { case constant(Double) case unaryOperation((Double) -> Double, (String) -> String) case binaryOperation((Double, Double) -> Double, (String, String) -> String) case nullaryOperation(() -> Double, String) case equals } // The different kinds of error messages that can appear, one for unary and one for binary. // The two values are passed, and an optional error message is returned. private enum Errors { case unaryError((Double) -> String?) case binaryError((Double, Double) -> String?) } // Dict built using the Operation enum as values, which are found by string keys passed from VC. // Constants can built in functions are used, // as well as closures to perform the actual operations and build de description // strings. // It knows which $ should be of what type because you defined it in the Operation enum. // Note to self: In the description case, the new stuff is constantly added to the // existing description!!! private let operations: Dictionary<String, Operation> = [ "π" : Operation.constant(Double.pi), "e" : Operation.constant(M_E), "√" : Operation.unaryOperation(sqrt, { "√(" + $0 + ")" }), "x²" : Operation.unaryOperation({ pow($0, 2) }, { "(" + $0 + ")²" }), "x³" : Operation.unaryOperation({ pow($0, 3) }, { "(" + $0 + ")³" }), "eˣ" : Operation.unaryOperation(exp, { "e^(" + $0 + ")" }), "cos" : Operation.unaryOperation(cos, { "cos(" + $0 + ")" }), "sin" : Operation.unaryOperation(sin, { "sin(" + $0 + ")" }), "tan" : Operation.unaryOperation(tan, { "tan(" + $0 + ")" }), "±" : Operation.unaryOperation({ -$0 }, { "-(" + $0 + ")" }), "1/x" : Operation.unaryOperation({ 1/$0 }, { "1/(" + $0 + ")" } ), "ln" : Operation.unaryOperation(log2, { "ln(" + $0 + ")" }), "log" : Operation.unaryOperation(log10, { "log(" + $0 + ")" }), "x" : Operation.binaryOperation({ $0 * $1 }, { $0 + "x" + $1 }), "÷" : Operation.binaryOperation({ $0 / $1 }, { $0 + "÷" + $1 }), "+" : Operation.binaryOperation({ $0 + $1 }, { $0 + "+" + $1 }), "-" : Operation.binaryOperation({ $0 - $1 }, { $0 + "-" + $1 }), "xʸ" : Operation.binaryOperation(pow, { $0 + "^" + $1 }), "Rnd" : Operation.nullaryOperation({ Double(arc4random()) / Double(UInt32.max) }, "rand()"), "=" : Operation.equals ] // Dict built using the Errors enum as values , which are found by string keys passed from VC. // For each error, test the conditions under which the error occurs as a closure. If true, set the // error message that should return, and nil if not (no error) private let errorsInOperation: Dictionary<String, Errors> = [ "√" : Errors.unaryError({ $0 < 0.0 ? "Root of negative number." : nil }), "÷" : Errors.binaryError({$1 == 0.0 ? "Divide by 0" : nil}), "1/x" : Errors.unaryError({$0 == 0.0 ? "Divide by 0" : nil}), "ln" : Errors.unaryError({ $0 < 0.0 ? "Natural log of negative" : nil }), "log" : Errors.unaryError({ $0 < 0.0 ? "10 log of negative" : nil }) ] // MARK: - Variable specific operations: New API in V2 // Version of set operand with a regular double mutating func setOperand(_ operand: Double) { stack.append(Element.operand(operand)) } // Version of set operand for dealing with variables as operands. Set add them to the stack mutating func setOperand(variable named: String) { stack.append(Element.variable(named)) } // Add the operation to be done onto the stack: mutating func performOperation(operation symbol: String) { stack.append(Element.operation(symbol)) } // Undo, by removing the last Element from stack. VC calls evaluate and update display after this. mutating func undo() { if !stack.isEmpty { stack.removeLast() } } // MARK: - Evaluate // This method will perform the evaluation on the stack of operands, variables and instructions. // A lot of code (accu, pending etc.) has been moved inside this method. // It takes a dictionary with all the variable names currently stored, with they values. // If none are stored, dict = nil. It returns a result if it can, weather an operation is pending, // and the description of the calculation, which defaults to an empty string. func evaluate(using variables: Dictionary<String, Double>? = nil) -> (result: Double?, isPending: Bool, description: String, error: String?) { // First, setup the accumulator and the pending binary operation stuff. // This is moved inside this method because because this method handles variables var accumulator: (acc: Double, des: String)? // Takes a operation, a description to add to the description string, and a accumulator to // set to the first operand. Is nil if nothing pending. var pendingBinaryOperation: PendingBinaryOperation? // Has the evaluation produced an error? var error: String? struct PendingBinaryOperation { // Store the acutal function, the description and the current (operand, description) // Also store the symbol or the operation, so it can be checked for errors in evalute() let function: (Double, Double) -> Double // What binary op is being done? (passed by closure) let description: (String, String) -> String let firstOperand: (Double, String) let symbol: String // Called when the second operand is set and equals is passed func perform(with secondOperand: (Double, String)) -> (Double, String) { return (function(firstOperand.0, secondOperand.0), description(firstOperand.1, secondOperand.1)) } } // If it does have data and equals is pressed and there is a new number in the accumulator, // call its perform method. // Again error check: if the symbol is in the dict, set the asso. value function to errorFunction. // Pass it the accu and operand, and if true (thus error) set message to optional var error. func performPendingBinaryOperation() { if pendingBinaryOperation != nil && accumulator != nil { if let errorOperation = errorsInOperation[pendingBinaryOperation!.symbol], case .binaryError(let errorFunction) = errorOperation { error = errorFunction(pendingBinaryOperation!.firstOperand.0, accumulator!.0) } accumulator = pendingBinaryOperation!.perform(with: accumulator!) pendingBinaryOperation = nil } } // The result and description to be returned at the end, after the code that evals the stack. // Check optionals so you only unwrap safely! var result: Double? { if accumulator != nil { return accumulator!.acc } return nil } // Check if pending operation, else return accu description, which can be an empty string var description: String? { if pendingBinaryOperation != nil { return pendingBinaryOperation!.description(pendingBinaryOperation!.firstOperand.1, accumulator?.1 ?? "") } else { return accumulator?.1 } } // The meat of the method: evaluation. The term stack is misleading here, it's not last in first // out, but first in first out. For each element in the stack, check what it is. // Operand? set acc to it. // Operation? Check the dictionary for a match, and switch the value (which is an enum Operation) // to perform the appropriate action, same as before. // ADDED: Error operations, will check for error, and set the error message to var error: String?, // if one is found. If non is found, it'll remain nil and return as nil // If it's a variable, look it up in optional dictionary to see if it has a value associated with it // If not, display 0 for element in stack { switch element { case .operand(let value): accumulator = (value, "\(value)") case .operation(let symbol): if let operation = operations[symbol] { switch operation { // Constant? set it to the accumulator, so the ViewController can // get it back to the display. Save the symbol as well. case .constant(let value): accumulator = (value, symbol) case .unaryOperation(let function, let description): if accumulator != nil { // If the symbol is found in the error dict, set it to errorOperation. // This is unary, so to that errorOperation, and extrac the asso value. // Pass it the accumulator value, and set result (message or nil) to error. if let errorOperation = errorsInOperation[symbol], case .unaryError(let errorFunction) = errorOperation { error = errorFunction(accumulator!.0) } accumulator = (function(accumulator!.acc), description(accumulator!.des)) } // Again, the ass values of the enum stored in the dict value can be set to constants. // Pass symbol for erro case .binaryOperation(let function, let description): performPendingBinaryOperation() if accumulator != nil { pendingBinaryOperation = PendingBinaryOperation(function: function, description: description, firstOperand: accumulator!, symbol: symbol) accumulator = nil } case .equals: performPendingBinaryOperation() case .nullaryOperation(let function, let description): accumulator = (function(), description) } } // If the variable has a value: display it. If not, show it as 0 case .variable(let symbol): if let value = variables?[symbol] { accumulator = (value, symbol) } else { accumulator = (0, symbol) } } } return (result, pendingBinaryOperation != nil, description ?? "", error) } }
mit
78e1862211547ed385fd7787f6b95de7
46.698113
165
0.593513
4.672828
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab3Sell/SLV_315_SellCommonStep05BrandController.swift
1
18953
// // SLV_315_SellCommonStep05BrandController.swift // selluv-ios // // Created by 조백근 on 2016. 11. 8.. // Copyright © 2016년 BitBoy Labs. All rights reserved. // /* 판매 공통 5브랜드 선택 컨트롤러 */ import Foundation import UIKit class SLVBrandListCell: UITableViewCell { @IBOutlet weak var brandLabel: UILabel! } class SLV_315_SellCommonStep05BrandController: SLVBaseStatusHiddenController { @IBOutlet weak var searchTableView: SearchTableView! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tabController.animationTabBarHidden(true) tabController.hideFab() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // self.searchTableView.searchActive(true) // self.searchTableView.becomeKeyboard() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) searchTableView.searchActive(false) } override func viewDidLoad() { super.viewDidLoad() self.title = "브랜드 선택" self.setupBackButton() self.switchButton() searchTableView.layoutMargins = UIEdgeInsets.zero searchTableView.separatorInset = UIEdgeInsets.zero definesPresentationContext = true extendedLayoutIncludesOpaqueBars = true searchTableView.searchDataSource = self searchTableView.setHolder(holder: "브랜드를 검색하실 수 있습니다.") searchTableView.setBarStyel(style: .default) searchTableView.customSearchBarStyle() searchTableView.sectionIndexColor = text_color_bl51 searchTableView.sectionIndexBackgroundColor = UIColor.clear if BrandModel.shared.isEnName { searchTableView.itemList = Array(BrandModel.shared.enBrands!) } else { searchTableView.itemList = Array(BrandModel.shared.koBrands!) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func setupBackButton() { let back = UIButton() back.setImage(UIImage(named:"ic-back-arrow.png"), for: .normal) back.frame = CGRect(x: 17, y: 23, width: 12+32, height: 20) back.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 26) back.addTarget(self, action: #selector(SLV_313_SellCommonStep03Category2Controller.back(sender:)), for: .touchUpInside) let item = UIBarButtonItem(customView: back) self.navigationItem.leftBarButtonItem = item } func switchButton() { let mySwitch = Switch() mySwitch.frame = CGRect(x: 0, y: 0, width: 82, height: 32) mySwitch.leftText = "영어" mySwitch.rightText = "한글" mySwitch.rightSelected = false mySwitch.tintColor = UIColor.darkGray mySwitch.disabledColor = UIColor.init(colorLiteralRed: 204/255, green: 204/255, blue: 204/255, alpha: 1)// mySwitch.addTarget(self, action: #selector(SLV_315_SellCommonStep05BrandController.changeLanguage(sender:)), for: .valueChanged) let sw = UIBarButtonItem(customView: mySwitch) self.navigationItem.setRightBarButtonItems([sw], animated: false ) } func changeLanguage(sender: AnyObject) { let sw: Switch = sender as! Switch if sw.rightSelected == false { BrandModel.shared.isEnName = true searchTableView.itemList = Array(BrandModel.shared.enBrands!) } else { BrandModel.shared.isEnName = false searchTableView.itemList = Array(BrandModel.shared.koBrands!) } if searchTableView.isSearching() { BrandModel.shared.updateSearchResults() } self.searchTableView.reloadData() } func requestNewBrand() { let keyword = self.searchTableView.keyword()?.trimmed if keyword != "" {//한글 초성 추출 후 첫번째 프리픽스 꺼내서 한영 체크 let divide = keyword?.hangul ?? "" let first = divide.firstCharacter ?? "" //2. 초성추출 let isEnglish = first.isAlphanumeric //1. 한글여부 SellDataModel.shared.addUnknownBrand(name: keyword!, firstIndex: first, isEnglish: isEnglish, completion: { (success, brandId) in if success == false { AlertHelper.alert(message: "요청에 실패하였습니다.") } // let korean = isEnglish ? "":keyword! // let english = isEnglish ? keyword!:"" TempInputInfoModel.shared.selectBrand(code: brandId, korean:keyword, english: keyword, isEn: isEnglish) self.next() }) } } //MARK: Event func back(sender: UIBarButtonItem?) { _ = self.navigationController?.tr_popViewController() } @IBAction func touchClose(_ sender: Any) { tabController.closePresent {} } func touchNewBrand(sender: UIButton) { //모달뛰워!@ self.popupNewBrandNotice() } func next() { let isDirect = TempInputInfoModel.shared.isDirectInput if isDirect == true { //직접 판매 let board = UIStoryboard(name:"Sell", bundle: nil) let photoController = board.instantiateViewController(withIdentifier: "SLV_316_SellDirectStep1PhotoContoller") as! SLV_316_SellDirectStep1PhotoContoller // self.navigationController?.show(photoController, sender: nil) self.navigationController?.tr_pushViewController(photoController, method: TRPushTransitionMethod.default, statusBarStyle: .hide) { photoController.setupDefaultPhotoMode() } } else { //발렛 판매 let board = UIStoryboard(name:"Sell", bundle: nil) let controller = board.instantiateViewController(withIdentifier: "SLV_380_SellBallet1SellerInfoController") as! SLV_380_SellBallet1SellerInfoController self.navigationController?.tr_pushViewController(controller, method: TRPushTransitionMethod.default, statusBarStyle: .hide) { } } } //MARK: call Custom Popup func popupNewBrandNotice() { self.searchTableView.resignKeyboard() let name = self.searchTableView.keyword()?.trimmed if let popupView = Bundle.main.loadNibNamed("SLV_NobrandPopup", owner: self, options: nil)?.first as? SLV_NobrandPopup { let popupConfig = STZPopupViewConfig() popupConfig.dismissTouchBackground = true popupConfig.cornerRadius = 4 popupConfig.overlayColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5) popupConfig.showAnimation = .fadeIn popupConfig.dismissAnimation = .fadeOut popupConfig.showCompletion = { popupView in let option = popupView as! SLV_NobrandPopup option.binding() option.setupNewBrandName(name!) log.debug("show") } popupConfig.dismissCompletion = { popupView in log.debug("dismiss") let option = popupView as! SLV_NobrandPopup if option.isRegisterOk == true { self.requestNewBrand() } } presentPopupView(popupView, config: popupConfig) popupView.popBaseConstraints(config: popupConfig, parent: self) } } // override func prepare(for segue: UIStoryboardSegue?, sender: Any?) { // if (segue?.identifier == "SLV_316_SellDirectStep1PhotoContoller") { // let viewController = segue!.destination as! SLV_316_SellDirectStep1PhotoContoller // viewController.setupDefaultPhotoMode() // } // } } extension SLV_315_SellCommonStep05BrandController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { var cellBrand: Brand? if self.searchTableView.isSearching() { if BrandModel.shared.isEnName { let key = BrandModel.shared.searchSections?[indexPath.section] let p = NSPredicate(format: "indexEn==%@", key!) let rows = BrandModel.shared.searchBrands?.filter {p.evaluate(with: $0)} cellBrand = (rows?[indexPath.row])! as Brand } else { let key = BrandModel.shared.searchSections?[indexPath.section] let p = NSPredicate(format: "indexKo==%@", key!) let rows = BrandModel.shared.searchBrands?.filter {p.evaluate(with: $0)} cellBrand = (rows?[indexPath.row])! as Brand } } else { if BrandModel.shared.isEnName { let key = BrandModel.shared.enSections?[indexPath.section] let p = NSPredicate(format: "indexEn==%@", key!) let rows = BrandModel.shared.enBrands?.filter(p) cellBrand = (rows?[indexPath.row])! as Brand } else { let key = BrandModel.shared.koSections?[indexPath.section] let p = NSPredicate(format: "indexKo==%@", key!) let rows = BrandModel.shared.koBrands?.filter(p) cellBrand = (rows?[indexPath.row])! as Brand } } if let brand = cellBrand { let key = brand.id let isEn = BrandModel.shared.isEnName TempInputInfoModel.shared.selectBrand(code: key, korean: brand.korean, english: brand.english, isEn: isEn) self.next() } tableView.deselectRow(at: indexPath as IndexPath, animated: false) } } extension SLV_315_SellCommonStep05BrandController: UITableViewDataSource { func sectionIndexTitles(for tableView: UITableView) -> [String]? { // return list of section titles to display in section index view (e.g. "ABCD...Z#") if self.searchTableView.isSearching() { return BrandModel.shared.searchSections } else { if BrandModel.shared.isEnName { return BrandModel.shared.enSections } else { return BrandModel.shared.koSections } } } // optional public func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int // tell table which section corresponds to section title/index (e.g. "B",1)) func numberOfSections(in tableView: UITableView) -> Int { if self.searchTableView.isSearching() { if let section = BrandModel.shared.searchSections { let count = section.count if count == 0 { return 1 } return count } return 1 } else { if BrandModel.shared.isEnName { return (BrandModel.shared.enSections?.count)! } else { return (BrandModel.shared.koSections?.count)! } } } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView() view.frame = CGRect(x:0, y:0, width: UIScreen.main.bounds.width, height:51) view.backgroundColor = bg_color_g245 let label = UILabel() label.font = UIFont.systemFont(ofSize: 15, weight: UIFontWeightRegular) label.textColor = text_color_bl51 label.frame = CGRect(x:30, y:10, width: 30, height: 30) label.backgroundColor = UIColor.clear label.textAlignment = .left view.addSubview(label) if self.searchTableView.isSearching() { let searchGroup = BrandModel.shared.searchSections if searchGroup != nil && searchGroup!.count > 0 { label.text = searchGroup![section] } else { //등록 지원 let name = searchTableView.keyword() if let key = name { if key != "" { let text = "+ '\(key)' 브랜드 추가하기" label.textColor = UIColor.white label.frame = CGRect(x:30, y:10, width: 240, height: 30) label.textAlignment = .left label.text = text view.backgroundColor = bg_color_brass let btn = UIButton(type: .custom) btn.frame = view.frame btn.addTarget(self, action: #selector(SLV_315_SellCommonStep05BrandController.touchNewBrand(sender:)), for: .touchUpInside) view.addSubview(btn) } } } } else { if BrandModel.shared.isEnName { label.text = (BrandModel.shared.enSections?[section])! } else { label.text = (BrandModel.shared.koSections?[section])! } } return view } // func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { // if self.isEn { // return (BrandModel.shared.enSections?[section])! // } else { // return (BrandModel.shared.koSections?[section])! // } // } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // return searchTableView.itemList.count if self.searchTableView.isSearching() { let searchGroup = BrandModel.shared.searchSections if searchGroup == nil || searchGroup!.count == 0 { return 0 } if BrandModel.shared.isEnName { let key = BrandModel.shared.searchSections?[section] let p = NSPredicate(format: "indexEn==%@", key!) let rows = BrandModel.shared.searchBrands?.filter {p.evaluate(with: $0)} return rows!.count } else { let key = BrandModel.shared.searchSections?[section] let p = NSPredicate(format: "indexKo==%@", key!) let rows = BrandModel.shared.searchBrands?.filter {p.evaluate(with: $0)} return rows!.count } } else { if BrandModel.shared.isEnName { let key = BrandModel.shared.enSections?[section] let p = NSPredicate(format: "indexEn==%@", key!) let rows = BrandModel.shared.enBrands?.filter(p) return rows!.count } else { let key = BrandModel.shared.koSections?[section] let p = NSPredicate(format: "indexKo==%@", key!) let rows = BrandModel.shared.koBrands?.filter(p) return rows!.count } } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "SLVBrandListCell", for: indexPath) as! SLVBrandListCell //let brand = searchTableView.itemList[(indexPath as NSIndexPath).row] as! Brand //items.filter("race == %@", sectionNames[indexPath.section])[indexPath.row].name cell.brandLabel.textColor = UIColor.gray var cellBrand: Brand? if self.searchTableView.isSearching() { if BrandModel.shared.isEnName { let key = BrandModel.shared.searchSections?[indexPath.section] let p = NSPredicate(format: "indexEn==%@", key!) let rows = BrandModel.shared.searchBrands?.filter {p.evaluate(with: $0)} cellBrand = (rows?[indexPath.row])! as Brand } else { let key = BrandModel.shared.searchSections?[indexPath.section] let p = NSPredicate(format: "indexKo==%@", key!) let rows = BrandModel.shared.searchBrands?.filter {p.evaluate(with: $0)} cellBrand = (rows?[indexPath.row])! as Brand } } else { if BrandModel.shared.isEnName { let key = BrandModel.shared.enSections?[indexPath.section] let p = NSPredicate(format: "indexEn==%@", key!) let rows = BrandModel.shared.enBrands?.filter(p) cellBrand = (rows?[indexPath.row])! as Brand } else { let key = BrandModel.shared.koSections?[indexPath.section] let p = NSPredicate(format: "indexKo==%@", key!) let rows = BrandModel.shared.koBrands?.filter(p) cellBrand = (rows?[indexPath.row])! as Brand } } if let brand = cellBrand { let en = brand.english let ko = brand.korean let enLen = en.distance(from: en.startIndex, to: en.endIndex) let koLen = ko.distance(from: ko.startIndex, to: ko.endIndex) let enFirst = "\(en) \(ko)" let koFirst = "\(ko) \(en)" if BrandModel.shared.isEnName == true { let myMutableString = NSMutableAttributedString(string: enFirst, attributes: [ NSFontAttributeName:UIFont.systemFont(ofSize: 13), NSForegroundColorAttributeName: text_color_g153] ) myMutableString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 15), range: NSRange(location:0,length:enLen)) myMutableString.addAttribute(NSForegroundColorAttributeName, value: text_color_bl51, range: NSRange(location:0,length:enLen)) cell.brandLabel.attributedText = myMutableString } else { let myMutableString = NSMutableAttributedString(string: koFirst, attributes: [ NSFontAttributeName:UIFont.systemFont(ofSize: 13), NSForegroundColorAttributeName: text_color_g153] ) myMutableString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 15), range: NSRange(location:0,length:koLen)) myMutableString.addAttribute(NSForegroundColorAttributeName, value: text_color_bl51, range: NSRange(location:0,length:koLen)) cell.brandLabel.attributedText = myMutableString } } cell.layoutMargins = UIEdgeInsets.zero return cell } } extension SLV_315_SellCommonStep05BrandController : SearchTableViewDataSource { func searchPropertyName() -> String { if BrandModel.shared.isEnName { return "english" } else { return "korean" } } }
mit
98875e39318b504b7e12407ca1fd4fe1
41.420814
204
0.589227
4.630773
false
false
false
false
open-telemetry/opentelemetry-swift
Tests/OpenTelemetrySdkTests/Trace/Export/BatchSpansProcessorTests.swift
1
10789
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ import OpenTelemetryApi @testable import OpenTelemetrySdk import XCTest class BatchSpansProcessorTests: XCTestCase { let spanName1 = "MySpanName/1" let spanName2 = "MySpanName/2" let maxScheduleDelay = 0.5 let tracerSdkFactory = TracerProviderSdk() var tracer: Tracer! let blockingSpanExporter = BlockingSpanExporter() var mockServiceHandler = SpanExporterMock() override func setUp() { tracer = tracerSdkFactory.get(instrumentationName: "BatchSpansProcessorTest") } override func tearDown() { tracerSdkFactory.shutdown() } @discardableResult private func createSampledEndedSpan(spanName: String) -> ReadableSpan { let span = TestUtils.createSpanWithSampler(tracerSdkFactory: tracerSdkFactory, tracer: tracer, spanName: spanName, sampler: Samplers.alwaysOn) .startSpan() as! ReadableSpan span.end() return span } private func createNotSampledEndedSpan(spanName: String) { TestUtils.createSpanWithSampler(tracerSdkFactory: tracerSdkFactory, tracer: tracer, spanName: spanName, sampler: Samplers.alwaysOff) .startSpan() .end() } func testStartEndRequirements() { let spansProcessor = BatchSpanProcessor(spanExporter: WaitingSpanExporter(numberToWaitFor: 0)) XCTAssertFalse(spansProcessor.isStartRequired) XCTAssertTrue(spansProcessor.isEndRequired) } func testExportDifferentSampledSpans() { let waitingSpanExporter = WaitingSpanExporter(numberToWaitFor: 2) tracerSdkFactory.addSpanProcessor(BatchSpanProcessor(spanExporter: waitingSpanExporter, scheduleDelay: maxScheduleDelay)) let span1 = createSampledEndedSpan(spanName: spanName1) let span2 = createSampledEndedSpan(spanName: spanName2) let exported = waitingSpanExporter.waitForExport() XCTAssertEqual(exported, [span1.toSpanData(), span2.toSpanData()]) } func testExportMoreSpansThanTheBufferSize() { let waitingSpanExporter = WaitingSpanExporter(numberToWaitFor: 6) tracerSdkFactory.addSpanProcessor(BatchSpanProcessor(spanExporter: waitingSpanExporter, scheduleDelay: maxScheduleDelay, maxQueueSize: 6, maxExportBatchSize: 2)) let span1 = createSampledEndedSpan(spanName: spanName1) let span2 = createSampledEndedSpan(spanName: spanName1) let span3 = createSampledEndedSpan(spanName: spanName1) let span4 = createSampledEndedSpan(spanName: spanName1) let span5 = createSampledEndedSpan(spanName: spanName1) let span6 = createSampledEndedSpan(spanName: spanName1) let exported = waitingSpanExporter.waitForExport() XCTAssertEqual(exported, [span1.toSpanData(), span2.toSpanData(), span3.toSpanData(), span4.toSpanData(), span5.toSpanData(), span6.toSpanData()]) } func testForceExport() { let waitingSpanExporter = WaitingSpanExporter(numberToWaitFor: 1) let batchSpansProcessor = BatchSpanProcessor(spanExporter: waitingSpanExporter, scheduleDelay: 10, maxQueueSize: 10000, maxExportBatchSize: 2000) tracerSdkFactory.addSpanProcessor(batchSpansProcessor) for _ in 0 ..< 100 { createSampledEndedSpan(spanName: "notExported") } batchSpansProcessor.forceFlush() let exported = waitingSpanExporter.waitForExport() XCTAssertEqual(exported?.count, 100) } func testExportSpansToMultipleServices() { let waitingSpanExporter = WaitingSpanExporter(numberToWaitFor: 2) let waitingSpanExporter2 = WaitingSpanExporter(numberToWaitFor: 2) tracerSdkFactory.addSpanProcessor(BatchSpanProcessor(spanExporter: MultiSpanExporter(spanExporters: [waitingSpanExporter, waitingSpanExporter2]), scheduleDelay: maxScheduleDelay)) let span1 = createSampledEndedSpan(spanName: spanName1) let span2 = createSampledEndedSpan(spanName: spanName2) let exported1 = waitingSpanExporter.waitForExport() let exported2 = waitingSpanExporter2.waitForExport() XCTAssertEqual(exported1, [span1.toSpanData(), span2.toSpanData()]) XCTAssertEqual(exported2, [span1.toSpanData(), span2.toSpanData()]) } func testExportMoreSpansThanTheMaximumLimit() { let maxQueuedSpans = 8 let waitingSpanExporter = WaitingSpanExporter(numberToWaitFor: maxQueuedSpans) tracerSdkFactory.addSpanProcessor(BatchSpanProcessor(spanExporter: MultiSpanExporter(spanExporters: [waitingSpanExporter, blockingSpanExporter]), scheduleDelay: maxScheduleDelay, maxQueueSize: maxQueuedSpans, maxExportBatchSize: maxQueuedSpans / 2)) var spansToExport = [SpanData]() // Wait to block the worker thread in the BatchSampledSpansProcessor. This ensures that no items // can be removed from the queue. Need to add a span to trigger the export otherwise the // pipeline is never called. spansToExport.append(createSampledEndedSpan(spanName: "blocking_span").toSpanData()) blockingSpanExporter.waitUntilIsBlocked() for i in 0 ..< maxQueuedSpans { // First export maxQueuedSpans, the worker thread is blocked so all items should be queued. spansToExport.append(createSampledEndedSpan(spanName: "span_1_\(i)").toSpanData()) } // TODO: assertThat(spanExporter.getReferencedSpans()).isEqualTo(maxQueuedSpans); // Now we should start dropping. for i in 0 ..< 7 { createSampledEndedSpan(spanName: "span_2_\(i)") // TODO: assertThat(getDroppedSpans()).isEqualTo(i + 1); } // TODO: assertThat(getReferencedSpans()).isEqualTo(maxQueuedSpans); // Release the blocking exporter blockingSpanExporter.unblock() // While we wait for maxQueuedSpans we ensure that the queue is also empty after this. var exported = waitingSpanExporter.waitForExport() XCTAssertEqual(exported, spansToExport) exported?.removeAll() spansToExport.removeAll() // We cannot compare with maxReferencedSpans here because the worker thread may get // unscheduled immediately after exporting, but before updating the pushed spans, if that is // the case at most bufferSize spans will miss. // TODO: assertThat(getPushedSpans()).isAtLeast((long) maxQueuedSpans - maxBatchSize); for i in 0 ..< maxQueuedSpans { spansToExport.append(createSampledEndedSpan(spanName: "span_3_\(i)").toSpanData()) // No more dropped spans. // TODO: assertThat(getDroppedSpans()).isEqualTo(7); } exported = waitingSpanExporter.waitForExport() XCTAssertEqual(exported, spansToExport) } func testExportNotSampledSpans() { let waitingSpanExporter = WaitingSpanExporter(numberToWaitFor: 1) tracerSdkFactory.addSpanProcessor(BatchSpanProcessor(spanExporter: waitingSpanExporter, scheduleDelay: maxScheduleDelay)) createNotSampledEndedSpan(spanName: spanName1) createNotSampledEndedSpan(spanName: spanName2) let span2 = createSampledEndedSpan(spanName: spanName2) // Spans are recorded and exported in the same order as they are ended, we test that a non // sampled span is not exported by creating and ending a sampled span after a non sampled span // and checking that the first exported span is the sampled span (the non sampled did not get // exported). let exported = waitingSpanExporter.waitForExport() // Need to check this because otherwise the variable span1 is unused, other option is to not // have a span1 variable. XCTAssertEqual(exported, [span2.toSpanData()]) } func testShutdownFlushes() { let waitingSpanExporter = WaitingSpanExporter(numberToWaitFor: 1) // Set the export delay to zero, for no timeout, in order to confirm the #flush() below works tracerSdkFactory.addSpanProcessor(BatchSpanProcessor(spanExporter: waitingSpanExporter, scheduleDelay: 0)) let span2 = createSampledEndedSpan(spanName: spanName2) // Force a shutdown, without this, the waitForExport() call below would block indefinitely. tracerSdkFactory.shutdown() let exported = waitingSpanExporter.waitForExport() XCTAssertEqual(exported, [span2.toSpanData()]) XCTAssertTrue(waitingSpanExporter.shutdownCalled) } } class BlockingSpanExporter: SpanExporter { let cond = NSCondition() enum State { case waitToBlock case blocked case unblocked } var state: State = .waitToBlock func export(spans: [SpanData]) -> SpanExporterResultCode { cond.lock() while state != .unblocked { state = .blocked // Some threads may wait for Blocked State. cond.broadcast() cond.wait() } cond.unlock() return .success } func waitUntilIsBlocked() { cond.lock() while state != .blocked { cond.wait() } cond.unlock() } func flush() -> SpanExporterResultCode { return .success } func shutdown() {} fileprivate func unblock() { cond.lock() state = .unblocked cond.unlock() cond.broadcast() } } class WaitingSpanExporter: SpanExporter { var spanDataList = [SpanData]() let cond = NSCondition() let numberToWaitFor: Int var shutdownCalled = false init(numberToWaitFor: Int) { self.numberToWaitFor = numberToWaitFor } func waitForExport() -> [SpanData]? { var ret: [SpanData] cond.lock() defer { cond.unlock() } while spanDataList.count < numberToWaitFor { cond.wait() } ret = spanDataList spanDataList.removeAll() return ret } func export(spans: [SpanData]) -> SpanExporterResultCode { cond.lock() spanDataList.append(contentsOf: spans) cond.unlock() cond.broadcast() return .success } func flush() -> SpanExporterResultCode { return .success } func shutdown() { shutdownCalled = true } }
apache-2.0
5576a8cf90ee9d61a274a93cb25b16c4
37.395018
257
0.662249
4.892971
false
true
false
false
esttorhe/RxSwift
RxExample/RxExample/Examples/PartialUpdates/PartialUpdatesViewController.swift
1
7832
// // PartialUpdatesViewController.swift // RxExample // // Created by Krunoslav Zaher on 6/8/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import UIKit import RxSwift import RxCocoa //import CoreData let generateCustomSize = true let runAutomatically = false let useAnimatedUpdateForCollectionView = false class PartialUpdatesViewController : ViewController { /* @IBOutlet weak var reloadTableViewOutlet: UITableView! @IBOutlet weak var partialUpdatesTableViewOutlet: UITableView! @IBOutlet weak var partialUpdatesCollectionViewOutlet: UICollectionView! var moc: NSManagedObjectContext! var child: NSManagedObjectContext! var timer: NSTimer? = nil static let initialValue: [HashableSectionModel<String, Int>] = [ NumberSection(model: "section 1", items: [1, 2, 3]), NumberSection(model: "section 2", items: [4, 5, 6]), NumberSection(model: "section 3", items: [7, 8, 9]), NumberSection(model: "section 4", items: [10, 11, 12]), NumberSection(model: "section 5", items: [13, 14, 15]), NumberSection(model: "section 6", items: [16, 17, 18]), NumberSection(model: "section 7", items: [19, 20, 21]), NumberSection(model: "section 8", items: [22, 23, 24]), NumberSection(model: "section 9", items: [25, 26, 27]), NumberSection(model: "section 10", items: [28, 29, 30]) ] static let firstChange: [HashableSectionModel<String, Int>]? = nil var generator = Randomizer(rng: PseudoRandomGenerator(4, 3), sections: initialValue) var sections = Variable([NumberSection]()) let disposeBag = DisposeBag() func skinTableViewDataSource(dataSource: RxTableViewSectionedDataSource<NumberSection>) { dataSource.cellFactory = { (tv, ip, i) in let cell = tv.dequeueReusableCellWithIdentifier("Cell")! ?? UITableViewCell(style:.Default, reuseIdentifier: "Cell") cell.textLabel!.text = "\(i)" return cell } dataSource.titleForHeaderInSection = { [unowned dataSource] (section: Int) -> String in return dataSource.sectionAtIndex(section).model } } func skinCollectionViewDataSource(dataSource: RxCollectionViewSectionedDataSource<NumberSection>) { dataSource.cellFactory = { [unowned dataSource] (cv, ip, i) in let cell = cv.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: ip) as! NumberCell cell.value!.text = "\(i)" return cell } dataSource.supplementaryViewFactory = { [unowned dataSource] (cv, kind, ip) in let section = cv.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "Section", forIndexPath: ip) as! NumberSectionView section.value!.text = "\(dataSource.sectionAtIndex(ip.section).model)" return section } } override func viewDidLoad() { super.viewDidLoad() // For UICollectionView, if another animation starts before previous one is finished, it will sometimes crash :( // It's not deterministic (because Randomizer generates deterministic updates), and if you click fast // It sometimes will and sometimes wont crash, depending on tapping speed. // I guess you can maybe try some tricks with timeout, hard to tell :( That's on Apple side. if generateCustomSize { let nSections = 10 let nItems = 100 var sections = [HashableSectionModel<String, Int>]() for i in 0 ..< nSections { sections.append(HashableSectionModel(model: "Section \(i + 1)", items: Array(i * nItems ..< (i + 1) * nItems))) } generator = Randomizer(rng: PseudoRandomGenerator(4, 3), sections: sections) } #if runAutomatically timer = NSTimer.scheduledTimerWithTimeInterval(0.6, target: self, selector: "randomize", userInfo: nil, repeats: true) #endif self.sections.next(generator.sections) let tvAnimatedDataSource = RxTableViewSectionedAnimatedDataSource<NumberSection>() let reloadDataSource = RxTableViewSectionedReloadDataSource<NumberSection>() skinTableViewDataSource(tvAnimatedDataSource) skinTableViewDataSource(reloadDataSource) let newSections = self.sections >- skip(1) let initialState = [Changeset.initialValue(self.sections.value)] // reactive data sources let updates = zip(self.sections, newSections) { (old, new) in return differentiate(old, finalSections: new) } >- startWith(initialState) updates >- partialUpdatesTableViewOutlet.rx_subscribeWithReactiveDataSource(tvAnimatedDataSource) >- disposeBag.addDisposable self.sections >- reloadTableViewOutlet.rx_subscribeWithReactiveDataSource(reloadDataSource) >- disposeBag.addDisposable // Collection view logic works, but when clicking fast because of internal bugs // collection view will sometimes get confused. I know what you are thinking, // but this is really not a bug in the algorithm. The generated changes are // pseudorandom, and crash happens depending on clicking speed. // // More info in `RxDataSourceStarterKit/README.md` // // If you want, turn this to true, just click slow :) // // While `useAnimatedUpdateForCollectionView` is false, you can click as fast as // you want, table view doesn't seem to have same issues like collection view. #if useAnimatedUpdateForCollectionView let cvAnimatedDataSource = RxCollectionViewSectionedAnimatedDataSource<NumberSection>() skinCollectionViewDataSource(cvAnimatedDataSource) updates >- partialUpdatesCollectionViewOutlet.rx_subscribeWithReactiveDataSource(cvAnimatedDataSource) >- disposeBag.addDisposable #else let cvReloadDataSource = RxCollectionViewSectionedReloadDataSource<NumberSection>() skinCollectionViewDataSource(cvReloadDataSource) self.sections >- partialUpdatesCollectionViewOutlet.rx_subscribeWithReactiveDataSource(cvReloadDataSource) >- disposeBag.addDisposable #endif // touches partialUpdatesCollectionViewOutlet.rx_itemSelected >- subscribeNext { [unowned self] i in print("Let me guess, it's .... It's \(self.generator.sections[i.section].items[i.item]), isn't it? Yeah, I've got it.") } >- disposeBag.addDisposable merge(from([partialUpdatesTableViewOutlet.rx_itemSelected, reloadTableViewOutlet.rx_itemSelected])) >- subscribeNext { [unowned self] i in print("I have a feeling it's .... \(self.generator.sections[i.section].items[i.item])?") } >- disposeBag.addDisposable } override func viewWillDisappear(animated: Bool) { self.timer?.invalidate() } @IBAction func randomize() { generator.randomize() var values = generator.sections // useful for debugging if PartialUpdatesViewController.firstChange != nil { values = PartialUpdatesViewController.firstChange! } //print(values) sections.next(values) }*/ }
mit
34e3e0a20618c27328ab0aaa43a6608d
39.169231
145
0.630873
5.416321
false
false
false
false
felipeuntill/WeddingPlanner
IOS/WeddingPlanner/LocalStorageProvider.swift
1
1663
// // LocalStorageProvider.swift // WeddingPlanner // // Created by Felipe Assunção on 5/27/16. // Copyright © 2016 Felipe Assunção. All rights reserved. // import Foundation public class LocalStorageProvider<T> { var storageKey = "wedding-planner-storage" var userDefaults = NSUserDefaults.standardUserDefaults() var storage = NSUUID().UUIDString init(storage : String){ self.storage = storage } func syncronize (data : AnyObject) { let myData = NSKeyedArchiver.archivedDataWithRootObject(data) NSUserDefaults.standardUserDefaults().setObject(myData, forKey: "\(storageKey)-\(storage)") NSUserDefaults.standardUserDefaults().synchronize() } func restore<T> () -> T? { if let raw = NSUserDefaults.standardUserDefaults().dataForKey("\(storageKey)-\(storage)") { if let result = NSKeyedUnarchiver.unarchiveObjectWithData(raw) as? T{ return result } } return nil } // static func syncronize () { //// let myData = NSKeyedArchiver.archivedDataWithRootObject(RecipeManager.recipes) //// NSUserDefaults.standardUserDefaults().setObject(myData, forKey: "recipearray") //// NSUserDefaults.standardUserDefaults().synchronize() // } // // static func initalizeDefaults () { // if let recipesRaw = NSUserDefaults.standardUserDefaults().dataForKey(storageKey) { // if let recipes = NSKeyedUnarchiver.unarchiveObjectWithData(recipesRaw) as? [Recipe]{ // RecipeManager.recipes = recipes // } // } // } }
mit
a64d45ddbb09de8c5fca25c645f7fe65
31.529412
99
0.637515
4.805797
false
false
false
false
R3dTeam/SwiftLint
Source/SwiftLintFramework/Rules/OperatorFunctionWhitespaceRule.swift
5
2065
// // OperatorWhitespaceRule.swift // SwiftLint // // Created by Akira Hirakawa on 8/6/15. // Copyright (c) 2015 Realm. All rights reserved. // import SourceKittenFramework public struct OperatorFunctionWhitespaceRule: Rule { public init() {} public let identifier = "operator_whitespace" public func validateFile(file: File) -> [StyleViolation] { let operators = ["/", "=", "-", "+", "!", "*", "|", "^", "~", "?", "."].map({"\\\($0)"}) + ["%", "<", ">", "&"] let zeroOrManySpaces = "(\\s{0}|\\s{2,})" let pattern1 = "func\\s+[" + "".join(operators) + "]+\(zeroOrManySpaces)(<[A-Z]+>)?\\(" let pattern2 = "func\(zeroOrManySpaces)[" + "".join(operators) + "]+\\s+(<[A-Z]+>)?\\(" return file.matchPattern("(\(pattern1)|\(pattern2))").filter { _, syntaxKinds in return syntaxKinds.first == .Keyword }.map { range, _ in return StyleViolation(type: .OperatorFunctionWhitespace, location: Location(file: file, offset: range.location), severity: .Medium, reason: self.example.ruleDescription) } } public let example = RuleExample( ruleName: "Operator Function Whitespace Rule", ruleDescription: "Use a single whitespace around operators when " + "defining them.", nonTriggeringExamples: [ "func <| (lhs: Int, rhs: Int) -> Int {}\n", "func <|< <A>(lhs: A, rhs: A) -> A {}\n", "func abc(lhs: Int, rhs: Int) -> Int {}\n" ], triggeringExamples: [ "func <|(lhs: Int, rhs: Int) -> Int {}\n", // no spaces after "func <|<<A>(lhs: A, rhs: A) -> A {}\n", // no spaces after "func <| (lhs: Int, rhs: Int) -> Int {}\n", // 2 spaces after "func <|< <A>(lhs: A, rhs: A) -> A {}\n", // 2 spaces after "func <| (lhs: Int, rhs: Int) -> Int {}\n", // 2 spaces before "func <|< <A>(lhs: A, rhs: A) -> A {}\n" // 2 spaces before ] ) }
mit
ebabb9f458d76be6e60df045db651485
40.3
98
0.504116
3.802947
false
false
false
false
YauheniYarotski/APOD
APOD/AnimationControllers/SwipePresenter.swift
1
1366
// // SwipePresenter // APOD // // Created by Yauheni Yarotski on 6/14/16. // Copyright © 2016 Yauheni_Yarotski. All rights reserved. // import UIKit class SwipePresenter: UIPercentDrivenInteractiveTransition { var interactionInProgress = false fileprivate var shouldCompleteTransition = false func handlePan(_ gestureRecognizer: UIPanGestureRecognizer) { guard let view = gestureRecognizer.view else {return} let verticalMovement = (gestureRecognizer.translation(in: view.window).y / view.window!.bounds.height) * -1 let downwardMovement = fmaxf(Float(verticalMovement), 0.0) let downwardMovementPercent = fminf(downwardMovement, 1.0) let progress = CGFloat(downwardMovementPercent) switch gestureRecognizer.state { case .began: interactionInProgress = true case .changed: shouldCompleteTransition = gestureRecognizer.velocity(in: view).y <= 0 update(progress) case .cancelled: interactionInProgress = false cancel() case .ended: interactionInProgress = false shouldCompleteTransition ? finish() : cancel() default: print("Unsupported") break } } }
mit
8eb56459a0c669a1ce15b4f54caa14c2
28.673913
115
0.611722
5.352941
false
false
false
false
schibsted/layout
LayoutTests/StackViewTests.swift
1
5480
// Copyright © 2017 Schibsted. All rights reserved. import XCTest @testable import Layout func autoLayoutViewOfSize(_ width: CGFloat, _ height: CGFloat) -> UIView { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.widthAnchor.constraint(equalToConstant: width).isActive = true view.heightAnchor.constraint(equalToConstant: height).isActive = true return view } class StackViewTests: XCTestCase { func testFixedSizeElementsInAutoSizedStack() throws { let expectedSize = CGSize(width: 200, height: 150) do { // Check ordinary UIStackView let view = UIStackView(arrangedSubviews: [ autoLayoutViewOfSize(200, 100), autoLayoutViewOfSize(200, 50), ]) view.axis = .vertical view.translatesAutoresizingMaskIntoConstraints = false view.layoutIfNeeded() XCTAssertEqual(view.frame.size, expectedSize) } do { // Check Layout-wrapped UIStackView let view = UIStackView(arrangedSubviews: [ autoLayoutViewOfSize(200, 100), autoLayoutViewOfSize(200, 50), ]) view.axis = .vertical let node = LayoutNode(view: view) node.update() XCTAssertEqual(node.frame.size, expectedSize) XCTAssertEqual(node.view.systemLayoutSizeFitting(.zero), expectedSize) } do { // Check Fully Layout-based UIStackView let node = try LayoutNode( class: UIStackView.self, expressions: ["axis": "vertical"], children: [ LayoutNode(expressions: ["width": "200", "height": "100"]), LayoutNode(expressions: ["width": "200", "height": "50"]), ] ) node.update() XCTAssertEqual(node.frame.size, expectedSize) XCTAssertEqual(node.view.frame.size, expectedSize) } } func testAutoSizeElementsInAutoSizedStack() throws { let label1 = try LayoutNode( class: UILabel.self, expressions: ["text": "Hello World"] ) label1.update() let label1Size = label1.frame.size XCTAssert(label1Size != .zero) let label2 = try LayoutNode( class: UILabel.self, expressions: [ "text": "Goodbye World", // Workaround for behavior change in iOS 11.2 "contentCompressionResistancePriority.horizontal": "required", ] ) label2.update() let label2Size = label2.frame.size XCTAssert(label2Size != .zero) do { // Check ordinary UIStackView let view = UIStackView(arrangedSubviews: [label1.view, label2.view]) view.axis = .vertical view.translatesAutoresizingMaskIntoConstraints = false view.layoutIfNeeded() XCTAssertEqual(label1.view.systemLayoutSizeFitting(.zero), label1Size) XCTAssertEqual(label2.view.systemLayoutSizeFitting(.zero), label2Size) XCTAssertEqual(view.systemLayoutSizeFitting(.zero), CGSize( width: max(label1Size.width, label2Size.width), height: label1Size.height + label2Size.height )) } do { // Check Layout-wrapped UIStackView let view = UIStackView(arrangedSubviews: [label1.view, label2.view]) view.axis = .vertical let node = LayoutNode(view: view) node.update() XCTAssertEqual(label1.view.systemLayoutSizeFitting(.zero), label1Size) XCTAssertEqual(label2.view.systemLayoutSizeFitting(.zero), label2Size) XCTAssertEqual(node.frame.size, CGSize( width: max(label1Size.width, label2Size.width), height: label1Size.height + label2Size.height )) XCTAssertEqual(node.view.systemLayoutSizeFitting(.zero), node.frame.size) } do { // Check Fully Layout-based UIStackView let node = try LayoutNode( class: UIStackView.self, expressions: ["axis": "vertical"], children: [label1, label2] ) node.update() XCTAssertEqual(label1.frame.size, label1Size) XCTAssertEqual(label2.frame.size, label2Size) XCTAssertEqual(node.frame.size, CGSize( width: max(label1Size.width, label2Size.width), height: label1Size.height + label2Size.height )) XCTAssertEqual(node.view.frame.size, node.frame.size) } } func testAutoSizeElementsInFixedWidthStack() throws { let label1 = try LayoutNode( class: UILabel.self, expressions: ["text": "Hello World"] ) let label2 = try LayoutNode( class: UILabel.self, expressions: ["text": "Goodbye World"] ) let node = try LayoutNode( class: UIStackView.self, expressions: ["width": "300", "axis": "vertical"], children: [label1, label2] ) node.update() XCTAssertEqual(node.frame.width, 300) XCTAssert(node.frame.height > 10) XCTAssertEqual(node.view.frame.size, node.frame.size) } }
mit
86c7eb504d44faebe8b01cad7c8ebed9
36.02027
85
0.578208
5.008227
false
false
false
false
raywenderlich/swift-algorithm-club
Longest Common Subsequence/LongestCommonSubsequence.playground/Contents.swift
2
1631
// last checked with Xcode 11.4 #if swift(>=4.0) print("Hello, Swift 4!") #endif extension String { public func longestCommonSubsequence(_ other: String) -> String { func lcsLength(_ other: String) -> [[Int]] { var matrix = [[Int]](repeating: [Int](repeating: 0, count: other.count+1), count: self.count+1) for (i, selfChar) in self.enumerated() { for (j, otherChar) in other.enumerated() { if otherChar == selfChar { matrix[i+1][j+1] = matrix[i][j] + 1 } else { matrix[i+1][j+1] = max(matrix[i][j+1], matrix[i+1][j]) } } } return matrix } func backtrack(_ matrix: [[Int]]) -> String { var i = self.count var j = other.count var charInSequence = self.endIndex var lcs = String() while i >= 1 && j >= 1 { if matrix[i][j] == matrix[i][j - 1] { j -= 1 } else if matrix[i][j] == matrix[i - 1][j] { i -= 1 charInSequence = self.index(before: charInSequence) } else { i -= 1 j -= 1 charInSequence = self.index(before: charInSequence) lcs.append(self[charInSequence]) } } return String(lcs.reversed()) } return backtrack(lcsLength(other)) } } // Examples let a = "ABCBX" let b = "ABDCAB" let c = "KLMK" a.longestCommonSubsequence(c) // "" a.longestCommonSubsequence("") // "" a.longestCommonSubsequence(b) // "ABCB" b.longestCommonSubsequence(a) // "ABCB" a.longestCommonSubsequence(a) // "ABCBX" "Hello World".longestCommonSubsequence("Bonjour le monde")
mit
dba137e6a01028dc737625ed161e4728
24.888889
101
0.553648
3.268537
false
false
false
false
tardieu/swift
test/SILGen/coverage_smoke.swift
3
2725
// RUN: rm -rf %t && mkdir -p %t // RUN: %target-build-swift %s -profile-generate -profile-coverage-mapping -Xfrontend -disable-incremental-llvm-codegen -o %t/main // RUN: env LLVM_PROFILE_FILE=%t/default.profraw %target-run %t/main // RUN: %llvm-profdata merge %t/default.profraw -o %t/default.profdata // RUN: %llvm-profdata show %t/default.profdata -function=f_internal | %FileCheck %s --check-prefix=CHECK-INTERNAL // RUN: %llvm-profdata show %t/default.profdata -function=f_private | %FileCheck %s --check-prefix=CHECK-PRIVATE // RUN: %llvm-profdata show %t/default.profdata -function=f_public | %FileCheck %s --check-prefix=CHECK-PUBLIC // RUN: %llvm-profdata show %t/default.profdata -function=main | %FileCheck %s --check-prefix=CHECK-MAIN // RUN: %llvm-cov show %t/main -instr-profile=%t/default.profdata | %FileCheck %s --check-prefix=CHECK-COV // RUN: rm -rf %t // REQUIRES: profile_runtime // REQUIRES: OS=macosx // REQUIRES: rdar28221303 // CHECK-INTERNAL: Functions shown: 1 // CHECK-COV: {{ *}}[[@LINE+1]]|{{ *}}1{{.*}}func f_internal internal func f_internal() {} // CHECK-PRIVATE: Functions shown: 1 // CHECK-COV: {{ *}}[[@LINE+1]]|{{ *}}1{{.*}}func f_private private func f_private() { f_internal() } // CHECK-PUBLIC: Functions shown: 1 // CHECK-COV: {{ *}}[[@LINE+1]]|{{ *}}1{{.*}}func f_public public func f_public() { f_private() } class Class1 { var Field1 = 0 // CHECK-COV: {{ *}}[[@LINE+1]]|{{ *}}1{{.*}}init init() {} // CHECK-COV: {{ *}}[[@LINE+1]]|{{ *}}1{{.*}}deinit deinit {} } // CHECK-MAIN: Maximum function count: 1 func main() { // CHECK-COV: {{ *}}[[@LINE+1]]|{{ *}}1{{.*}}f_public f_public() // CHECK-COV: {{ *}}[[@LINE+1]]|{{ *}}1{{.*}}if (true) if (true) {} var x : Int32 = 0 while (x < 10) { // CHECK-COV: {{ *}}[[@LINE+1]]|{{ *}}10{{.*}}x += 1 x += 1 } // CHECK-COV: {{ *}}[[@LINE+1]]|{{ *}}1{{.*}}Class1 let _ = Class1() } // rdar://problem/22761498 - enum declaration suppresses coverage func foo() { var x : Int32 = 0 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 enum ETy { case A } // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 repeat { // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 x += 1 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 } while x == 0 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 x += 1 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 } // rdar://problem/27874041 - top level code decls get no coverage var g1 : Int32 = 0 // CHECK-COV: {{ *}}[[@LINE]]| repeat { // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 g1 += 1 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 } while g1 == 0 // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 main() // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1 foo() // CHECK-COV: {{ *}}[[@LINE]]|{{ *}}1
apache-2.0
a902acb2ceda527ed12beaff6514351a
36.328767
130
0.545321
3.153935
false
false
false
false
brentdax/swift
test/SILOptimizer/cast_folding.swift
6
28808
// RUN: %target-swift-frontend -O -emit-sil %s | %FileCheck %s // We want to check two things here: // - Correctness // - That certain "is" checks are eliminated based on static analysis at compile-time // // In ideal world, all those testNN functions should be simplified down to a single basic block // which returns either true or false, i.e. all type checks should folded statically. public protocol P {} public protocol R {} protocol Q: P {} class A: P {} class AA: A {} class X {} class B: P {} private struct S: P {} struct T: Q {} private struct U {} public protocol CP1: class {} public protocol CP2: class {} // Class D implements only one of class protocols // and it cannot be extended elsewhere as it is private private class D: CP1 {} private final class F: CP1 {} // Class E implements both class protocols at once class E: CP1, CP2 {} func cast0<T>(_ a: T) -> Bool { // Succeeds if T is A return type(of: A()) is T.Type } func cast1<T>(_ a: T) -> Bool { // Succeeds if T is A return type(of: (A() as AnyObject)) is T.Type } func cast2<T>(_ a: T) -> Bool { // Succeeds if T is A let ao: AnyObject = A() as AnyObject return type(of: ao) is T.Type } func cast3(_ p: AnyObject) -> Bool { // Always fails return type(of: p) is AnyObject.Protocol } func cast4(_ p: AnyObject) -> Bool { return type(of: p) is A.Type } func cast5(_ t: AnyObject.Type) -> Bool { // Succeeds if t is B.self return t is B.Type } func cast6<T>(_ t: T) -> Bool { // Always fails return AnyObject.self is T.Type } func cast7<T>(_ t: T.Type) -> Bool { // Succeeds if t is AnyObject.self return t is AnyObject.Protocol } func cast8<T>(_ a: T) -> Bool { // Succeeds if T is A return type(of: (A() as P)) is T.Type } func cast9<T>(_ a: T) -> Bool { // Succeeds if T is A let ao: P = A() as P return type(of: ao) is T.Type } func cast10(_ p: P) -> Bool { return type(of: p) is P.Protocol } func cast11(_ p: P) -> Bool { // Succeeds if p is of type A return type(of: p) is A.Type } func cast12(_ t: P.Type) -> Bool { return t is B.Type } func cast13<T>(_ t: T) -> Bool { // Succeeds if T is P return P.self is T.Type } func cast14<T>(_ t: T.Type) -> Bool { // Succeeds if p is P.self return t is P.Protocol } func cast15<T>(_ t: T) -> Bool { // Succeeds if T is P return P.self is T.Type } func cast16<T>(_ t: T) -> Bool { // Succeeds if T is P return T.self is P.Protocol } func cast17<T>(_ t: T) -> Bool { // Succeeds if T is AnyObject return AnyObject.self is T.Type } func cast18<T>(_ t: T) -> Bool { // Succeeds if T is AnyObject return T.self is AnyObject.Protocol } func cast20<T>(_ t: T) -> Bool { // Succeeds if T is P return T.self is P.Type } func cast21<T>(_ t: T) -> Bool { // Succeeds if T is P return T.self is P.Protocol } func cast22(_ existential: P.Type) -> Bool { // Succeeds if existential is S.self return existential is S.Type } func cast23(_ concrete: P.Protocol) -> Bool { // Always fails return concrete is S.Type } func cast24(_ existential: P.Type) -> Bool { // Succeeds if existential is Q.self return existential is Q.Type } func cast25(_ concrete: P.Protocol) -> Bool { // Always fails, because P != Q return concrete is Q.Type } func cast26(_ existential: Q.Type) -> Bool { // Succeeds always, because Q: P return existential is P.Type } func cast27(_ existential: CP1.Type) -> Bool { // Fails always, because existential is a class // and it cannot be struct return existential is S.Type } func cast28(_ existential: CP1.Type) -> Bool { // Succeeds if existential conforms to CP1 and CP2 return existential is CP2.Type } func cast29(_ o: Any) -> Bool { // Succeeds if o is P.Type return o is P.Type } func cast30(_ o: AnyObject) -> Bool { // Succeeds if o is P.Type return o is P.Type } func cast32(_ p: P) -> Bool { // Fails always, because a metatype cannot conform to a protocol return p is P.Type } func cast33(_ p: P) -> Bool { // Same as above, but non-existential metatype return p is X.Type } func cast38<T>(_ t: T) -> Bool { return t is (Int, Int) } func cast39<T>(_ t: T) -> Bool { return t is (x: Int, y: Int) } func cast40<T>(_ t: T) -> Bool { return t is (x: Int, y: A) } func cast41<T>(_ t: T, _ mt: T.Type) -> Bool { let typ = type(of: t as Any) return typ is AnyClass } func cast42(_ p: P) -> Bool { return type(of: p as Any) is AnyClass } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding5test0SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test0() -> Bool { return cast0(A()) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding5test1SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test1() -> Bool { return cast1(A()) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding5test2SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test2() -> Bool { return cast2(A()) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding5test3SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test3() -> Bool { return cast3(A()) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding5test4SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test4() -> Bool { return cast4(A()) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding7test5_1SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test5_1() -> Bool { return cast5(B.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding7test5_2SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test5_2() -> Bool { return cast5(AnyObject.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding7test6_1SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test6_1() -> Bool { return cast6(B.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding7test6_2SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test6_2() -> Bool { return cast6(AnyObject.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding7test7_1SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test7_1() -> Bool { return cast7(B.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding7test7_2SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test7_2() -> Bool { return cast7(AnyObject.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding5test8SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test8() -> Bool { return cast8(A()) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding5test9SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test9() -> Bool { return cast9(A()) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding6test10SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test10() -> Bool { return cast10(A()) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding6test11SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test11() -> Bool { return cast11(A()) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding6test12SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test12() -> Bool { return cast12(A.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test13_1SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test13_1() -> Bool { return cast13(A.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test13_2SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test13_2() -> Bool { return cast13(P.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test13_3SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test13_3() -> Bool { return cast13(A() as P) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test14_1SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test14_1() -> Bool { return cast14(A.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test14_2SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test14_2() -> Bool { return cast14(P.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test15_1SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test15_1() -> Bool { return cast15(A()) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test15_2SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test15_2() -> Bool { return cast15(A() as P) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test16_1SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test16_1() -> Bool { return cast16(A()) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test16_2SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test16_2() -> Bool { return cast16(A() as P) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test17_1SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test17_1() -> Bool { return cast17(A()) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test17_2SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test17_2() -> Bool { return cast17(A() as AnyObject) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test18_1SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test18_1() -> Bool { return cast18(A()) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test18_2SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test18_2() -> Bool { return cast18(A() as AnyObject) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding6test19SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test19() -> Bool { let t: Any.Type = type(of: 1 as Any) return t is Int.Type } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test20_1SbyF : $@convention(thin) () -> Bool @inline(never) func test20_1() -> Bool { return cast20(S.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test20_2SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test20_2() -> Bool { return cast20(U()) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test21_1SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test21_1() -> Bool { return cast21(S.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test21_2SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test21_2() -> Bool { return cast21(A() as P) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test22_1SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test22_1() -> Bool { return cast22(T.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test22_2SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test22_2() -> Bool { return cast22(S.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding6test23SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test23() -> Bool { return cast23(P.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test24_1SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test24_1() -> Bool { return cast24(T.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test24_2SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test24_2() -> Bool { return cast24(S.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding6test25SbyF : $@convention(thin) () -> Bool // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test25() -> Bool { return cast25(P.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding6test26SbyF // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test26() -> Bool { return cast26(T.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding6test27SbyF // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test27() -> Bool { return cast27(D.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test28_1SbyF // CHECK: checked_cast // CHECK: return @inline(never) func test28_1() -> Bool { return cast28(D.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test28_2SbyF // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test28_2() -> Bool { return cast28(E.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding8test28_3SbyF // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) func test28_3() -> Bool { return cast28(F.self) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding6test29SbyF // CHECK: bb0 // CHECK: checked_cast // CHECK: return @inline(never) func test29() -> Bool { return cast29(X()) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding6test30SbyF // CHECK: bb0 // CHECK: checked_cast // CHECK: return @inline(never) func test30() -> Bool { return cast30(X()) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding6test32SbyF // CHECK: bb0 // CHECK: checked_cast // CHECK: return @inline(never) func test32() -> Bool { // We don't actually fold this right now, but at least make sure it // doesn't crash return cast32(A()) } // CHECK-LABEL: sil hidden [noinline] @$s12cast_folding6test33SbyF // CHECK: bb0 // CHECK: checked_cast // CHECK: return @inline(never) func test33() -> Bool { // Ditto... return cast33(A()) } protocol PP { func foo() -> Int } public class CC : PP { func foo() -> Int { return 0 } } public class DD : PP { func foo() -> Int { return 1 } } // Check that the body of the function // contains a trap followed by unreachable // and no code afterwards. // CHECK-LABEL: sil @$s12cast_folding7getAsDDyAA0E0CAA2CCCF // CHECK: builtin "int_trap" // CHECK-NEXT: unreachable // CHECK-NEXT: } public func getAsDD(_ c: CC) -> DD { return c as! DD } // Check that the body of the function // contains a trap followed by unreachable // and no code afterwards. // CHECK-LABEL: sil @$s12cast_folding7callFooySiAA2CCCF // CHECK: builtin "int_trap" // CHECK-NEXT: unreachable // CHECK-NEXT: } public func callFoo(_ c: CC) -> Int { return (c as! DD).foo() } @inline(never) func callFooGeneric<T : PP>(_ c: T) -> Int { return (c as! DD).foo() } // Check that the inlined version of callFooGeneric contains only a trap // followed by unreachable and no code afterwards // CHECK-LABEL: sil [noinline] @$s12cast_folding16callForGenericCCyyAA0F0CF // CHECK: builtin "int_trap" // CHECK-NEXT: unreachable // CHECK-NEXT: } @inline(never) public func callForGenericCC(_ c: CC) { callFoo(c) } // Check that this conversion does not crash a compiler. @inline(never) public func test34() { if let _ = A.self as? P { print("A: dice") } else { print("A: no dice") } } // Check that this conversion does not crash a compiler. @inline(never) public func test35() { if let _ = X.self as? P { print("X: dice") } else { print("X: no dice") } } // Check that we do not eliminate casts from AnyHashable to a type that // implements Hashable. // CHECK-LABEL: sil [noinline] @$s12cast_folding6test36{{[_0-9a-zA-Z]*}}F // CHECK: checked_cast_addr_br take_always AnyHashable in {{.*}} to Int @inline(never) public func test36(ah: AnyHashable) { if let _ = ah as? Int { print("success") } else { print("failure") } } // Check that we do not eliminate casts to AnyHashable from an opaque type // that might implement Hashable. // CHECK-LABEL: sil [noinline] @$s12cast_folding6test37{{[_0-9a-zA-Z]*}}F // CHECK: checked_cast_addr_br take_always T in {{.*}} to AnyHashable @inline(never) public func test37<T>(ah: T) { if let _ = ah as? AnyHashable { print("success") } else { print("failure") } } // CHECK-LABEL: sil [noinline] @$s12cast_folding7test38a{{[_0-9a-zA-Z]*}}F // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) public func test38a() -> Bool { return cast38((1, 2)) } // CHECK-LABEL: sil [noinline] @$s12cast_folding7test38b{{[_0-9a-zA-Z]*}}F // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) public func test38b() -> Bool { return cast38((x: 1, y: 2)) } // CHECK-LABEL: sil [noinline] @$s12cast_folding7test38c{{[_0-9a-zA-Z]*}}F // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) public func test38c() -> Bool { return cast38((z: 1, y: 2)) } // CHECK-LABEL: sil [noinline] @$s12cast_folding7test39a{{[_0-9a-zA-Z]*}}F // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) public func test39a() -> Bool { return cast39((1, 2)) } // CHECK-LABEL: sil [noinline] @$s12cast_folding7test39b{{[_0-9a-zA-Z]*}}F // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) public func test39b() -> Bool { return cast39((x: 1, y: 2)) } // CHECK-LABEL: sil [noinline] @$s12cast_folding7test39c{{[_0-9a-zA-Z]*}}F // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) public func test39c() -> Bool { return cast39((z: 1, y: 2)) } // CHECK-LABEL: sil [noinline] @$s12cast_folding7test39d{{[_0-9a-zA-Z]*}}F // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) public func test39d() -> Bool { return cast39((1, 2, 3)) } // CHECK-LABEL: sil [noinline] @$s12cast_folding7test40a{{[_0-9a-zA-Z]*}}F // CHECK: bb0 // FIXME: Would love to fold this to just "true" // CHECK-NOT: return: // CHECK: unconditional_checked_cast_addr @inline(never) public func test40a() -> Bool { return cast40((1, A())) } // CHECK-LABEL: sil [noinline] @$s12cast_folding7test40b{{[_0-9a-zA-Z]*}}F // CHECK: bb0 // FIXME: Would love to fold this to just "true" // CHECK-NOT: return: // CHECK: unconditional_checked_cast_addr @inline(never) public func test40b() -> Bool { return cast40((1, AA())) } // CHECK-LABEL: sil [noinline] @$s12cast_folding7test40c{{[_0-9a-zA-Z]*}}F // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) public func test40c() -> Bool { return cast40((1, S())) } // CHECK-LABEL: sil [noinline] @$s12cast_folding7test40d{{[_0-9a-zA-Z]*}}F // CHECK: bb0 // CHECK-NOT: return // CHECK: checked_cast_addr_br take_always (Int, Any) in @inline(never) public func test40d(_ a: Any) -> Bool { return cast40((1, a)) } // CHECK-LABEL: sil [noinline] @$s12cast_folding6test41SbyF // CHECK: bb0 // FIXME: Would love to fold this to just "true" // CHECK-NOT: return: // CHECK: checked_cast_br // CHECK: //{{.*}}$s12cast_folding6test41{{.*}}F @inline(never) public func test41() -> Bool { return cast41(A(), P.self) } // CHECK-LABEL: sil [noinline] @$s12cast_folding6test42{{.*}}F // CHECK: bb0 // CHECK-NOT: return: // CHECK: checked_cast // CHECK: //{{.*}}$s12cast_folding6test42{{.*}}F @inline(never) public func test42(_ p: P) -> Bool { return cast42(p) } // CHECK-LABEL: sil [noinline] @{{.*}}test43{{.*}} // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) public func test43() -> Bool { return P.self is Any.Type } // CHECK-LABEL: sil [noinline] @{{.*}}test44{{.*}} // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) public func test44() -> Bool { return Any.self is Any.Type } // CHECK-LABEL: sil [noinline] @{{.*}}test45{{.*}} // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) public func test45() -> Bool { return (P & R).self is Any.Type } // CHECK-LABEL: sil [noinline] @{{.*}}test46{{.*}} // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) public func test46() -> Bool { return AnyObject.self is Any.Type } // CHECK-LABEL: sil [noinline] @{{.*}}test47{{.*}} // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) public func test47() -> Bool { return Any.Type.self is Any.Type } // CHECK-LABEL: sil [noinline] @{{.*}}test48{{.*}} // CHECK: bb0 // CHECK-NEXT: %0 = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: %1 = struct $Bool // CHECK-NEXT: return %1 @inline(never) public func test48() -> Bool { return Any.Type.self is Any.Type.Type } func cast<U, V>(_ u: U.Type) -> V? { return u as? V } // CHECK-LABEL: sil [noinline] @{{.*}}testCastAnyObjectProtocolTo{{.*}}Type // CHECK: %0 = enum $Optional{{.*}}, #Optional.none!enumelt // CHECK-NEXT: return %0 @inline(never) public func testCastAnyObjectProtocolToAnyObjectType() -> AnyObject.Type? { return cast(AnyObject.self) } // CHECK-LABEL: // testCastProtocolTypeProtocolToProtocolTypeType // CHECK: sil [noinline] @{{.*}}testCastProtocol{{.*}}$@convention(thin) () -> Optional<@thick P.Type.Type> // CHECK: %0 = enum $Optional{{.*}}, #Optional.none!enumelt // CHECK-NEXT: return %0 @inline(never) public func testCastProtocolTypeProtocolToProtocolTypeType() -> P.Type.Type? { return P.Type.self as? P.Type.Type } protocol PForOptional { } extension Optional: PForOptional { } func testCastToPForOptional<T>(_ t: T) -> Bool { if let _ = t as? PForOptional { return true } return false } // CHECK-LABEL: // testCastToPForOptionalSuccess() // CHECK: [[RES:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK: [[RET:%.*]] = struct $Bool ([[RES]] : $Builtin.Int1) // CHECK: return [[RET]] : $Bool @inline(never) public func testCastToPForOptionalSuccess() -> Bool { let t: Int? = 42 return testCastToPForOptional(t) } // CHECK-LABEL: // testCastToPForOptionalFailure() // CHECK: [[RES:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK: [[RET:%.*]] = struct $Bool ([[RES]] : $Builtin.Int1) // CHECK: return [[RET]] : $Bool @inline(never) public func testCastToPForOptionalFailure() -> Bool { let t: Int = 42 return testCastToPForOptional(t) } print("test0=\(test0())") print("test1=\(test1())") print("test2=\(test2())") print("test3=\(test3())") print("test4=\(test4())") print("test5_1=\(test5_1())") print("test5_2=\(test5_2())") print("test6_1=\(test6_1())") print("test6_2=\(test6_2())") print("test7_1=\(test7_1())") print("test7_2=\(test7_2())") print("test8=\(test8())") print("test9=\(test9())") print("test10=\(test10())") print("test11=\(test11())") print("test12=\(test12())") print("test13_1=\(test13_1())") print("test13_2=\(test13_2())") print("test13_3=\(test13_3())") print("test14_1=\(test14_1())") print("test14_2=\(test14_2())") print("test15_1=\(test15_1())") print("test15_2=\(test15_2())") print("test16_1=\(test16_1())") print("test16_2=\(test16_2())") print("test17_1=\(test17_1())") print("test17_2=\(test17_2())") print("test18_1=\(test18_1())") print("test18_2=\(test18_2())") print("test19=\(test19())") print("test20_1=\(test20_1())") print("test20_2=\(test20_2())") print("test21_1=\(test21_1())") print("test21_2=\(test21_2())") print("test22_1=\(test22_1())") print("test22_2=\(test22_2())") print("test23=\(test23())") print("test24_1=\(test24_1())") print("test24_2=\(test24_2())") print("test25=\(test25())") print("test26=\(test26())") print("test27=\(test27())") print("test28_1=\(test28_1())") print("test28_2=\(test28_2())") print("test28_3=\(test28_3))") print("test29=\(test29())") print("test30=\(test30())") print("test32=\(test32())") print("test33=\(test33())")
apache-2.0
173b9a4750d616419f69e391267f8497
23.70669
107
0.644751
2.850302
false
true
false
false
LamGiauKhongKhoTeam/LGKK
Modules/Extensions/UIWindow+MTExtension.swift
1
1658
// // UIWindow+MTExtension.swift // MobileTrading // // Created by Nguyen Minh on 4/8/17. // Copyright © 2017 AHDEnglish. All rights reserved. // import UIKit extension UIWindow { public func sp_set(rootViewController newRootVC: UIViewController, withTransition transition: CATransition? = nil) { let previousViewController = rootViewController if let transition = transition { // Add the transition layer.add(transition, forKey: kCATransition) } rootViewController = newRootVC // Update status bar appearance using the new view controllers appearance - animate if needed if UIView.areAnimationsEnabled { UIView.animate(withDuration: CATransaction.animationDuration()) { newRootVC.setNeedsStatusBarAppearanceUpdate() } } else { newRootVC.setNeedsStatusBarAppearanceUpdate() } /// The presenting view controllers view doesn't get removed from the window as its currently transistioning and presenting a view controller if let transitionViewClass = NSClassFromString("UITransitionView") { for subview in subviews where subview.isKind(of: transitionViewClass) { subview.removeFromSuperview() } } if let previousViewController = previousViewController { // Allow the view controller to be deallocated previousViewController.dismiss(animated: false) { // Remove the root view in case its still showing previousViewController.view.removeFromSuperview() } } } }
mit
ba0c329b6509021f65cdf34fa7ff413c
39.414634
149
0.659022
5.834507
false
false
false
false
galv/reddift
reddiftSample/SubredditsListViewController.swift
1
2303
// // SubredditsListViewController.swift // reddift // // Created by sonson on 2015/04/16. // Copyright (c) 2015年 sonson. All rights reserved. // import Foundation import reddift class SubredditsListViewController: UITableViewController { var session:Session? = nil var subreddits:[Subreddit] = [] var paginator:Paginator? = nil override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { if self.subreddits.count == 0 { session?.getUserRelatedSubreddit(.Subscriber, paginator:paginator, completion: { (result) -> Void in switch result { case .Failure: print(result.error) case .Success(let listing): self.subreddits += listing.children.flatMap({$0 as? Subreddit}) self.paginator = listing.paginator dispatch_async(dispatch_get_main_queue(), { () -> Void in self.tableView.reloadData() }) } }) } } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return subreddits.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell if subreddits.indices ~= indexPath.row { let link = subreddits[indexPath.row] cell.textLabel?.text = link.title } return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ToSubredditsViewController" { if let con = segue.destinationViewController as? LinkViewController { con.session = self.session if let indexPath = self.tableView.indexPathForSelectedRow { if subreddits.indices ~= indexPath.row { con.subreddit = subreddits[indexPath.row] } } } } } }
mit
6659fb00767cbc3bb660c3cdd396e7c1
32.347826
118
0.599739
5.289655
false
false
false
false
TotalDigital/People-iOS
People at Total/ViewController.swift
1
18369
// // ViewController.swift // People at Total // // Created by Florian Letellier on 31/01/2017. // Copyright © 2017 Florian Letellier. All rights reserved. // import UIKit import SwiftyJSON import p2_OAuth2 import Alamofire extension NSMutableAttributedString { func bold(_ text:String) -> NSMutableAttributedString { let attrs:[String:AnyObject] = [NSFontAttributeName : UIFont(name: "HelveticaNeue-bold", size: 32)!] let boldString = NSMutableAttributedString(string:"\(text)", attributes:attrs) self.append(boldString) return self } func normal(_ text:String)->NSMutableAttributedString { let attrs:[String:AnyObject] = [NSFontAttributeName : UIFont(name: "HelveticaNeue", size: 32)!] let normal = NSAttributedString(string: "\(text)", attributes :attrs) self.append(normal) return self } func color(_ text: String, _ color: UIColor)->NSMutableAttributedString { let attrs:[String:AnyObject] = [NSForegroundColorAttributeName : color] let coloredString = NSMutableAttributedString(string:"\(text)", attributes:attrs) self.append(coloredString) return self } } extension UIViewController { func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard)) view.addGestureRecognizer(tap) } func dismissKeyboard() { view.endEditing(true) } } class ViewController: UIViewController { @IBOutlet weak var signinButton: UIButton! @IBOutlet weak var sentenceLabel: UILabel! fileprivate var alamofireManager: SessionManager? @IBOutlet weak var logo: UIImageView! var profiles: [Profile] = [] var loader: OAuth2DataLoader? var token: String = "" var isProd: Bool? @IBOutlet weak var privacyTerms: UILabel! var oauth2: OAuth2CodeGrant? @IBOutlet var signInEmbeddedButton: UIButton? override func viewDidLoad() { super.viewDidLoad() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { print("coucou segue : \((segue.identifier)!)") if((segue.identifier)! == "signIn"){ print("token segue : \(self.token)") let barViewControllers = segue.destination as! UITabBarController let nav = barViewControllers.viewControllers![0] as! UINavigationController let destinationViewController = nav.viewControllers[0] as! searchViewController let secondViewController = barViewControllers.viewControllers![1] as! myProfileViewController destinationViewController.access_token = self.token secondViewController.access_token = self.token } } @IBAction func signInSafari(_ sender: UIButton?) { if (APIUtility.sharedInstance.isProd == true) { oauth2 = OAuth2CodeGrant(settings: [ "client_id": "be038752db66a64a42fd515df59c6120977c6721ba0c5eb8ce6e85651c05c150", // yes, this client-id and secret will work! "client_secret": "e3578569e862b503b684dfde864adcae947deee07eee1e2dd6e75f931564a31e", "authorize_uri": "https://people.total.com/oauth/authorize", "token_uri": "https://people.total/oauth/token", "redirect_uris": ["peopleauthapp://oauth/callback"], // app has registered this scheme "secret_in_body": true, // GitHub does not accept client secret in the Authorization header "verbose": true ] as OAuth2JSON) } else { oauth2 = OAuth2CodeGrant(settings: [ "client_id": "b4fe2d0ac24446c37b9ff5085ab43f9f4053ae97f06a283dfa91b875d3c29a7c", // yes, this client-id and secret will work! "client_secret": "9a7d51a35992e06b27b158d348feaa3e5692124388a81f576365aa090edbcdb5", "authorize_uri": "https://people-total-staging.herokuapp.com/oauth/authorize", "token_uri": "https://people-total-staging.herokuapp.com/oauth/token", "redirect_uris": ["peopleauthapp://oauth/callback"], // app has registered this scheme "secret_in_body": true, // GitHub does not accept client secret in the Authorization header "verbose": true ] as OAuth2JSON) } if (oauth2?.isAuthorizing)! { oauth2?.abortAuthorization() return } oauth2?.forgetTokens() sender?.setTitle("Authorizing...", for: UIControlState.normal) oauth2?.logger = OAuth2DebugLogger(.trace) oauth2?.authConfig.authorizeEmbedded = true // the default oauth2?.authConfig.ui.useSafariView = false oauth2?.authConfig.authorizeContext = self // oauth2.authorize() { authParameters, error in // if let params = authParameters { // print("Authorized! Access token is in `oauth2.accessToken`") // print("Authorized! Additional parameters: \(params)") // } // else { // print("Authorization was cancelled or went wrong: \(error)") // error will not be nil // } // } let loader = OAuth2DataLoader(oauth2: oauth2!) self.loader = loader print("token : \(String(describing: oauth2?.accessToken))") // if oauth2.accessToken != nil { // self.token = oauth2.accessToken! // self.performSegue(withIdentifier: "signIn", sender: nil) // } loader.perform(request: userDataRequest) { response in do { DispatchQueue.main.async { if self.oauth2?.accessToken != nil { // Store accessToken Locally let defaults = UserDefaults.standard defaults.set(self.oauth2?.accessToken, forKey: "accessToken") let mainStoryboard: UIStoryboard = UIStoryboard(name: "Storyboard", bundle: nil) let viewController = mainStoryboard.instantiateViewController(withIdentifier: "tabBarcontroller") as! UITabBarController let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.window?.rootViewController = viewController appDelegate.window?.makeKeyAndVisible() } else { sender?.setTitle("Sign in", for: UIControlState.normal) } } print("sigin in safari") //let json = try response.responseJSON() //dump("jsons : \(json)") //self.didGetUserdata(json: json, loader: loader) } catch let error { //self.didCancelOrFail(error) } } } var userDataRequest: URLRequest { print("isProd : \(self.isProd)") if self.isProd == true { var request = URLRequest(url: URL(string: "https://people.total/api/v1/users")!) return request } else { var request = URLRequest(url: URL(string: "https://people-total-staging.herokuapp.com/api/v1/users")!) return request } //request.setValue("application/vnd.github.v3+json", forHTTPHeaderField: "Accept") } /*func didGetUserdata(json: [String: Any], loader: OAuth2DataLoader?) { DispatchQueue.main.async { var users: [User] for i in 0..<json.count { //Do something you want var projects: [Project] = [] var jobs: [Job] = [] var user = User() if let first_name = json[i]["first_name"].stringValue as? String, let last_name = json[i]["last_name"].stringValue as? String { user.first_name = first_name user.last_name = last_name } if let job = json[i]["job_title"].stringValue as? String { user.job = "\(job)" } if let location = json[i]["office_address"].stringValue as? String { user.location = "\(location)" } if var image = json[i]["picture_url"].stringValue as? String { if image == "http://placehold.it/180x180" { image = "https://placeholdit.imgix.net/~text?txtsize=17&txt=180%C3%97180&w=180&h=180" } user.image = image //print("image : \(image)") } if let entity = json[i]["entity"].stringValue as? String { user.entities = "\(entity)" } var skill = Skill() for j in 0..<json[i]["skills"].count { //print("s : \(json[i]["skills"][j]["name"].stringValue)") if let s = json[i]["skills"][j]["name"].stringValue as? String { skill.skills.append(s) } } //print("skills : \(skill.skills)") var language = Language() for j in 0..<json[i]["languages"].count { if let l = json[i]["languages"][j]["name"].stringValue as? String { language.langues.append(l) } } var relations = Relation() for j in 0..<json[i]["relationships"].count { if let relation = (json[i]["relationships"][j].dictionaryValue) as? Dictionary{ //let id = relation["target"]?["user_id"].int var profile = Profile() var user = User() user.first_name = relation["target"]?["first_name"].stringValue user.last_name = relation["target"]?["last_name"].stringValue user.image = relation["target"]?["picture_url"].stringValue user.job = relation["target"]?["job_title"].stringValue profile.user = user switch ((relation["kind"]?.stringValue)!) { case "is_manager_of": print("kind : \((relation["kind"]?.stringValue)!)") relations.teamMembers_profile.append(profile) case "is_managed_by": relations.managers_profile.append(profile) case "is_colleague_of": relations.colleagues_profile.append(profile) case "is_assisted_by": relations.assistants_profile.append(profile) default: break } } } dump("relations : \(relations)") for j in 0..<json[i]["projects"].count { var project = Project() let proj = (json[i]["projects"][j]) //dump("proj : \(proj["id"])") // project = self.projects.first {$0.id! == proj["id"].intValue}! project.title = proj["name"].stringValue project.location = proj["location"].stringValue project.description = proj["project_participations"][0]["role_description"].stringValue project.id = proj["id"].intValue project.start_date = proj["project_participations"][0]["start_date"].stringValue project.end_date = proj["project_participations"][0]["end_date"].stringValue project.participation_id = proj["project_participations"][0]["id"].intValue //print("project.participation_id : \(project.participation_id)") for k in 0..<proj["project_participations"].count { let participants = proj["project_participations"].arrayValue print("k : \(k)") dump("participants : \(participants)") let participant = participants[k].dictionaryValue var profile = Profile() var user = User() profile.id = (participant["user_id"]?.intValue)! user.first_name = participant["user_first_name"]?.stringValue user.last_name = participant["user_last_name"]?.stringValue user.image = participant["user_picture_url"]?.stringValue profile.user = user project.members_profile.append(profile) } dump("project members : \(project.members_profile)") projects.append(project) } for j in 0..<json[i]["jobs"].count { var job = Job() if let j = (json[i]["jobs"][j].dictionaryValue) as? Dictionary { job.title = j["title"]?.stringValue job.location = j["location"]?.stringValue job.id = j["id"]?.intValue job.start_date = j["start_date"]?.stringValue job.end_date = j["end_date"]?.stringValue job.description = j["description"]?.stringValue jobs.append(job) } } var contact = Contact() if let email = json[i]["email"].stringValue as? String { contact.email = email } if let phone = json[i]["phone"].stringValue as? String { contact.phone_number = json[i]["phone"].stringValue } if let linkedin = json[i]["linkedin"].stringValue as? String { contact.linkedin_profile = linkedin } if let wat = json[i]["wat_link"].stringValue as? String { contact.wat_profile = wat } if let twitter = json[i]["twitter"].stringValue as? String { contact.twitter_profile = twitter } if let agil = json[i]["agil"].stringValue as? String { contact.agil_profile = agil } if let skype = json[i]["skype"].stringValue as? String { contact.skipe = skype } let profile = Profile() profile.user = user profile.jobs = jobs profile.contact = contact profile.projects = projects profile.langues = language profile.skills = skill profile.relations = relations //dump("relations : \(profile.relations)") if let id = json[i]["id"].intValue as? Int { profile.id = id print("id profile : \(profile.id)") } //dump(profile) self.profiles.append(profile) //defaults.set(self.profiles, forKey: "profiles") print("coucou") } } }*/ func didCancelOrFail(_ error: Error?) { DispatchQueue.main.async { if let error = error { print("Authorization went wrong: \(error)") } } } /* override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //DataGenerator.sharedInstance.getUser() oauth2.forgetTokens() let formattedString = NSMutableAttributedString() formattedString .normal("Already ") .bold("17281 colleagues ") .normal("in ") .bold("your ") .normal("network.") sentenceLabel.attributedText = formattedString navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) navigationController?.navigationBar.shadowImage = UIImage() navigationController?.navigationBar.isTranslucent = true signinButton.layer.cornerRadius = 2 signinButton.layer.borderWidth = 2 signinButton.layer.borderColor = UIColor.white.cgColor }*/ override func viewWillAppear(_ animated: Bool) { //super.viewWillAppear(animated) // Hide the navigation bar on the this view controller if APIUtility.sharedInstance.isProd == false { self.logo.image = UIImage() self.privacyTerms.isHidden = true } self.navigationController?.setNavigationBarHidden(true, animated: animated) navigationController?.setNavigationBarHidden(false, animated: true) navigationController?.navigationBar.tintColor = UIColor.white navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] //getData() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) let defaults: UserDefaults = UserDefaults.standard // Show the navigation bar on other view controllers self.navigationController?.setNavigationBarHidden(false, animated: animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
31796b8aa15835a522989cd3c3d2067c
42.218824
165
0.526949
5.236032
false
false
false
false
hooman/swift
test/decl/ext/generic.swift
5
4729
// RUN: %target-typecheck-verify-swift protocol P1 { associatedtype AssocType } protocol P2 : P1 { } protocol P3 { } struct X<T : P1, U : P2, V> { struct Inner<A, B : P3> { } struct NonGenericInner { } } extension Int : P1 { typealias AssocType = Int } extension Double : P2 { typealias AssocType = Double } extension X<Int, Double, String> { // expected-error@-1{{constrained extension must be declared on the unspecialized generic type 'X' with constraints specified by a 'where' clause}} let x = 0 // expected-error@-1 {{extensions must not contain stored properties}} static let x = 0 // expected-error@-1 {{static stored properties not supported in generic types}} func f() -> Int {} class C<T> {} } typealias GGG = X<Int, Double, String> extension GGG { } // okay through a typealias // Lvalue check when the archetypes are not the same. struct LValueCheck<T> { let x = 0 } extension LValueCheck { init(newY: Int) { x = 42 } } // Member type references into another extension. struct MemberTypeCheckA<T> { } protocol MemberTypeProto { associatedtype AssocType func foo(_ a: AssocType) init(_ assoc: MemberTypeCheckA<AssocType>) } struct MemberTypeCheckB<T> : MemberTypeProto { func foo(_ a: T) {} typealias Element = T var t1: T } extension MemberTypeCheckB { typealias Underlying = MemberTypeCheckA<T> } extension MemberTypeCheckB { init(_ x: Underlying) { } } extension MemberTypeCheckB { var t2: Element { return t1 } } // rdar://problem/19795284 extension Array { var pairs: [(Element, Element)] { get { return [] } } } // rdar://problem/21001937 struct GenericOverloads<T, U> { var t: T var u: U init(t: T, u: U) { self.t = t; self.u = u } func foo() { } var prop: Int { return 0 } subscript (i: Int) -> Int { return i } } extension GenericOverloads where T : P1, U : P2 { init(t: T, u: U) { self.t = t; self.u = u } func foo() { } var prop: Int { return 1 } subscript (i: Int) -> Int { return i } } extension Array where Element : Hashable { // expected-note {{where 'Element' = 'T'}} var worseHashEver: Int { var result = 0 for elt in self { result = (result << 1) ^ elt.hashValue } return result } } func notHashableArray<T>(_ x: [T]) { x.worseHashEver // expected-error{{property 'worseHashEver' requires that 'T' conform to 'Hashable'}} } func hashableArray<T : Hashable>(_ x: [T]) { // expected-warning @+1 {{unused}} x.worseHashEver // okay } func intArray(_ x: [Int]) { // expected-warning @+1 {{unused}} x.worseHashEver } class GenericClass<T> { } extension GenericClass where T : Equatable { // expected-note {{where 'T' = 'T'}} func foo(_ x: T, y: T) -> Bool { return x == y } } func genericClassEquatable<T : Equatable>(_ gc: GenericClass<T>, x: T, y: T) { _ = gc.foo(x, y: y) } func genericClassNotEquatable<T>(_ gc: GenericClass<T>, x: T, y: T) { gc.foo(x, y: y) // expected-error{{referencing instance method 'foo(_:y:)' on 'GenericClass' requires that 'T' conform to 'Equatable'}} } extension Array where Element == String { } extension GenericClass : P3 where T : P3 { } extension GenericClass where Self : P3 { } // expected-error@-1{{covariant 'Self' or 'Self?' can only appear as the type of a property, subscript or method result; did you mean 'GenericClass'?}} {{30-34=GenericClass}} // expected-error@-2{{'GenericClass<T>' in conformance requirement does not refer to a generic parameter or associated type}} protocol P4 { associatedtype T init(_: T) } protocol P5 { } struct S4<Q>: P4 { init(_: Q) { } } extension S4 where T : P5 {} struct S5<Q> { init(_: Q) { } } extension S5 : P4 {} // rdar://problem/21607421 public typealias Array2 = Array extension Array2 where QQQ : VVV {} // expected-error@-1 {{cannot find type 'QQQ' in scope}} // expected-error@-2 {{cannot find type 'VVV' in scope}} // https://bugs.swift.org/browse/SR-9009 func foo() { extension Array where Element : P1 { // expected-error@-1 {{declaration is only valid at file scope}} func foo() -> Element.AssocType {} } } // Deeply nested protocol P6 { associatedtype Assoc1 associatedtype Assoc2 } struct A<T, U, V> { struct B<W, X, Y> { struct C<Z: P6> { } } } extension A.B.C where T == V, X == Z.Assoc2 { func f() { } } // Extensions of nested non-generics within generics. extension A.B { struct D { } } extension A.B.D { func g() { } } // rdar://problem/43955962 struct OldGeneric<T> {} typealias NewGeneric<T> = OldGeneric<T> extension NewGeneric { static func oldMember() -> OldGeneric { return OldGeneric() } static func newMember() -> NewGeneric { return NewGeneric() } }
apache-2.0
c89e85e5050137ffb8189ba1f5e7244f
19.924779
174
0.647071
3.259132
false
false
false
false
lorentey/swift
test/ClangImporter/cf.swift
3
6011
// RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -typecheck -verify -import-cf-types -I %S/Inputs/custom-modules %s // REQUIRES: objc_interop import CoreCooling import CFAndObjC func assertUnmanaged<T>(_ t: Unmanaged<T>) {} func assertManaged<T: AnyObject>(_ t: T) {} func test0(_ fridge: CCRefrigerator) { assertManaged(fridge) } func test1(_ power: Unmanaged<CCPowerSupply>) { assertUnmanaged(power) let fridge = CCRefrigeratorCreate(power) // expected-error {{cannot convert value of type 'Unmanaged<CCPowerSupply>' to expected argument type 'CCPowerSupply?'}} assertUnmanaged(fridge) } func test2() { let fridge = CCRefrigeratorCreate(kCCPowerStandard)! assertUnmanaged(fridge) } func test3(_ fridge: CCRefrigerator) { assertManaged(fridge) } func test4() { // FIXME: this should not require a type annotation let power: CCPowerSupply = kCCPowerStandard assertManaged(power) let fridge = CCRefrigeratorCreate(power)! assertUnmanaged(fridge) } func test5() { let power: Unmanaged<CCPowerSupply> = .passUnretained(kCCPowerStandard) assertUnmanaged(power) _ = CCRefrigeratorCreate(power.takeUnretainedValue()) } func test6() { let fridge = CCRefrigeratorCreate(nil) fridge?.release() } func test7() { let value = CFBottom()! assertUnmanaged(value) } func test8(_ f: CCRefrigerator) { _ = f as CFTypeRef _ = f as AnyObject } func test9() { let fridge = CCRefrigeratorCreateMutable(kCCPowerStandard).takeRetainedValue() let constFridge: CCRefrigerator = fridge CCRefrigeratorOpen(fridge) let item = CCRefrigeratorGet(fridge, 0).takeUnretainedValue() // TODO(diagnostics): In this case we should probably suggest to flip `item` and `fridge` CCRefrigeratorInsert(item, fridge) // expected-error {{cannot convert value of type 'CCItem' to expected argument type 'CCMutableRefrigerator?'}} // expected-error@-1 {{cannot convert value of type 'CCMutableRefrigerator' to expected argument type 'CCItem?'}} CCRefrigeratorInsert(constFridge, item) // expected-error {{cannot convert value of type 'CCRefrigerator' to expected argument type 'CCMutableRefrigerator?'}} CCRefrigeratorInsert(fridge, item) CCRefrigeratorClose(fridge) } func testProperty(_ k: Kitchen) { k.fridge = CCRefrigeratorCreate(kCCPowerStandard).takeRetainedValue() CCRefrigeratorOpen(k.fridge) CCRefrigeratorClose(k.fridge) } func testTollFree0(_ mduct: MutableDuct) { _ = mduct as CCMutableDuct let duct = mduct as Duct _ = duct as CCDuct } func testTollFree1(_ ccmduct: CCMutableDuct) { _ = ccmduct as MutableDuct let ccduct: CCDuct = ccmduct _ = ccduct as Duct } func testChainedAliases(_ fridge: CCRefrigerator) { _ = fridge as CCRefrigerator _ = fridge as CCFridge _ = fridge as CCFridgeRef // expected-error{{'CCFridgeRef' has been renamed to 'CCFridge'}} {{17-28=CCFridge}} } func testBannedImported(_ object: CCOpaqueTypeRef) { CCRetain(object) // expected-error {{'CCRetain' is unavailable: Core Foundation objects are automatically memory managed}} expected-warning {{result of call to 'CCRetain' is unused}} CCRelease(object) // expected-error {{'CCRelease' is unavailable: Core Foundation objects are automatically memory managed}} CCMungeAndRetain(object) // okay, has a custom swift_name } func testOutParametersGood() { var fridge: CCRefrigerator? CCRefrigeratorCreateIndirect(&fridge) var power: CCPowerSupply? CCRefrigeratorGetPowerSupplyIndirect(fridge!, &power) var item: Unmanaged<CCItem>? CCRefrigeratorGetItemUnaudited(fridge!, 0, &item) } func testOutParametersBad() { let fridge: CCRefrigerator? CCRefrigeratorCreateIndirect(fridge) // expected-error {{cannot convert value of type 'CCRefrigerator?' to expected argument type 'UnsafeMutablePointer<CCRefrigerator?>?'}} let power: CCPowerSupply? CCRefrigeratorGetPowerSupplyIndirect(0, power) // expected-error {{cannot convert value of type 'Int' to expected argument type 'CCRefrigerator?'}} let item: CCItem? CCRefrigeratorGetItemUnaudited(0, 0, item) // expected-error {{cannot convert value of type 'Int' to expected argument type 'CCRefrigerator?'}} } func nameCollisions() { var objc: MyProblematicObject? var cf: MyProblematicObjectRef? cf = objc // expected-error {{cannot assign value of type 'MyProblematicObject?' to type 'MyProblematicObjectRef?'}} objc = cf // expected-error {{cannot assign value of type 'MyProblematicObjectRef?' to type 'MyProblematicObject?'}} var cfAlias: MyProblematicAliasRef? cfAlias = cf // okay cf = cfAlias // okay var otherAlias: MyProblematicAlias? otherAlias = cfAlias // expected-error {{cannot assign value of type 'MyProblematicAliasRef?' (aka 'Optional<MyProblematicObjectRef>') to type 'MyProblematicAlias?' (aka 'Optional<Float>')}} cfAlias = otherAlias // expected-error {{cannot assign value of type 'MyProblematicAlias?' (aka 'Optional<Float>') to type 'MyProblematicAliasRef?' (aka 'Optional<MyProblematicObjectRef>')}} func isOptionalFloat(_: inout Optional<Float>) {} isOptionalFloat(&otherAlias) // okay var np: NotAProblem? var np2: NotAProblemRef? // expected-error{{'NotAProblemRef' has been renamed to 'NotAProblem'}} {{12-26=NotAProblem}} np = np2 np2 = np } func testNonConstVoid() { let value: Unmanaged<CFNonConstVoidRef> = CFNonConstBottom()! assertUnmanaged(value) } class NuclearFridge: CCRefrigerator {} // expected-error {{cannot inherit from Core Foundation type 'CCRefrigerator'}} extension CCRefrigerator { @objc func foo() {} // expected-error {{method cannot be marked @objc because Core Foundation types are not classes in Objective-C}} func bar() {} // okay, implicitly non-objc } protocol SwiftProto {} @objc protocol ObjCProto {} extension CCRefrigerator: ObjCProto {} // expected-error {{Core Foundation class 'CCRefrigerator' cannot conform to @objc protocol 'ObjCProto' because Core Foundation types are not classes in Objective-C}} extension CCRefrigerator: SwiftProto {}
apache-2.0
abd57afb18d9de8ea92a67ca40931795
35.430303
205
0.75262
4.020736
false
true
false
false
googlearchive/friendlyping
ios/FriendlyPingSwift/ClientListDataSource.swift
1
2525
// // Copyright (c) 2015 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /** DataSource for the clients table */ class ClientListDataSource: NSObject, UITableViewDataSource { /** The registered clients */ var clients : Array<FriendlyPingClient> = [] /** Add a client */ func addClient(c:FriendlyPingClient) { clients.append(c) } /** Move a client to the top of the table */ func moveToTop(index:Int) { let newTopObject = clients[index] self.clients.removeAtIndex(index) self.clients.insert(newTopObject, atIndex: 0) } /** One section in the table */ func numberOfSectionsInTableView (tableView: UITableView) -> Int { return 1 } /** Number of rows in the table == number of clients */ func tableView(_tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.clients.count } /** Cells for clients */ func tableView (_tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = _tableView.dequeueReusableCellWithIdentifier("ClientCell") as UITableViewCell! let client = clients[indexPath.row] cell.textLabel?.text = client.name if let imageData = NSData (contentsOfURL: client.profilePictureUrl!) { cell.imageView!.image = UIImage (data: imageData) } return cell } } /** Extend sequence to iterate the list */ extension ClientListDataSource : SequenceType { typealias Generator = AnyGenerator<FriendlyPingClient> func generate() -> Generator { var index = 0 return anyGenerator { if index < self.clients.count { return self.clients[index++] } return nil } } } /** Extend collection for array like operations */ extension ClientListDataSource : CollectionType { typealias Index = Int var startIndex: Int { return 0 } var endIndex: Int { return clients.count } subscript(i: Int) -> FriendlyPingClient { return clients[i] } }
apache-2.0
bad017beacd80b354449572ad6b95641
27.055556
76
0.688317
4.353448
false
false
false
false
jayb967/twitter-client-clone-
TwitterClient/TwitterClient/API.swift
1
6173
// // API.swift // TwitterClient // // Created by Rio Balderas on 3/21/17. // Copyright © 2017 Jay Balderas. All rights reserved. // import Foundation import Accounts import Social typealias AccountCallback = (ACAccount?) -> () //giving a new name to another type typealias UserCallback = (User?) -> () typealias TweetsCallback = ([Tweet]?) ->() //enum Callback { // case Accounts(ACAccount?) // case User(User?) // case Tweets([Tweet]?) //} // //typealias babyGotBack = (Callback) -> () class API{ static let shared = API() var account : ACAccount? //telling variable what type it is, aka ACAccount private func login(callback: @escaping AccountCallback){//these are trailing closures, escaping the scope of function itself, used to asychronous calls , i.e. @escaping let accountStore = ACAccountStore() let accountType = accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter) accountStore.requestAccessToAccounts(with: accountType, options: nil) { (success, error) in if let error = error { print("Error: \(error.localizedDescription)") callback(nil) return } if success { //if no errors... if let account = accountStore.accounts(with: accountType).first as? ACAccount{ callback(account) } } else { print("The user did not allow access to this account") callback(nil) } } } private func getOAuthUser(callback: @escaping UserCallback){ let url = URL(string: "https://api.twitter.com/1.1/account/verify_credentials.json") if let request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .GET, url: url, parameters: nil) { request.account = self.account request.perform(handler: { (data, response, error) in if let error = error { print("Error: \(error)") callback(nil) //this callback needs an escaping thing by the callback return } guard let response = response else { callback(nil); return } guard let data = data else { callback(nil); return} switch response.statusCode { case 200...299: JSONParser.responseStatusCodes(data: data, callback: { (success, tweets) in if success { callback(tweets) } }) print("Everything is good with a \(response.statusCode)") case 400...499: print("Something is wrong with the app with a code \(response.statusCode)") return case 500...599: print("\(response.statusCode) there is a problem with a server") return default: print("Error response came back with statusCode: \(response.statusCode)") callback(nil) } }) // if let userJSON = try! JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any]{ // let user = User(json: userJSON) // print("Everything is good with a \(response.statusCode)") // callback(user) // // } //need to put in a do catch for this force unwrap, and move this JSON part in the JSON parser class }//need to import social framework } private func updateTimeline(url: String, callback: @escaping TweetsCallback){ // let url = URL(string: "") if let request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .GET, url: URL(string: url), parameters: nil) {//parameters are for the key value pairing in the url for the API its requesting from. request.account = self.account request.perform(handler: { (data, response, error) in if let error = error { print("Error: Error requesting user's home timeline - \(error.localizedDescription)") callback(nil) return } guard let response = response else { callback(nil); return } guard let data = data else { callback(nil); return } if response.statusCode >= 200 && response.statusCode <= 300 { JSONParser.tweetsFrom(data: data, callback: { (success, tweets) in if success { callback(tweets) } }) } else { print("Something else went wrong! We have a status code outside 200-299") callback(nil) } }) } } func getTweets(callback: @escaping TweetsCallback){ if self.account == nil { login(callback: { (account) in if let account = account { self.account = account self.updateTimeline(url: "https://api.twitter.com/1.1/statuses/home_timeline.json", callback: {(tweets) in callback(tweets) }) } }) } else { // self.updateTimeline(callback: callback) // this does the same thing as the one right below self.updateTimeline(url: "https://api.twitter.com/1.1/statuses/home_timeline.json", callback: { (tweets) in callback(tweets) }) } } func getTweetsFor(_ user: String, callback: @escaping TweetsCallback) { let urlString = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=\(user)" self.updateTimeline(url: urlString, callback: {(tweets) in callback(tweets) }) } func getUser(callback: @escaping UserCallback){ self.getOAuthUser{(aUser) in guard let userProfile = aUser else { fatalError("Could not access user profile")} callback(userProfile) } } }
mit
7ab63379951d3cfe53f936746cb49256
33.480447
219
0.558976
4.867508
false
false
false
false
kuruvilla6970/Zoot
Source/Web View/WebViewController.swift
1
21888
// // WebViewController.swift // THGHybridWeb // // Created by Angelo Di Paolo on 4/16/15. // Copyright (c) 2015 TheHolyGrail. All rights reserved. // import Foundation import JavaScriptCore import UIKit #if NOFRAMEWORKS #else import THGBridge #endif /** Defines methods that a delegate of a WebViewController object can optionally implement to interact with the web view's loading cycle. */ @objc public protocol WebViewControllerDelegate { /** Sent before the web view begins loading a frame. :param: webViewController The web view controller loading the web view frame. :param: request The request that will load the frame. :param: navigationType The type of user action that started the load. :returns: Return true to */ optional func webViewController(webViewController: WebViewController, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool /** Sent before the web view begins loading a frame. :param: webViewController The web view controller that has begun loading the frame. */ optional func webViewControllerDidStartLoad(webViewController: WebViewController) /** Sent after the web view as finished loading a frame. :param: webViewController The web view controller that has completed loading the frame. */ optional func webViewControllerDidFinishLoad(webViewController: WebViewController) /** Sent if the web view fails to load a frame. :param: webViewController The web view controller that failed to load the frame. :param: error The error that occured during loading. */ optional func webViewController(webViewController: WebViewController, didFailLoadWithError error: NSError) /** Sent when the web view creates the JS context for the frame. :param: webViewController The web view controller that failed to load the frame. :param: context The newly created JavaScript context. */ optional func webViewControllerDidCreateJavaScriptContext(webViewController: WebViewController, context: JSContext) } /** A view controller that integrates a web view with the hybrid JavaScript API. # Usage Initialize a web view controller and call `loadURL()` to asynchronously load the web view with a URL. ``` let webController = WebViewController() webController.loadURL(NSURL(string: "foo")!) window?.rootViewController = webController ``` Call `addHybridAPI()` to add the bridged JavaScript API to the web view. The JavaScript API will be accessible to any web pages that are loaded in the web view controller. ``` let webController = WebViewController() webController.addHybridAPI() webController.loadURL(NSURL(string: "foo")!) window?.rootViewController = webController ``` To utilize the navigation JavaScript API you must provide a navigation controller for the web view controller. ``` let webController = WebViewController() webController.addHybridAPI() webController.loadURL(NSURL(string: "foo")!) let navigationController = UINavigationController(rootViewController: webController) window?.rootViewController = navigationController ``` */ public class WebViewController: UIViewController { enum AppearenceCause { case Unknown, WebPush, WebPop, WebModal, WebDismiss } /// The URL that was loaded with `loadURL()` private(set) public var url: NSURL? /// The web view used to load and render the web content. private(set) public lazy var webView: UIWebView = { let webView = UIWebView(frame: CGRectZero) webView.delegate = self webViews.addObject(webView) return webView }() /// JavaScript bridge for the web view's JSContext private(set) public var bridge = Bridge() private var storedScreenshotGUID: String? = nil private var goBackInWebViewOnAppear = false private var firstLoadCycleCompleted = true private var disappearedBy = AppearenceCause.Unknown private var storedAppearence = AppearenceCause.WebPush private var appearedFrom: AppearenceCause { get { switch disappearedBy { case .WebPush: return .WebPop case .WebModal: return .WebDismiss default: return storedAppearence } } set { storedAppearence = newValue } } private lazy var placeholderImageView: UIImageView = { return UIImageView(frame: self.view.bounds) }() private var errorView: UIView? private var errorLabel: UILabel? private var reloadButton: UIButton? public weak var hybridAPI: HybridAPI? public var navigationCallback: JSValue? /// Handles web view controller events. public weak var delegate: WebViewControllerDelegate? /// Set `false` to disable error message UI. public var showErrorDisplay = true /** Initialize a web view controller instance with a web view and JavaScript bridge. The newly initialized web view controller becomes the delegate of the web view. :param: webView The web view to use in the web view controller. :param: bridge The bridge instance to integrate int */ public required init(webView: UIWebView, bridge: Bridge) { super.init(nibName: nil, bundle: nil) self.bridge = bridge self.webView = webView self.webView.delegate = self } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { if webView.delegate === self { webView.delegate = nil } } public override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() edgesForExtendedLayout = .None view.addSubview(placeholderImageView) } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) hybridAPI?.parentViewController = self switch appearedFrom { case .WebPush, .WebModal, .WebPop, .WebDismiss: if goBackInWebViewOnAppear { goBackInWebViewOnAppear = false webView.goBack() // go back before remove/adding web view } webView.delegate = self webView.removeFromSuperview() webView.frame = view.bounds view.addSubview(webView) view.removeDoubleTapGestures() // if we have a screenshot stored, load it. if let guid = storedScreenshotGUID { placeholderImageView.image = UIImage.loadImageFromGUID(guid) placeholderImageView.frame = view.bounds view.bringSubviewToFront(placeholderImageView) } if appearedFrom == .WebModal || appearedFrom == .WebPush { navigationCallback?.asValidValue?.callWithArguments(nil) } case .Unknown: break } } public override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) hybridAPI?.view.appeared() switch appearedFrom { case .WebPop, .WebDismiss: showWebView() addBridgeAPIObject() case .WebPush, .WebModal, .Unknown: break } } public override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) switch disappearedBy { case .WebPop, .WebDismiss, .WebPush, .WebModal: // only store screen shot when disappearing by web transition placeholderImageView.frame = webView.frame // must align frames for image capture let image = webView.captureImage() placeholderImageView.image = image storedScreenshotGUID = image.saveImageToGUID() view.bringSubviewToFront(placeholderImageView) webView.hidden = true case .Unknown: break } hybridAPI?.view.disappeared() // needs to be called in viewWillDisappear not Did } public override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) switch disappearedBy { case .WebPop, .WebDismiss, .WebPush, .WebModal: // we're gone. dump the screenshot, we'll load it later if we need to. placeholderImageView.image = nil case .Unknown: // we don't know how it will appear if we don't know how it disappeared appearedFrom = .Unknown } } public final func showWebView() { webView.hidden = false placeholderImageView.image = nil view.sendSubviewToBack(placeholderImageView) } } // MARK: - Request Loading extension WebViewController { /** Load the web view with the provided URL. :param: url The URL used to load the web view. */ final public func loadURL(url: NSURL) { webView.stopLoading() hybridAPI = nil firstLoadCycleCompleted = false self.url = url webView.loadRequest(requestWithURL(url)) } /** Create a request with the provided URL. :param: url The URL for the request. */ public func requestWithURL(url: NSURL) -> NSURLRequest { return NSURLRequest(URL: url) } } // MARK: - UIWebViewDelegate extension WebViewController: UIWebViewDelegate { final public func webViewDidStartLoad(webView: UIWebView) { delegate?.webViewControllerDidStartLoad?(self) } public func webViewDidFinishLoad(webView: UIWebView) { delegate?.webViewControllerDidFinishLoad?(self) if self.errorView != nil { self.removeErrorDisplay() } } final public func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { if pushesWebViewControllerForNavigationType(navigationType) { pushWebViewController() } return delegate?.webViewController?(self, shouldStartLoadWithRequest: request, navigationType: navigationType) ?? true } final public func webView(webView: UIWebView, didFailLoadWithError error: NSError) { if error.code != NSURLErrorCancelled { if showErrorDisplay { renderFeatureErrorDisplayWithError(error, featureName: featureNameForError(error)) } } delegate?.webViewController?(self, didFailLoadWithError: error) } } // MARK: - JavaScript Context extension WebViewController { /** Update the bridge's JavaScript context by attempting to retrieve a context from the web view. */ final public func updateBridgeContext() { if let context = webView.javaScriptContext { configureBridgeContext(context) } else { println("Failed to retrieve JavaScript context from web view.") } } private func didCreateJavaScriptContext(context: JSContext) { configureBridgeContext(context) delegate?.webViewControllerDidCreateJavaScriptContext?(self, context: context) configureContext(context) if let hybridAPI = hybridAPI { var readyCallback = bridge.contextValueForName("nativeBridgeReady") if !readyCallback.isUndefined() { readyCallback.callWithData(hybridAPI) } } } /** Explictly set the bridge's JavaScript context. */ final public func configureBridgeContext(context: JSContext) { bridge.context = context } public func configureContext(context: JSContext) { addBridgeAPIObject() } } // MARK: - Web Controller Navigation extension WebViewController { /** Push a new web view controller on the navigation stack using the existing web view instance. Does not affect web view history. Uses animation. */ public func pushWebViewController() { pushWebViewController(hideBottomBar: false, callback: nil) } /** Push a new web view controller on the navigation stack using the existing web view instance. Does not affect web view history. Uses animation. :param: hideBottomBar Hides the bottom bar of the view controller when true. */ public func pushWebViewController(#hideBottomBar: Bool, callback: JSValue?) { goBackInWebViewOnAppear = true disappearedBy = .WebPush let webViewController = newWebViewController() webViewController.appearedFrom = .WebPush webViewController.navigationCallback = callback webViewController.hidesBottomBarWhenPushed = hideBottomBar navigationController?.pushViewController(webViewController, animated: true) } /** Pop a web view controller off of the navigation. Does not affect web view history. Uses animation. */ public func popWebViewController() { if let navController = self.navigationController where navController.viewControllers.count > 1 { (navController.viewControllers[navController.viewControllers.count - 1] as? WebViewController)?.goBackInWebViewOnAppear = false navController.popViewControllerAnimated(true) } } /** Present a navigation controller containing a new web view controller as the root view controller. The existing web view instance is reused. */ public func presentModalWebViewController(callback: JSValue?) { goBackInWebViewOnAppear = false disappearedBy = .WebModal let webViewController = newWebViewController() webViewController.appearedFrom = .WebModal webViewController.navigationCallback = callback let navigationController = UINavigationController(rootViewController: webViewController) if let tabBarController = tabBarController { tabBarController.presentViewController(navigationController, animated: true, completion: nil) } else { presentViewController(navigationController, animated: true, completion: nil) } } /// Pops until there's only a single view controller left on the navigation stack. public func popToRootWebViewController() { navigationController?.popToRootViewControllerAnimated(true) } /** Return `true` to have the web view controller push a new web view controller on the stack for a given navigation type of a request. */ public func pushesWebViewControllerForNavigationType(navigationType: UIWebViewNavigationType) -> Bool { return false } public func newWebViewController() -> WebViewController { let webViewController = self.dynamicType(webView: webView, bridge: bridge) webViewController.addBridgeAPIObject() return webViewController } } // MARK: - Error UI extension WebViewController { private func createErrorLabel() -> UILabel? { let height = CGFloat(50) let y = CGRectGetMidY(view.bounds) - (height / 2) - 100 var label = UILabel(frame: CGRectMake(0, y, CGRectGetWidth(view.bounds), height)) label.lineBreakMode = NSLineBreakMode.ByWordWrapping label.numberOfLines = 0 label.textAlignment = NSTextAlignment.Center label.backgroundColor = view.backgroundColor label.font = UIFont.systemFontOfSize(12, weight: 2) return label } private func createReloadButton() -> UIButton? { if let button = UIButton.buttonWithType(UIButtonType.Custom) as? UIButton { let size = CGSizeMake(170, 38) let x = CGRectGetMidX(view.bounds) - (size.width / 2) var y = CGRectGetMidY(view.bounds) - (size.height / 2) if let label = errorLabel { y = CGRectGetMaxY(label.frame) + 20 } button.setTitle(NSLocalizedString("Try again", comment: "Try again"), forState: UIControlState.Normal) button.frame = CGRectMake(x, y, size.width, size.height) button.backgroundColor = UIColor.lightGrayColor() button.titleLabel?.backgroundColor = UIColor.lightGrayColor() button.titleLabel?.textColor = UIColor.whiteColor() return button } return nil } } // MARK: - Error Display Events extension WebViewController { /// Override to completely customize error display. Must also override `removeErrorDisplay` public func renderErrorDisplayWithError(error: NSError, message: String) { let errorView = UIView(frame: view.bounds) view.addSubview(errorView) self.errorView = errorView self.errorLabel = createErrorLabel() self.reloadButton = createReloadButton() if let errorLabel = errorLabel { errorLabel.text = NSLocalizedString(message, comment: "Web View Load Error") errorView.addSubview(errorLabel) } if let button = reloadButton { button.addTarget(self, action: "reloadButtonTapped:", forControlEvents: .TouchUpInside) errorView.addSubview(button) } } /// Override to handle custom error display removal. public func removeErrorDisplay() { errorView?.removeFromSuperview() errorView = nil } /// Override to customize the feature name that appears in the error display. public func featureNameForError(error: NSError) -> String { return "This feature" } /// Override to customize the error message text. public func renderFeatureErrorDisplayWithError(error: NSError, featureName: String) { let message = "Sorry!\n \(featureName) isn't working right now." renderErrorDisplayWithError(error, message: message) } /// Removes the error display and attempts to reload the web view. public func reloadButtonTapped(sender: AnyObject) { map(url) {self.loadURL($0)} } } // MARK: - Bridge API extension WebViewController { public func addBridgeAPIObject() { if let bridgeObject = hybridAPI { bridge.context.setObject(bridgeObject, forKeyedSubscript: HybridAPI.exportName) } else { let platform = HybridAPI(parentViewController: self) bridge.context.setObject(platform, forKeyedSubscript: HybridAPI.exportName) hybridAPI = platform } } } // MARK: - UIView Utils extension UIView { func captureImage() -> UIImage { UIGraphicsBeginImageContextWithOptions(bounds.size, opaque, 0.0) layer.renderInContext(UIGraphicsGetCurrentContext()) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func removeDoubleTapGestures() { for view in self.subviews { view.removeDoubleTapGestures() } if let gestureRecognizers = gestureRecognizers { for gesture in gestureRecognizers { if let gesture = gesture as? UITapGestureRecognizer where gesture.numberOfTapsRequired == 2 { removeGestureRecognizer(gesture) } } } } } // MARK: - UIImage utils extension UIImage { // saves image to temp directory and returns a GUID so you can fetch it later. func saveImageToGUID() -> String? { let guid = String.GUID() // do this shit in the background. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in let data = UIImageJPEGRepresentation(self, 1.0) if let data = data { let fileManager = NSFileManager.defaultManager() let fullPath = NSTemporaryDirectory().stringByAppendingPathComponent(guid) fileManager.createFileAtPath(fullPath, contents: data, attributes: nil) } } return guid } class func loadImageFromGUID(guid: String?) -> UIImage? { if let guid = guid { let fileManager = NSFileManager.defaultManager() let fullPath = NSTemporaryDirectory().stringByAppendingPathComponent(guid) let image = UIImage(contentsOfFile: fullPath) return image } return nil } } // MARK: - JSContext Event private var webViews = NSHashTable.weakObjectsHashTable() private struct Statics { static var webViewOnceToken: dispatch_once_t = 0 } extension NSObject { func webView(webView: AnyObject, didCreateJavaScriptContext context: JSContext, forFrame frame: AnyObject) { if let webFrameClass: AnyClass = NSClassFromString("WebFrame") where !(frame.dynamicType === webFrameClass) { return } if let allWebViews = webViews.allObjects as? [UIWebView] { for webView in allWebViews { webView.didCreateJavaScriptContext(context) } } } } extension UIWebView { func didCreateJavaScriptContext(context: JSContext) { (delegate as? WebViewController)?.didCreateJavaScriptContext(context) } }
mit
a37ecc13f27e349d2bab021b26cc2e33
32.519142
172
0.651818
5.39379
false
false
false
false
etiennemartin/jugglez
Jugglez/GameViewController.swift
1
1344
// // GameViewController.swift // Jugglez // // Created by Etienne Martin on 2015-01-18. // Copyright (c) 2015 Etienne Martin. All rights reserved. // import UIKit import SpriteKit class GameViewController: UIViewController { deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override func viewDidLoad() { super.viewDidLoad() let scene = IntroScene(size: view.bounds.size) scene.scaleMode = .ResizeFill if let skView = view as? SKView { skView.ignoresSiblingOrder = true //skView.showsFPS = true //skView.showsNodeCount = true skView.presentScene(scene) } // Register for GameCenter event NSNotificationCenter.defaultCenter().addObserver( self, selector: "onGameCenterViewRequired:", name: GameCenterManager.presentGameCenterNotificationViewController, object: nil) } override func prefersStatusBarHidden() -> Bool { return true } internal func onGameCenterViewRequired(notification: NSNotification) { if GameCenterManager.sharedInstance.authViewController != nil { self.presentViewController(GameCenterManager.sharedInstance.authViewController!, animated: true, completion: nil) } } }
mit
1a5aaa6344baa9f48a750d2da87c3644
28.217391
125
0.659226
5.291339
false
false
false
false
neonichu/LiveGIFs
Code/ImageCell.swift
1
1262
// // ImageCell.swift // LiveGIFs // // Created by Boris Bügling on 13/10/15. // Copyright © 2015 Boris Bügling. All rights reserved. // import UIKit class ImageCell: UICollectionViewCell { let imageView: UIImageView let shadowView: UIView override init(frame: CGRect) { imageView = UIImageView(frame: frame) imageView.alpha = 0.9 imageView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] imageView.clipsToBounds = true imageView.contentMode = .ScaleAspectFill imageView.layer.cornerRadius = 2.0 shadowView = UIView(frame: frame) shadowView.backgroundColor = UIColor.whiteColor() shadowView.layer.shadowColor = UIColor.blackColor().CGColor shadowView.layer.shadowOffset = CGSize(width: 2.0, height: 2.0) shadowView.layer.shadowOpacity = 0.5 super.init(frame: frame) addSubview(shadowView) addSubview(imageView) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { imageView.frame = CGRectInset(bounds, 5.0, 5.0) shadowView.frame = CGRectInset(bounds, 5.0, 5.0) super.layoutSubviews() } }
mit
1c43f8beb608d27f42af419530c1d915
26.977778
71
0.660842
4.480427
false
false
false
false
grafiti-io/SwiftCharts
SwiftCharts/Axis/ChartAxisYHighLayerDefault.swift
1
3071
// // ChartAxisYHighLayerDefault.swift // SwiftCharts // // Created by ischuetz on 25/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit /// A ChartAxisLayer for high Y axes class ChartAxisYHighLayerDefault: ChartAxisYLayerDefault { override var low: Bool {return false} /// The start point of the axis line. override var lineP1: CGPoint { return CGPoint(x: origin.x, y: axis.firstVisibleScreen) } /// The end point of the axis line. override var lineP2: CGPoint { return CGPoint(x: end.x, y: axis.lastVisibleScreen) } override func updateInternal() { guard let chart = chart else {return} super.updateInternal() if lastFrame.width != frame.width { // Move drawers by delta let delta = frame.width - lastFrame.width offset -= delta initDrawers() chart.notifyAxisInnerFrameChange(yHigh: ChartAxisLayerWithFrameDelta(layer: self, delta: delta)) } } override func handleAxisInnerFrameChange(_ xLow: ChartAxisLayerWithFrameDelta?, yLow: ChartAxisLayerWithFrameDelta?, xHigh: ChartAxisLayerWithFrameDelta?, yHigh: ChartAxisLayerWithFrameDelta?) { super.handleAxisInnerFrameChange(xLow, yLow: yLow, xHigh: xHigh, yHigh: yHigh) // Handle resizing of other high y axes if let yHigh = yHigh , yHigh.layer.frame.maxX > frame.maxX { offset = offset - yHigh.delta initDrawers() } } override func initDrawers() { lineDrawer = generateLineDrawer(offset: 0) let labelsOffset = settings.labelsToAxisSpacingY + settings.axisStrokeWidth labelDrawers = generateLabelDrawers(offset: labelsOffset) let axisTitleLabelsOffset = labelsOffset + labelsMaxWidth + settings.axisTitleLabelsToLabelsSpacing axisTitleLabelDrawers = generateAxisTitleLabelsDrawers(offset: axisTitleLabelsOffset) } override func generateLineDrawer(offset: CGFloat) -> ChartLineDrawer { let halfStrokeWidth = settings.axisStrokeWidth / 2 // we want that the stroke begins at the beginning of the frame, not in the middle of it let x = origin.x + offset + halfStrokeWidth let p1 = CGPoint(x: x, y: axis.firstVisibleScreen) let p2 = CGPoint(x: x, y: axis.lastVisibleScreen) return ChartLineDrawer(p1: p1, p2: p2, color: settings.lineColor, strokeWidth: settings.axisStrokeWidth) } override func labelsX(offset: CGFloat, labelWidth: CGFloat, textAlignment: ChartLabelTextAlignment) -> CGFloat { var labelsX: CGFloat switch textAlignment { case .left, .default: labelsX = origin.x + offset case .right: labelsX = origin.x + offset + labelsMaxWidth - labelWidth } return labelsX } override func axisLineX(offset: CGFloat) -> CGFloat { return self.offset + offset + settings.axisStrokeWidth / 2 } }
apache-2.0
7db93b85c84d3574417e5f0557578353
36
198
0.656138
4.674277
false
false
false
false
manGoweb/S3
Sources/S3Kit/Protocols/S3Client.swift
1
5251
import Foundation import NIO import HTTPMediaTypes /// S3 client Protocol public protocol S3Client { /// Get list of objects func buckets(on eventLoop: EventLoop) -> EventLoopFuture<BucketsInfo> /// Create a bucket func create(bucket: String, region: Region?, on eventLoop: EventLoop) -> EventLoopFuture<Void> /// Delete a bucket wherever it is // func delete(bucket: String, on container: Container) -> EventLoopFuture<Void> /// Delete a bucket func delete(bucket: String, region: Region?, on eventLoop: EventLoop) -> EventLoopFuture<Void> /// Get bucket location func location(bucket: String, on eventLoop: EventLoop) -> EventLoopFuture<Region> /// Get list of objects func list(bucket: String, region: Region?, on eventLoop: EventLoop) -> EventLoopFuture<BucketResults> /// Get list of objects func list(bucket: String, region: Region?, headers: [String: String], on eventLoop: EventLoop) -> EventLoopFuture<BucketResults> /// Upload file to S3 func put(file: File.Upload, on eventLoop: EventLoop) -> EventLoopFuture<File.Response> /// Upload file to S3 func put(file: File.Upload, headers: [String: String], on eventLoop: EventLoop) -> EventLoopFuture<File.Response> /// Upload file to S3 func put(file url: URL, destination: String, access: AccessControlList, on eventLoop: EventLoop) -> EventLoopFuture<File.Response> /// Upload file to S3 func put(file url: URL, destination: String, bucket: String?, access: AccessControlList, on eventLoop: EventLoop) -> EventLoopFuture<File.Response> /// Upload file to S3 func put(file path: String, destination: String, access: AccessControlList, on eventLoop: EventLoop) -> EventLoopFuture<File.Response> /// Upload file to S3 func put(file path: String, destination: String, bucket: String?, access: AccessControlList, on eventLoop: EventLoop) -> EventLoopFuture<File.Response> /// Upload file to S3 func put(string: String, destination: String, on eventLoop: EventLoop) -> EventLoopFuture<File.Response> /// Upload file to S3 func put(string: String, destination: String, access: AccessControlList, on eventLoop: EventLoop) -> EventLoopFuture<File.Response> /// Upload file to S3 func put(string: String, mime: HTTPMediaType, destination: String, on eventLoop: EventLoop) -> EventLoopFuture<File.Response> /// Upload file to S3 func put(string: String, mime: HTTPMediaType, destination: String, access: AccessControlList, on eventLoop: EventLoop) -> EventLoopFuture<File.Response> /// Upload file to S3 func put(string: String, mime: HTTPMediaType, destination: String, bucket: String?, access: AccessControlList, on eventLoop: EventLoop) -> EventLoopFuture<File.Response> /// File URL func url(fileInfo file: LocationConvertible) throws -> URL /// Retrieve file data from S3 func get(fileInfo file: LocationConvertible, on eventLoop: EventLoop) -> EventLoopFuture<File.Info> /// Retrieve file data from S3 func get(fileInfo file: LocationConvertible, headers: [String: String], on eventLoop: EventLoop) -> EventLoopFuture<File.Info> /// Retrieve file data from S3 func get(file: LocationConvertible, on eventLoop: EventLoop) -> EventLoopFuture<File.Response> /// Retrieve file data from S3 func get(file: LocationConvertible, headers: [String: String], on eventLoop: EventLoop) -> EventLoopFuture<File.Response> /// Delete file from S3 func delete(file: LocationConvertible, on eventLoop: EventLoop) -> EventLoopFuture<Void> /// Delete file from S3 func delete(file: LocationConvertible, headers: [String: String], on eventLoop: EventLoop) -> EventLoopFuture<Void> /// Copy file on S3 func copy(file: LocationConvertible, to: LocationConvertible, headers: [String: String], on eventLoop: EventLoop) -> EventLoopFuture<File.CopyResponse> } extension S3Client { /// Retrieve file data from S3 func get(file: LocationConvertible, on eventLoop: EventLoop) -> EventLoopFuture<File.Response> { return get(file: file, headers: [:], on: eventLoop) } /// Copy file on S3 public func copy(file: LocationConvertible, to: LocationConvertible, on eventLoop: EventLoop) -> EventLoopFuture<File.CopyResponse> { return self.copy(file: file, to: to, headers: [:], on: eventLoop) } static var dateFormatter: DateFormatter { let formatter = DateFormatter() formatter.calendar = Calendar(identifier: .iso8601) formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX" return formatter } static var headerDateFormatter: DateFormatter { let formatter = DateFormatter() formatter.calendar = Calendar(identifier: .iso8601) formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.dateFormat = "EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'" return formatter } }
mit
ae0e6699fecd6f97ed8e9ab0f565fd18
43.5
173
0.692059
4.56212
false
false
false
false
YaoJuan/YJDouYu
YJDouYu/YJDouYu/Classes/Home-首页/Controller/YJCommendViewController.swift
1
3396
// // YJCommendViewController.swift // YJDouYu // // Created by 赵思 on 2017/7/31. // Copyright © 2017年 赵思. All rights reserved. // import UIKit private let kPrettyItemH: CGFloat = kItemWidth / 0.75 private let kCycleViewH: CGFloat = 1 / 5 * kSceenH private let kTagViewH: CGFloat = 90 class YJCommendViewController: YJBaseViewController { // MARK: - 懒加载属性 fileprivate lazy var recommendVM: YJRecommondVM = YJRecommondVM() fileprivate lazy var cycleView: YJRecommendCycleView = { let view = YJRecommendCycleView.cycleView() view.frame = CGRect(x: 0, y: -(kCycleViewH + kTagViewH), width: kSceenW, height: kCycleViewH) return view }() fileprivate lazy var tagView: YJRecommendTagView = { let view = YJRecommendTagView.tagView() view.frame = CGRect(x: 0, y: -kTagViewH, width: kSceenW, height: kTagViewH) return view }() override func loadData() { // 请求房间列表数据 recommendVM.loadRecommondData() { [unowned self] in self.anchorVM = self.recommendVM // 刷新数据列表 self.collectionView.reloadData() // 处理上方的标签 var tagItems = self.recommendVM.groupItems tagItems.removeFirst() tagItems.removeFirst() let item = YJRecommondGroupItem() item.tag_name = "更多" tagItems.append(item) self.tagView.groupItems = tagItems } // 请求无限轮播数据 recommendVM.loadCycleData { self.cycleView.cycleItems = self.recommendVM.cycleItems } } } // MARK: - 初始化ui extension YJCommendViewController { override func setupUI() { super.setupUI() collectionView.delegate = self // 2.往collectionview上添加循环view collectionView.addSubview(cycleView) // 3.添加tagView collectionView.addSubview(tagView) // 4.设置collectionview的edgeinset显示出cycleView collectionView.contentInset = UIEdgeInsetsMake(kCycleViewH + kTagViewH, 0, 0, 0) } } // MARK: - 数据源 / 代理 extension YJCommendViewController: UICollectionViewDelegateFlowLayout { override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { var cell: YJCollectionBaseCell! if indexPath.section == 1 { cell = collectionView.dequeueReusableCell(withReuseIdentifier: prettyReuseIdentifier, for: indexPath) as! YJCollectionBaseCell } else { cell = collectionView.dequeueReusableCell(withReuseIdentifier: normalReuseIdentifier, for: indexPath) as! YJCollectionBaseCell } // 模型赋值 let item = recommendVM.groupItems[indexPath.section].room_list?[indexPath.row] cell.roomItem = item return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let normalSize = CGSize(width: kItemWidth, height: kNormalItemH) let prettySize = CGSize(width: kItemWidth, height: kPrettyItemH) return indexPath.section == 1 ? prettySize : normalSize } }
mit
f471eb5c746ebaeab834d3fb7f9400ea
31.61
160
0.651334
4.753644
false
false
false
false
LYM-mg/DemoTest
其他功能/SwiftyDemo/Pods/Kingfisher/Sources/General/ImageSource/Source.swift
12
3659
// // Source.swift // Kingfisher // // Created by onevcat on 2018/11/17. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// Represents an image setting source for Kingfisher methods. /// /// A `Source` value indicates the way how the target image can be retrieved and cached. /// /// - network: The target image should be got from network remotely. The associated `Resource` /// value defines detail information like image URL and cache key. /// - provider: The target image should be provided in a data format. Normally, it can be an image /// from local storage or in any other encoding format (like Base64). public enum Source { /// Represents the source task identifier when setting an image to a view with extension methods. public enum Identifier { /// The underlying value type of source identifier. public typealias Value = UInt static var current: Value = 0 static func next() -> Value { current += 1 return current } } // MARK: Member Cases /// The target image should be got from network remotely. The associated `Resource` /// value defines detail information like image URL and cache key. case network(Resource) /// The target image should be provided in a data format. Normally, it can be an image /// from local storage or in any other encoding format (like Base64). case provider(ImageDataProvider) // MARK: Getting Properties /// The cache key defined for this source value. public var cacheKey: String { switch self { case .network(let resource): return resource.cacheKey case .provider(let provider): return provider.cacheKey } } /// The URL defined for this source value. /// /// For a `.network` source, it is the `downloadURL` of associated `Resource` instance. /// For a `.provider` value, it is always `nil`. public var url: URL? { switch self { case .network(let resource): return resource.downloadURL // `ImageDataProvider` does not provide a URL. All it cares is how to get the data back. case .provider(_): return nil } } } extension Source { var asResource: Resource? { guard case .network(let resource) = self else { return nil } return resource } var asProvider: ImageDataProvider? { guard case .provider(let provider) = self else { return nil } return provider } }
mit
9ad0cb71fa5aaa019bcff480bdd17ec9
36.336735
101
0.675868
4.619949
false
false
false
false
sergdort/SwiftImport
Example/Pods/Tests/EventTests.swift
1
2374
// // EventTests.swift // SwiftImport // // Created by Segii Shulga on 8/29/15. // Copyright © 2015 CocoaPods. All rights reserved. // import Quick import Nimble import MagicalRecord import SwiftImport class EventTests: CoreDataTestCase { func test_shouldNotImportWrongEvent() { let event = curry(SwiftImport<Event>.importObjects) <^> JSONObjects -<< JSONFromFileName -<< "WrongEvent" <*> NSManagedObjectContext.MR_defaultContext() expect(event?.value).to(beNil()) } func test_importEvents() { let events = curry(SwiftImport<Event>.importObjects) <^> JSONObjects -<< JSONFromFileName -<< "Events" <*> NSManagedObjectContext.MR_defaultContext() expect(events?.value?[0].eventId).to(equal(1)) expect(events?.value?[0].name).to(equal("WWDC 2015")) expect(events?.value?[0].locationName).to(equal("San Francisco")) expect(events?.value?[0].address).to(equal("Place # X")) expect(events?.value?[1].eventId).to(equal(2)) expect(events?.value?[1].name).to(equal("WWDC 2014")) expect(events?.value?[1].locationName).to(equal("San Francisco")) expect(events?.value?[1].address).to(equal("Place # X1")) } func test_ShouldImportEvent() { let event = curry(SwiftImport<Event>.importObject) <^> JSONObject -<< JSONFromFileName -<< "Event" <*> NSManagedObjectContext.MR_defaultContext() let user = event?.value?.participants?.anyObject() as? User let homeCity = user?.homeCity expect(event).toNot(beNil()) expect(event?.value?.locationName).toNot(beNil()) expect(event?.value?.eventId).toNot(beNil()) expect(event?.value?.address).toNot(beNil()) expect(event?.value?.name).toNot(beNil()) expect(event?.value?.participants).toNot(beNil()) expect(event?.value?.participants?.count).to(equal(2)) expect(user).toNot(beNil()) expect(user?.userId).toNot(beNil()) expect(user?.name).toNot(beNil()) expect(user?.lastName).toNot(beNil()) expect(user?.homeCity).toNot(beNil()) expect(user?.createdEvents).toNot(beNil()) expect(user?.createdEvents?.count).to(equal(2)) expect(homeCity).toNot(beNil()) expect(homeCity?.cityId).toNot(beNil()) expect(homeCity?.name).toNot(beNil()) expect(event?.error).to(beNil()) } }
mit
c49a53836a8f76e23615b8126d95e4e6
37.274194
71
0.648968
3.955
false
true
false
false
Shaunthehugo/Study-Buddy
StudyBuddy/SubjectViewController.swift
1
5845
// // SubjectViewController.swift // Pods // // Created by Shaun Dougherty on 3/20/16. // // import UIKit import Parse import Crashlytics import DZNEmptyDataSet class SubjectViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate { var tutorList: [PFObject]! = [] var username:String! var usernames: [String]! = [] var userList: NSMutableArray = NSMutableArray() var selectedUser: PFUser! var subjectName:String! @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() navigationItem.title = subjectName self.tableView.emptyDataSetSource = self self.tableView.emptyDataSetDelegate = self self.tableView.dataSource = self self.tableView.delegate = self // Do any additional setup after loading the view loadUsers(subjectName) } func emptyDataSetDidAppear(scrollView: UIScrollView!) { self.tableView.separatorColor = UIColor.clearColor() } func emptyDataSetDidDisappear(scrollView: UIScrollView!) { self.tableView.separatorColor = UIColor.lightGrayColor() } func titleForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! { let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18) let attributes :[String:AnyObject] = [NSFontAttributeName : labelFont!] let title: NSAttributedString = NSAttributedString(string: "No Tutors Are Available", attributes: attributes) return title } func buttonTitleForEmptyDataSet(scrollView: UIScrollView!, forState state: UIControlState) -> NSAttributedString! { let labelFont = UIFont(name: "HelveticaNeue", size: 15) let buttonTint = UIColor(red: 118.0/250.0, green: 196.0/250.0, blue: 230.0/250.0, alpha: 1) let attributes :[String:AnyObject] = [NSFontAttributeName : labelFont!, NSForegroundColorAttributeName: buttonTint] let title: NSAttributedString = NSAttributedString(string: "Invite Users", attributes: attributes) return title } override func viewDidAppear(animated: Bool) { print(subjectName) loadUsers(subjectName) } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } func loadUsers(subject: String) { let findTutors = PFUser.query() findTutors?.whereKey("username", notEqualTo: (PFUser.currentUser()?.username)!) findTutors!.whereKey("tutor", equalTo: true) findTutors!.whereKey("subject", equalTo: subject) findTutors?.whereKey("available", equalTo: true) findTutors!.orderByAscending("available") findTutors!.orderByAscending("lastName") findTutors?.findObjectsInBackgroundWithBlock({ (objects: [PFObject]?, error: NSError?) -> Void in PFObject.pinAllInBackground(objects!) if error == nil { self.tutorList.removeAll() self.userList = NSMutableArray(array: objects! as! [PFUser]) self.tableView.reloadData() } else { Crashlytics.sharedInstance().recordError(error!) findTutors?.fromPin() findTutors?.findObjectsInBackgroundWithBlock({ (objects: [PFObject]?, error: NSError?) -> Void in if error == nil { self.userList = NSMutableArray(array: objects! as! [PFUser]) self.tableView.reloadData() } else { Crashlytics.sharedInstance().recordError(error!) } }) } }) } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return userList.count } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { selectedUser = userList.objectAtIndex(indexPath.row) as! PFUser UIApplication.sharedApplication().beginIgnoringInteractionEvents() let sb = UIStoryboard(name: "Main", bundle: nil) let conversationVC = sb.instantiateViewControllerWithIdentifier("conversationVC") as! ConversationViewController var room = PFObject(className: "Room") let user1 = PFUser.currentUser() let user2 = userList[indexPath.row] let pred = NSPredicate(format: "user1 = %@ AND user2 = %@ OR user1 = %@ AND user2 = %@", user1!, user2 as! CVarArgType, user2 as! CVarArgType, user1!) let roomQuery = PFQuery(className: "Room", predicate: pred) roomQuery.cachePolicy = .CacheThenNetwork roomQuery.findObjectsInBackgroundWithBlock { (results: [PFObject]?, error: NSError?) in if error == nil { if results!.count > 0 { // room already existing room = results!.last! as PFObject // Setup MessageViewController and Push to the MessageVC // conversationVC.room = room // conversationVC.incomingUser = user2 as! PFUser // self.navigationController?.pushViewController(conversationVC, animated: true) UIApplication.sharedApplication().endIgnoringInteractionEvents() } else { // create a new room room["user1"] = user1 room["user2"] = user2 room.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) in if error == nil { conversationVC.room = room conversationVC.incomingUser = user2 as! PFUser self.navigationController?.pushViewController(conversationVC, animated: true) } else { Crashlytics.sharedInstance().recordError(error!) } }) } } } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("englishCell", forIndexPath: indexPath) as! TutorTableViewCell let user:PFUser = userList.objectAtIndex(indexPath.row) as! PFUser // user.pinInBackground() user.saveEventually() let firstName = user["firstName"] as! String let lastName = user["lastName"] as! String let name = ("\(firstName)" + " \(lastName)") cell.nameLabel?.text = name cell.subjectLabel?.text = subjectName return cell } }
mit
422a39775b72618a5008222ce0693feb
32.597701
152
0.726775
4.208063
false
false
false
false
qingjie/HAJWelcomeVideo
HAJWelcomeVideo.swift
2
2340
// Created by Hicham Abou Jaoude on 2014-07-24. // Copyright (c) 2014 Hicham Abou Jaoude. All rights reserved. import AVFoundation import QuartzCore import CoreMedia class HAJWelcomeVideo: NSObject { var avPLayer = AVPlayer() var movieView = UIView() var view = UIView() // Set this when initializing var gradientView = UIView() var startTime = CMTimeMake(0, 1) func welcomeWithVideo(videoName: String, type: String, startTime: CMTime, endTime: CMTime, gradientArray: NSArray, view: UIView) -> (){ self.view = view self.movieView.frame = self.view.frame self.startTime = startTime var bundle = NSBundle.mainBundle() var moviePath = bundle.pathForResource(videoName, ofType: type) var movieURL = NSURL.fileURLWithPath(moviePath) var avAsset: AVAsset = AVAsset.assetWithURL(movieURL) as AVAsset var avPlayerItem = AVPlayerItem(asset: avAsset) avPlayerItem.forwardPlaybackEndTime = endTime self.avPLayer = AVPlayer(playerItem: avPlayerItem) var avPLayerLayer = AVPlayerLayer(player: self.avPLayer) avPLayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill avPLayerLayer.frame = self.view.frame self.movieView.layer.addSublayer(avPLayerLayer) AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, error: nil) AVAudioSession.sharedInstance().setActive(true, error: nil) self.avPLayer.seekToTime(startTime) self.avPLayer.volume = 0; self.avPLayer.actionAtItemEnd = AVPlayerActionAtItemEnd.None NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerItemDidReachEnd:", name: AVPlayerItemDidPlayToEndTimeNotification, object: self.avPLayer.currentItem) var gradient = CAGradientLayer() self.gradientView.frame = self.movieView.frame gradient.frame = self.gradientView.bounds let arrayColors: Array <AnyObject> = gradientArray gradient.colors = arrayColors self.gradientView.layer.insertSublayer(gradient, atIndex: 0) } func playerItemDidReachEnd(notification: NSNotification) -> (){ var p = notification.object as AVPlayerItem p.seekToTime(self.startTime) } }
mit
4b7408bfb3a2a27cc122ca2f4676749e
40.052632
181
0.694872
4.708249
false
false
false
false
Johnykutty/SwiftLint
Source/SwiftLintFramework/Rules/ForceUnwrappingRule.swift
2
7979
// // ForceUnwrappingRule.swift // SwiftLint // // Created by Benjamin Otto on 14/01/16. // Copyright © 2015 Realm. All rights reserved. // import Foundation import SourceKittenFramework public struct ForceUnwrappingRule: OptInRule, ConfigurationProviderRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "force_unwrapping", name: "Force Unwrapping", description: "Force unwrapping should be avoided.", nonTriggeringExamples: [ "if let url = NSURL(string: query)", "navigationController?.pushViewController(viewController, animated: true)", "let s as! Test", "try! canThrowErrors()", "let object: Any!", "@IBOutlet var constraints: [NSLayoutConstraint]!", "setEditing(!editing, animated: true)", "navigationController.setNavigationBarHidden(!navigationController." + "navigationBarHidden, animated: true)", "if addedToPlaylist && (!self.selectedFilters.isEmpty || " + "self.searchBar?.text?.isEmpty == false) {}", "print(\"\\(xVar)!\")", "var test = (!bar)" ], triggeringExamples: [ "let url = NSURL(string: query)↓!", "navigationController↓!.pushViewController(viewController, animated: true)", "let unwrapped = optional↓!", "return cell↓!", "let url = NSURL(string: \"http://www.google.com\")↓!", "let dict = [\"Boooo\": \"👻\"]func bla() -> String { return dict[\"Boooo\"]↓! }" ] ) public func validate(file: File) -> [StyleViolation] { return violationRanges(in: file).map { return StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, characterOffset: $0.location)) } } // capture previous and next of "!" // http://userguide.icu-project.org/strings/regexp private static let pattern = "([^\\s\\p{Ps}])(!)(.?)" private static let regularExpression = regex(pattern, options: [.dotMatchesLineSeparators]) private static let excludingSyntaxKindsForFirstCapture = SyntaxKind .commentKeywordStringAndTypeidentifierKinds().map { $0.rawValue } private static let excludingSyntaxKindsForSecondCapture = SyntaxKind .commentAndStringKinds().map { $0.rawValue } private static let excludingSyntaxKindsForThirdCapture = [SyntaxKind.identifier.rawValue] // swiftlint:disable:next function_body_length private func violationRanges(in file: File) -> [NSRange] { let contents = file.contents let nsstring = contents.bridge() let range = NSRange(location: 0, length: contents.utf16.count) let syntaxMap = file.syntaxMap return ForceUnwrappingRule.regularExpression .matches(in: contents, options: [], range: range) .flatMap { match -> NSRange? in if match.numberOfRanges < 3 { return nil } let firstRange = match.rangeAt(1) let secondRange = match.rangeAt(2) let violationRange = NSRange(location: NSMaxRange(firstRange), length: 0) guard let matchByteFirstRange = contents.bridge() .NSRangeToByteRange(start: firstRange.location, length: firstRange.length), let matchByteSecondRange = contents.bridge() .NSRangeToByteRange(start: secondRange.location, length: secondRange.length) else { return nil } let tokensInFirstRange = syntaxMap.tokens(inByteRange: matchByteFirstRange) let tokensInSecondRange = syntaxMap.tokens(inByteRange: matchByteSecondRange) // check first captured range // If not empty, first captured range is comment, string, keyword or typeidentifier. // We checks "not empty" because tokens may empty without filtering. guard tokensInFirstRange.filter({ ForceUnwrappingRule.excludingSyntaxKindsForFirstCapture.contains($0.type) }).isEmpty else { return nil } // if first captured range is identifier, generate violation if tokensInFirstRange.map({ $0.type }).contains(SyntaxKind.identifier.rawValue) { return violationRange } // check second capture '!' let forceUnwrapNotInCommentOrString = tokensInSecondRange.filter({ ForceUnwrappingRule.excludingSyntaxKindsForSecondCapture.contains($0.type) }).isEmpty // check firstCapturedString is ")" and '!' is not within comment or string let firstCapturedString = nsstring.substring(with: firstRange) if firstCapturedString == ")" && forceUnwrapNotInCommentOrString { return violationRange } // check third capture if match.numberOfRanges == 3 { // check third captured range let secondRange = match.rangeAt(3) guard let matchByteThirdRange = contents.bridge() .NSRangeToByteRange(start: secondRange.location, length: secondRange.length) else { return nil } let tokensInThirdRange = syntaxMap.tokens(inByteRange: matchByteThirdRange).filter { ForceUnwrappingRule.excludingSyntaxKindsForThirdCapture.contains($0.type) } // If not empty, third captured range is identifier. // "!" is "operator prefix !". if !tokensInThirdRange.isEmpty { return nil } } // check structure if checkStructure(in: file, byteRange: matchByteFirstRange) { return violationRange } else { return nil } } } // Returns if range should generate violation // check deepest kind matching range in structure private func checkStructure(in file: File, byteRange: NSRange) -> Bool { let nsstring = file.contents.bridge() let kinds = file.structure.kinds(forByteOffset: byteRange.location) if let lastKind = kinds.last { switch lastKind.kind { // range is in some "source.lang.swift.decl.var.*" case SwiftDeclarationKind.varClass.rawValue: fallthrough case SwiftDeclarationKind.varGlobal.rawValue: fallthrough case SwiftDeclarationKind.varInstance.rawValue: fallthrough case SwiftDeclarationKind.varStatic.rawValue: let byteOffset = lastKind.byteRange.location let byteLength = byteRange.location - byteOffset if let varDeclarationString = nsstring .substringWithByteRange(start: byteOffset, length: byteLength), varDeclarationString.contains("=") { // if declarations contains "=", range is not type annotation return true } else { // range is type annotation of declaration return false } // followings have invalid "key.length" returned from SourceKitService w/ Xcode 7.2.1 // case SwiftDeclarationKind.VarParameter.rawValue: fallthrough // case SwiftDeclarationKind.VarLocal.rawValue: fallthrough default: break } if lastKind.kind.hasPrefix("source.lang.swift.decl.function") { return true } } return false } }
mit
76446b4487d074a1f127b771f037a69f
44.764368
104
0.597011
5.413324
false
false
false
false
roop/memorydumper
memory.swift
1
19116
/*/../usr/bin/true source="$0" compiled="$0"c if [[ "$source" -nt "$compiled" ]]; then DEVELOPER_DIR=/Applications/Xcode6-Beta.app/Contents/Developer xcrun swiftc -sdk /Applications/Xcode6-Beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk -g "$source" -o "$compiled" || exit fi "$compiled" exit */ import Foundation import Darwin enum PrintColor { case Default case Red case Green case Yellow case Blue case Magenta case Cyan } protocol Printer { func print(color: PrintColor, _ str: String) func print(str: String) func println() func end() } class TermPrinter: Printer { let colorCodes: Dictionary<PrintColor, String> = [ .Default: "39", .Red: "31", .Green: "32", .Yellow: "33", .Blue: "34", .Magenta: "35", .Cyan: "36" ] func printEscape(color: PrintColor) { Swift.print("\u{1B}[\(colorCodes[color]!)m") } func print(color: PrintColor, _ str: String) { printEscape(color) Swift.print(str) printEscape(.Default) } func print(str: String) { print(.Default, str) } func println() { Swift.println() } func end() {} } class HTMLPrinter: Printer { let colorNames: Dictionary<PrintColor, String> = [ .Default: "black", .Red: "darkred", .Green: "green", .Yellow: "goldenrod", .Blue: "darkblue", .Magenta: "darkmagenta", .Cyan: "darkcyan" ] var didEnd = false init() { Swift.println("<div style=\"font-family: monospace\">") } deinit { assert(didEnd, "Must end printer before destroying it") } func escape(str: String) -> String { let mutable = NSMutableString(string: str) func replace(str: String, with: String) { mutable.replaceOccurrencesOfString(str, withString: with, options: NSStringCompareOptions(0), range: NSRange(location: 0, length: mutable.length)) } replace("&", "&amp;") replace("<", "&lt;") replace(">", "&gt;") replace(" ", "&nbsp; ") return mutable as NSString as! String } func print(color: PrintColor, _ str: String) { Swift.print("<span style=\"color: \(colorNames[color]!)\">") Swift.print(escape(str)) Swift.print("</span>") } func print(str: String) { print(.Default, str) } func println() { Swift.println("<br>") } func end() { Swift.println("</div>") didEnd = true } } struct Pointer: Hashable, Printable { let address: UInt var hashValue: Int { return unsafeBitCast(address, Int.self) } var description: String { return NSString(format: "0x%0*llx", sizeof(address.dynamicType) * 2, address) as! String } func symbolInfo() -> Dl_info? { var info = Dl_info(dli_fname: "", dli_fbase: nil, dli_sname: "", dli_saddr: nil) let ptr: UnsafePointer<Void> = unsafeBitCast(address, UnsafePointer<Void>.self) let result = dladdr(ptr, &info) return (result == 0 ? nil : info) } func symbolName() -> String? { if let info = symbolInfo() { let symbolAddress: UInt = unsafeBitCast(info.dli_saddr, UInt.self) if symbolAddress == address { return String.fromCString(info.dli_sname) } } return nil } func nextSymbol(limit: Int) -> Pointer? { if let myInfo = symbolInfo() { for i in 1..<limit { let candidate = self + i let candidateInfo = candidate.symbolInfo() if candidateInfo == nil { return nil } if myInfo.dli_saddr != candidateInfo!.dli_saddr { return candidate } } } return nil } } func ==(a: Pointer, b: Pointer) -> Bool { return a.address == b.address } func +(a: Pointer, b: Int) -> Pointer { return Pointer(address: a.address + UInt(b)) } func -(a: Pointer, b: Pointer) -> Int { return Int(a.address - b.address) } struct Memory { let buffer: [UInt8] let isMalloc: Bool let isSymbol: Bool static func readIntoArray(ptr: Pointer, var _ buffer: [UInt8]) -> Bool { let result = buffer.withUnsafeBufferPointer { (targetPtr: UnsafeBufferPointer<UInt8>) -> kern_return_t in let ptr64 = UInt64(ptr.address) let target: UInt = unsafeBitCast(targetPtr.baseAddress, UInt.self) let target64 = UInt64(target) var outsize: mach_vm_size_t = 0 return mach_vm_read_overwrite(mach_task_self_, ptr64, mach_vm_size_t(buffer.count), target64, &outsize) } return result == KERN_SUCCESS } static func read(ptr: Pointer, knownSize: Int? = nil) -> Memory? { let convertedPtr: UnsafePointer<Void> = unsafeBitCast(ptr.address, UnsafePointer<Void>.self) var length = Int(malloc_size(convertedPtr)) let isMalloc = length > 0 let isSymbol = ptr.symbolName() != nil if isSymbol { if let nextSymbol = ptr.nextSymbol(4096) { length = nextSymbol - ptr } } if length == 0 && knownSize == nil { var result = [UInt8]() while (result.count < 128) { var eightBytes = [UInt8](count: 8, repeatedValue: 0) let success = readIntoArray(ptr + result.count, eightBytes) if !success { break } result.extend(eightBytes) } return (result.count > 0 ? Memory(buffer: result, isMalloc: false, isSymbol: isSymbol) : nil) } else { if knownSize != nil { length = knownSize! } var result = [UInt8](count: length, repeatedValue: 0) let success = readIntoArray(ptr, result) return (success ? Memory(buffer: result, isMalloc: isMalloc, isSymbol: isSymbol) : nil) } } func scanPointers() -> [PointerAndOffset] { var pointers = [PointerAndOffset]() buffer.withUnsafeBufferPointer { (memPtr: UnsafeBufferPointer<UInt8>) -> Void in let ptrptr = UnsafePointer<UInt>(memPtr.baseAddress) let count = self.buffer.count / 8 for i in 0..<count { pointers.append(PointerAndOffset(pointer: Pointer(address: ptrptr[i]), offset: i * 8)) } } return pointers } func scanStrings() -> [String] { let lowerBound: UInt8 = 32 let upperBound: UInt8 = 126 var current = [UInt8]() var strings = [String]() for byte in buffer + [0] { if byte >= lowerBound && byte <= upperBound { current.append(byte) } else { if current.count >= 4 { var str = String() for byte in current { str.append(UnicodeScalar(byte)) } strings.append(str) } current.removeAll() } } return strings } func hex() -> String { let spacesInterval = 8 let str = NSMutableString(capacity: buffer.count * 2) for (index, byte) in enumerate(buffer) { if index > 0 && (index % spacesInterval) == 0 { str.appendString(" ") } str.appendFormat("%02x", byte) } return str as NSString as! String } } struct PointerAndOffset { let pointer: Pointer let offset: Int } enum Alignment { case Right case Left } func pad(value: Any, minWidth: Int, padChar: String = " ", align: Alignment = .Right) -> String { var str = "\(value)" var accumulator = "" if align == .Left { accumulator += str } if minWidth > count(str) { for i in 0..<(minWidth - count(str)) { accumulator += padChar } } if align == .Right { accumulator += str } return accumulator } func limit(str: String, maxLength: Int, continuation: String = "...") -> String { if count(str) <= maxLength { return str } let start = str.startIndex let truncationPoint = advance(start, maxLength) return str[start..<truncationPoint] + continuation } class ScanEntry { let parent: ScanEntry? var parentOffset: Int let address: Pointer var index: Int init(parent: ScanEntry?, parentOffset: Int, address: Pointer, index: Int) { self.parent = parent self.parentOffset = parentOffset self.address = address self.index = index } } func STR(p: UnsafePointer<CChar>) -> String { return String.fromCString(p) ?? "-" } struct ObjCClass { static let classMap: Dictionary<Pointer, ObjCClass> = { var tmpMap = Dictionary<Pointer, ObjCClass>() for c in AllClasses() { tmpMap[c.address] = c } return tmpMap }() static func atAddress(address: Pointer) -> ObjCClass? { return classMap[address] } static func dumpObjectClasses(p: Printer, _ obj: AnyObject) { var classPtr: AnyClass! = object_getClass(obj) while classPtr != nil { ObjCClass(address: Pointer(address: unsafeBitCast(classPtr, UInt.self))).dump(p) classPtr = class_getSuperclass(classPtr) } } let address: Pointer var classPtr: AnyClass { return unsafeBitCast(address.address, AnyClass.self) } var name: String { return String.fromCString(class_getName(classPtr))! } func dump(p: Printer) { func iterate(pointer: UnsafeMutablePointer<COpaquePointer>, callForEach: (COpaquePointer) -> Void) { if pointer != nil { var i = 0 while pointer[i] != nil { callForEach(pointer[i]) i++ } free(pointer) } } p.print("Objective-C class \(name)") if class_getName(classPtr) == "NSObject" { println() } else { p.print(":") p.println() iterate(class_copyIvarList(classPtr, nil)) { p.print(" Ivar: \(STR(ivar_getName($0))) \(STR(ivar_getTypeEncoding($0)))") p.println() } iterate(class_copyPropertyList(classPtr, nil)) { p.print(" Property: \(STR(property_getName($0))) \(STR(property_getAttributes($0)))") p.println() } iterate(class_copyMethodList(classPtr, nil)) { p.print(" Method: \(STR(sel_getName(method_getName($0)))) \(STR(method_getTypeEncoding($0)))") p.println() } } } } func AllClasses() -> [ObjCClass] { var count: CUnsignedInt = 0 let classList = objc_copyClassList(&count) var result = [ObjCClass]() for i in 0..<count { let rawClass: AnyClass! = classList[Int(i)] let address: Pointer = Pointer(address: unsafeBitCast(rawClass, UInt.self)) result.append(ObjCClass(address: address)) } return result } class ScanResult { let entry: ScanEntry let parent: ScanResult? let memory: Memory var children = [ScanResult]() var indent = 0 var color: PrintColor = .Default init(entry: ScanEntry, parent: ScanResult?, memory: Memory) { self.entry = entry self.parent = parent self.memory = memory } var name: String { if let c = ObjCClass.atAddress(entry.address) { return c.name } let pointers = memory.scanPointers() if pointers.count > 0 { if let c = ObjCClass.atAddress(pointers[0].pointer) { return "<\(c.name): \(entry.address.description)>" } } return entry.address.description } func dump(p: Printer) { if let parent = entry.parent { p.print("(") p.print(self.parent!.color, "\(pad(parent.index, 3)), \(pad(self.parent!.name, 24))@\(pad(entry.parentOffset, 3, align: .Left))") p.print(") <- ") } else { p.print("Starting pointer: ") } p.print(color, "\(pad(entry.index, 3)) \(entry.address.description): ") p.print(color, "\(pad(memory.buffer.count, 5)) bytes ") if memory.isMalloc { p.print(color, "<malloc> ") } else if memory.isSymbol { p.print(color, "<symbol> ") } else { p.print(color, "<unknwn> ") } p.print(color, limit(memory.hex(), 101)) if let symbolName = entry.address.symbolName() { p.print(" Symbol \(symbolName)") } if let objCClass = ObjCClass.atAddress(entry.address) { p.print(" ObjC class \(objCClass.name)") } let strings = memory.scanStrings() if strings.count > 0 { p.print(" -- strings: (") p.print(", ".join(strings)) p.print(")") } p.println() } func recursiveDump(p: Printer) { var entryColorIndex = 0 let entryColors: [PrintColor] = [ .Red, .Green, .Yellow, .Blue, .Magenta, .Cyan ] func nextColor() -> PrintColor { return entryColors[entryColorIndex++ % entryColors.count] } var chain = [self] while chain.count > 0 { let result = chain.removeLast() if result.children.count > 0 { result.color = nextColor() } for i in 0..<result.indent { p.print(" ") } result.dump(p) for child in result.children.reverse() { child.indent = result.indent + 1 chain.append(child) } } } } func scanmem<T>(var x: T, limit: Int) -> ScanResult { var count = 0 var seen = Dictionary<Pointer, Void>() var toScan = Array<ScanEntry>() var results = Dictionary<Pointer, ScanResult>() return withUnsafePointer(&x) { (ptr: UnsafePointer<T>) -> ScanResult in let firstAddr: Pointer = Pointer(address: unsafeBitCast(ptr, UInt.self)) let firstEntry = ScanEntry(parent: nil, parentOffset: 0, address: firstAddr, index: 0) seen[firstAddr] = () toScan.append(firstEntry) while toScan.count > 0 && count < limit { let entry = toScan.removeLast() entry.index = count let memory: Memory! = Memory.read(entry.address, knownSize: count == 0 ? sizeof(T.self) : nil) if memory != nil { count++ var parent: ScanResult? = nil if let parentEntry = entry.parent { parent = results[parentEntry.address] } let result = ScanResult(entry: entry, parent: parent, memory: memory) parent?.children.append(result) results[entry.address] = result let pointersAndOffsets = memory.scanPointers() for pointerAndOffset in pointersAndOffsets { let pointer = pointerAndOffset.pointer let offset = pointerAndOffset.offset if seen[pointer] == nil { seen[pointer] = () let newEntry = ScanEntry(parent: entry, parentOffset: offset, address: pointer, index: count) toScan.insert(newEntry, atIndex: 0) } } } } return results[firstAddr]! } } let printer = TermPrinter() func dumpmem<T>(x: T) { println("Dumping \(x)") scanmem(x, 32).recursiveDump(printer) } let obj: NSObject? = NSObject() let nilobj: NSObject? = nil dumpmem(obj) dumpmem(nilobj) let x = 42 let y: Int? = 42 let z: Int? = nil dumpmem(x) dumpmem(y) dumpmem(z) let r: NSRect? = NSMakeRect(0, 0, 0, 0) let rnil: NSRect? = nil dumpmem(r) dumpmem(rnil) protocol P { func p() } extension NSObject: P { func p() {} } extension Int: P { func p() {} } let pobj: P = NSObject() dumpmem(pobj) let pint: P = 42 dumpmem(pint) struct S: P { let x: Int let y: Int func p() {} } let s: P = S(x: 42, y: 43) dumpmem(s) struct T: P { let x: Int let y: Int let z: Int let a: Int func p() {} } let t: P = T(x: 42, y: 43, z: 44, a: 45) dumpmem(t) class Wrapper<T> { let value: T init(_ value: T) { self.value = value } } dumpmem(Wrapper(42)) dumpmem(Wrapper(T(x: 42, y: 43, z: 44, a: 45))) class Wrapper2<T, U> { let value1: T let value2: U init(_ value1: T, _ value2: U) { self.value1 = value1 self.value2 = value2 } } dumpmem(Wrapper2(42, 43)) dumpmem(Wrapper2((42, 43), 44)) dumpmem(Wrapper2(42, (43, 44))) // BEGIN: Recursive enum using intermediate protocol protocol TreeProto { var description: String {get} } enum Tree: TreeProto { case Empty case Leaf(String) case Node(TreeProto, TreeProto) var description: String { switch self { case Empty: return "<empty>" case let Leaf(text): return text case let Node(left, right): return "(" + left.description + ", " + right.description + ")" } } } let empty = Tree.Empty dumpmem(empty) let sadLeaf = Tree.Leaf("hello") dumpmem(sadLeaf) let twoNodes = Tree.Node(sadLeaf, Tree.Leaf("world")) dumpmem(twoNodes) let fourNodes = Tree.Node( Tree.Node(Tree.Leaf("node0"), Tree.Leaf("node1")), Tree.Node(Tree.Leaf("node2"), Tree.Leaf("node3"))) dumpmem(fourNodes) let tallTree = Tree.Node(Tree.Leaf("node0"), Tree.Node(Tree.Leaf("node1"), Tree.Node(Tree.Leaf("node2"), Tree.Node(Tree.Leaf("node3"), Tree.Node(Tree.Leaf("node4"), Tree.Node(Tree.Leaf("node5"), Tree.Node(Tree.Leaf("node6"), Tree.Node(Tree.Leaf("node7"), Tree.Node(Tree.Leaf("node8"), Tree.Node(Tree.Leaf("node9"), Tree.Node(Tree.Leaf("node10"), Tree.Leaf("node11")))))))))))) dumpmem(tallTree) // END: Recursive enum using intermediate protocol printer.end()
bsd-3-clause
2479b34a61bf7a0812460878b55df668
26
223
0.529766
4.056015
false
false
false
false
Czajnikowski/TrainTrippin
Pods/RxSwift/RxSwift/DataStructures/Bag.swift
3
7475
// // Bag.swift // RxSwift // // Created by Krunoslav Zaher on 2/28/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import Swift let arrayDictionaryMaxSize = 30 /** Class that enables using memory allocations as a means to uniquely identify objects. */ class Identity { // weird things have known to happen with Swift var _forceAllocation: Int32 = 0 } func hash(_ _x: Int) -> Int { var x = _x x = ((x >> 16) ^ x) &* 0x45d9f3b x = ((x >> 16) ^ x) &* 0x45d9f3b x = ((x >> 16) ^ x) return x; } /** Unique identifier for object added to `Bag`. */ public struct BagKey : Hashable { let uniqueIdentity: Identity? let key: Int public var hashValue: Int { if let uniqueIdentity = uniqueIdentity { return hash(key) ^ (ObjectIdentifier(uniqueIdentity).hashValue) } else { return hash(key) } } } /** Compares two `BagKey`s. */ public func == (lhs: BagKey, rhs: BagKey) -> Bool { return lhs.key == rhs.key && lhs.uniqueIdentity === rhs.uniqueIdentity } /** Data structure that represents a bag of elements typed `T`. Single element can be stored multiple times. Time and space complexity of insertion an deletion is O(n). It is suitable for storing small number of elements. */ public struct Bag<T> : CustomDebugStringConvertible { /** Type of identifier for inserted elements. */ public typealias KeyType = BagKey fileprivate typealias ScopeUniqueTokenType = Int typealias Entry = (key: BagKey, value: T) fileprivate var _uniqueIdentity: Identity? fileprivate var _nextKey: ScopeUniqueTokenType = 0 // data // first fill inline variables fileprivate var _key0: BagKey? = nil fileprivate var _value0: T? = nil fileprivate var _key1: BagKey? = nil fileprivate var _value1: T? = nil // then fill "array dictionary" fileprivate var _pairs = ContiguousArray<Entry>() // last is sparse dictionary fileprivate var _dictionary: [BagKey : T]? = nil fileprivate var _onlyFastPath = true /** Creates new empty `Bag`. */ public init() { } /** Inserts `value` into bag. - parameter element: Element to insert. - returns: Key that can be used to remove element from bag. */ public mutating func insert(_ element: T) -> BagKey { _nextKey = _nextKey &+ 1 #if DEBUG _nextKey = _nextKey % 20 #endif if _nextKey == 0 { _uniqueIdentity = Identity() } let key = BagKey(uniqueIdentity: _uniqueIdentity, key: _nextKey) if _key0 == nil { _key0 = key _value0 = element return key } _onlyFastPath = false if _key1 == nil { _key1 = key _value1 = element return key } if _dictionary != nil { _dictionary![key] = element return key } if _pairs.count < arrayDictionaryMaxSize { _pairs.append(key: key, value: element) return key } if _dictionary == nil { _dictionary = [:] } _dictionary![key] = element return key } /** - returns: Number of elements in bag. */ public var count: Int { let dictionaryCount: Int = _dictionary?.count ?? 0 return _pairs.count + (_value0 != nil ? 1 : 0) + (_value1 != nil ? 1 : 0) + dictionaryCount } /** Removes all elements from bag and clears capacity. */ public mutating func removeAll() { _key0 = nil _value0 = nil _key1 = nil _value1 = nil _pairs.removeAll(keepingCapacity: false) _dictionary?.removeAll(keepingCapacity: false) } /** Removes element with a specific `key` from bag. - parameter key: Key that identifies element to remove from bag. - returns: Element that bag contained, or nil in case element was already removed. */ public mutating func removeKey(_ key: BagKey) -> T? { if _key0 == key { _key0 = nil let value = _value0! _value0 = nil return value } if _key1 == key { _key1 = nil let value = _value1! _value1 = nil return value } if let existingObject = _dictionary?.removeValue(forKey: key) { return existingObject } for i in 0 ..< _pairs.count { if _pairs[i].key == key { let value = _pairs[i].value _pairs.remove(at: i) return value } } return nil } } extension Bag { /** A textual representation of `self`, suitable for debugging. */ public var debugDescription : String { return "\(self.count) elements in Bag" } } // MARK: forEach extension Bag { /** Enumerates elements inside the bag. - parameter action: Enumeration closure. */ public func forEach(_ action: (T) -> Void) { if _onlyFastPath { if let value0 = _value0 { action(value0) } return } let pairs = _pairs let value0 = _value0 let value1 = _value1 let dictionary = _dictionary if let value0 = value0 { action(value0) } if let value1 = value1 { action(value1) } for i in 0 ..< pairs.count { action(pairs[i].value) } if dictionary?.count ?? 0 > 0 { for element in dictionary!.values { action(element) } } } } extension Bag where T: ObserverType { /** Dispatches `event` to app observers contained inside bag. - parameter action: Enumeration closure. */ public func on(_ event: Event<T.E>) { if _onlyFastPath { _value0?.on(event) return } let pairs = _pairs let value0 = _value0 let value1 = _value1 let dictionary = _dictionary if let value0 = value0 { value0.on(event) } if let value1 = value1 { value1.on(event) } for i in 0 ..< pairs.count { pairs[i].value.on(event) } if dictionary?.count ?? 0 > 0 { for element in dictionary!.values { element.on(event) } } } } /** Dispatches `dispose` to all disposables contained inside bag. */ @available(*, deprecated, renamed: "disposeAll(in:)") public func disposeAllIn(_ bag: Bag<Disposable>) { disposeAll(in: bag) } /** Dispatches `dispose` to all disposables contained inside bag. */ public func disposeAll(in bag: Bag<Disposable>) { if bag._onlyFastPath { bag._value0?.dispose() return } let pairs = bag._pairs let value0 = bag._value0 let value1 = bag._value1 let dictionary = bag._dictionary if let value0 = value0 { value0.dispose() } if let value1 = value1 { value1.dispose() } for i in 0 ..< pairs.count { pairs[i].value.dispose() } if dictionary?.count ?? 0 > 0 { for element in dictionary!.values { element.dispose() } } }
mit
f75ad08f2d88a554d55fccdb4994dcfe
21.244048
99
0.544688
4.249005
false
false
false
false
tarunon/Illuso
Sources/Encoder.swift
1
2339
// // Encoder.swift // JSONEncoder // // Created by Nobuo Saito on 2016/01/07. // Copyright © 2016年 tarunon. All rights reserved. // import Foundation internal func convert<T>(_ array: [(String, T)]) -> [String: T] { var dict = [String: T]() array.forEach { key, value in dict[key] = value } return dict } internal func map(_ elements: Mirror.Children) throws -> [JSON] { return try elements .flatMap { key, value in try _encode(value) } } internal func map(_ pairs: Mirror.Children) throws -> [String: JSON] { return convert(try pairs .map { key, value -> (String, JSON) in guard case .array(let pair) = try _encode(value) else { throw JSONError.unknown } guard let key = pair[0].asObject() as? String else { throw JSONError.keyIsNotString(pair[0].asObject()) } return (key, pair[1]) }) } internal func analyze(_ mirror: Mirror) throws -> [(String, JSON)] { let superclassProperties = try mirror.superclassMirror.map { try analyze($0) } ?? [] let properties = try mirror.children .flatMap { key, value in key.map { ($0, value) } } .map { key, value in try (key, _encode(value)) } return superclassProperties + properties } internal func _encode(_ object: Any?) throws -> JSON { guard let object = object else { return .null } if let json = object as? JSON { return json } if let encodable = object as? Encodable { return try encodable.encode() } let mirror = Mirror(reflecting: object) switch mirror.displayStyle { case .some(.struct), .some(.class), .some(.enum): return .dictionary(convert(try analyze(mirror))) case .some(.collection), .some(.set), .some(.tuple): return .array(try map(mirror.children)) case .some(.dictionary): return .dictionary(try map(mirror.children)) case .some(.optional): if let some = mirror.children.first { return try _encode(some.value) } return .null default: break } throw JSONError.unsupportedType(object) } // workaround: We cannot overload class method and global function. public func encode(_ object: Any?) throws -> JSON { return try _encode(object) }
mit
09a93061a9c07514c019750bfc2a3506
28.56962
117
0.60488
3.939292
false
false
false
false
pfvernon2/swiftlets
Portable/Dispatch+Utilities.swift
1
9429
// // Dispatch+Utilities.swift // swiftlets // // Created by Frank Vernon on 8/29/16. // Copyright © 2016 Frank Vernon. All rights reserved. // import Foundation public extension DispatchQueue { ///DispatchTime conversion from TimeInterval with microsecond precision. private func dispatchTimeFromNow(seconds: TimeInterval) -> DispatchTime { let microseconds:Int = Int(seconds * 1000000.0) let dispatchOffset:DispatchTime = .now() + .microseconds(microseconds) return dispatchOffset } ///asyncAfter with TimeInterval semantics, i.e. microsecond precision out to 10,000 years. func asyncAfter(secondsFromNow seconds: TimeInterval, execute work: @escaping @convention(block) () -> Swift.Void) { asyncAfter(deadline: dispatchTimeFromNow(seconds: seconds), execute: work) } ///asyncAfter with TimeInterval semantics, i.e. microsecond precision out to 10,000 years. func asyncAfter(secondsFromNow seconds: TimeInterval, execute: DispatchWorkItem) { asyncAfter(deadline: dispatchTimeFromNow(seconds: seconds), execute: execute) } private static var _onceTracker = [String]() /** Executes a block of code, associated with a unique identifier, only once for the current run of the application. This method is thread safe and will only execute the code once even when called concurrently. - parameter identifier: A unique identifier such as a reverse DNS style name (com.domain.appIdentifier), or a GUID - parameter closure: Block of code to execute only once */ class func executeOnce(identifier: String, closure:()->Swift.Void) { objc_sync_enter(self) defer { objc_sync_exit(self) } guard !_onceTracker.contains(identifier) else { return } _onceTracker.append(identifier) closure() } } /** Reader Writer pattern with first-in priority semantics. Reads occur concurrently and writes serially. Execution of both read and write is based on first-in semantics of a queue. That is, all reads and writes will occur in the order in which they are added to the queue. This pattern is useful in cases where you want to access data in a fashion consistent with the order of the requests. For example a case where you wanted to update your user interface before a potentially invalidating write operation. If, however, you wish to ensure that writes happen as quickly as possible and/or that any data read is as current as possible, then you may want to consider using the DispatchWriterReader class. The DispatchWriterReader class ensures that reads return the most recent data based on their execution time as apposed to their queue order. */ open class DispatchReaderWriter { private var concurrentQueue: DispatchQueue = DispatchQueue(label: "com.cyberdev.Dispatch.readerWriter", attributes: .concurrent) public func read<T>(execute work: () throws -> T) rethrows -> T { try self.concurrentQueue.sync(execute: work) } public func write(execute work: @escaping @convention(block) () -> Swift.Void) { self.concurrentQueue.async(flags: .barrier, execute: work) } } /** This is similar to a reader writer pattern but has write priority semantics. Reads occur concurrently and writes serially. Execution is based on write priotity at execution time. That is, when a write is enqueued all currently executing reads will be allow to complete, however, all pending reads (i.e. reads which have not yet been scheduled) will be held off until all pending writes have completed. Thus if a sequence of writes are enqueued all reads will be held off until the sequence of writes complete. This pattern is useful in situations where race conditions at execution time must be minimized. While this may be useful, or even critical, for some operations please be aware that it can result in long delays, or even starvation, on read. - note: This incurs significantly more overhead than the DispatchReaderWriter class. Its usefulness is likely limited to cases where it is crucial to minimize race conditions when accessing updated data. */ open class DispatchWriterReader { private var writeQueue:DispatchQueue = DispatchQueue(label: "com.cyberdev.Dispatch.writerReader.write") private var readQueue:DispatchQueue = DispatchQueue(label: "com.cyberdev.Dispatch.writerReader.read", attributes: .concurrent) private var readGroup:DispatchGroup = DispatchGroup() public func read<T>(execute work: () throws -> T) rethrows -> T { try self.readQueue.sync { self.readGroup.enter() defer { self.readGroup.leave() } let result:T = try work() return result } } public func write(execute work: @escaping @convention(block) () -> Swift.Void) { readQueue.suspend() self.readGroup.wait() self.writeQueue.async { defer { self.readQueue.resume() } work() } } } ///Generic DispatchReaderWriter class. Useful for thread safe access to a single memeber variable in a class, for example. open class readerWriterType<T> { private var queue:DispatchReaderWriter = DispatchReaderWriter() private var _value:T init(value:T) { _value = value } public var value:T { get { self.queue.read { () -> T in self._value } } set (newElement) { self.queue.write { self._value = newElement } } } } ///Generic DispatchWriterReader class. Useful for thread safe access to a single memeber variable in a class, for example. open class writerReaderType<T> { private var queue:DispatchWriterReader = DispatchWriterReader() private var _value:T init(value:T) { _value = value } public var value:T { get { self.queue.read { () -> T in self._value } } set (newElement) { self.queue.write { self._value = newElement } } } } /** Class representing the concept of a guard in GCD. This would typically be used where one must limit the number of threads accessing a resource or otherwise prevent re-entrancy. This class is, in essence, a semaphore with "no wait" semantics. Rather than waiting for the semaphore to be signaled this class returns immediately with an indication of whether the semaphore was successfully decremented. This is useful in cases where you do not care to reenter an operation that is already in flight, for example. ``` let dataGuard: DispatchGuard = DispatchGuard() func refreshData() { guard dataGuard.enter() else { return } defer { dataGuard.exit() } //safely fetch data here without re-entrancy or unnecessary re-fetch issues } ``` */ open class DispatchGuard { private var semaphore: DispatchSemaphore //Create a DispatchGuard with the number of threads you want to allow simultaneous access. public init(value:Int = 1) { semaphore = DispatchSemaphore(value: value) } /** Attempt to enter the guard. - Returns: True if entry allowed, false if not - Note: If this methods returns true you must call exit() to free the guard statement */ public func enter() -> Bool { semaphore.wait(timeout: .now()) == .success } ///Exit the guard statement. This call must be balanced with successful calls to enter. public func exit() { semaphore.signal() } } /** Class to wrap common use case of a DispatchGuard into a RAII style pattern. ``` let dataGuard:DispatchGuard = DispatchGuard() func refreshData() { guard let _ = DispatchGuardCustodian(dataGuard) else { return } //safely fetch data here without re-entrancy or unnecessary re-fetch issues // the guard will be automatically released when the function exits } ``` */ open class DispatchGuardCustodian { fileprivate var dispatchGuard: DispatchGuard public init?(_ dispatchGuard: DispatchGuard) { guard dispatchGuard.enter() else { return nil } self.dispatchGuard = dispatchGuard } deinit { self.dispatchGuard.exit() } } ///Simple property wrapper to allow atomic access to values. /// /// Queue is assumed to be serial to preserve order of operations. @propertyWrapper struct AtomicAccessor<T> { private class Storage { var value: T init(initialValue: T) { value = initialValue } } private var storage: Storage public var queue: DispatchQueue init (wrappedValue: T, queue: DispatchQueue) { self.queue = queue self.storage = Storage(initialValue: wrappedValue); } var wrappedValue :T { get { queue.sync { self.storage.value } } nonmutating set { queue.async() { self.storage.value = newValue } } } }
apache-2.0
78eeb92485e56c729c5201719f228a75
32.080702
132
0.655919
4.742455
false
false
false
false
kokuyoku82/NumSwift
NumSwift/iOSNumSwiftTests/UtilsTests.swift
1
6379
// // Created by DboyLiao on 4/1/16. // Copyright © 2016 DboyLiao. // import XCTest import NumSwift class iOSUtilityFunctionTests: XCTestCase { func testNormDouble(){ let x:[Double] = [1, 2, 3, 4, 5, 6, 7, 8] let y:[Double] = [8, 7, 6, 5, 4, 3, 2, 1] let answer:[Double] = [8.06225775, 7.28010989, 6.70820393, 6.40312424, 6.40312424, 6.70820393, 7.28010989, 8.06225775] let result = norm(x, y) let (pass, maxDifference) = testAllClose(result, answer, tol: 1e-8) XCTAssert(pass, "maxDiff: \(maxDifference), result: \(result)") } func testNormFloat(){ let x:[Float] = [1, 2, 3, 4, 5, 6, 7, 8] let y:[Float] = [8, 7, 6, 5, 4, 3, 2, 1] let answer:[Float] = [8.06225775, 7.28010989, 6.70820393, 6.40312424, 6.40312424, 6.70820393, 7.28010989, 8.06225775] let result = norm(x, y) let (pass, maxDifference) = testAllClose(result, answer, tol:1e-8) XCTAssert(pass, "maxDiff: \(maxDifference), result: \(result)") } func tesRoundDouble() { let x:[Double] = [1.1, -2.3, 5.6, 2.7, -3.1415926] let answer:[Double] = [1, -2, 5, 2, -3] let result = roundToZero(x) XCTAssert(result == answer, "answer: \(answer), result: \(result)") } func testRoundFloat(){ let x:[Float] = [1.1, -2.3, 5.6, 2.7, -3.1415926] let answer:[Float] = [1, -2, 5, 2, -3] let result = roundToZero(x) XCTAssert(result == answer, "answer: \(answer), result: \(result)") } func testArangeDouble(){ let resultD = arange(5, step:1.0) let answerD:[Double] = [0, 1, 2, 3, 4] XCTAssert(resultD == answerD, "answerD: \(answerD), resultD: \(resultD)") } func testArangeFloat(){ let resultF:[Float] = arange(5, step:Float(1.0)) let answerF:[Float] = [0, 1, 2, 3, 4] XCTAssert(resultF == answerF, "answerF: \(answerF), resultF: \(resultF)") } func testLinspaceDouble(){ let result = linspace(1.0, 10.0, num:10) let answer:[Double] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] XCTAssert(result == answer, "answer: \(answer), result: \(result)") } func testLinspaceFloat(){ let result = linspace(Float(1.0), Float(10.0), num:10) let answer:[Float] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] XCTAssert(result == answer, "answer: \(answer), result: \(result)") } func testMeanDouble(){ let x:[Double] = [1, 2, 3, 4] let result = mean(x) let answer = 2.5 XCTAssert(result == answer, "answer: \(answer), result: \(result)") } func testMeanFloat(){ let x:[Float] = [1, 2, 3, 4] let result = mean(x) let answer:Float = 2.5 XCTAssert(result == answer, "answer: \(answer), result: \(result)") } func testVarianceDouble(){ let x = 1.stride(to: 11, by: 1).map { Double($0) } let result = variance(x) let answer:Double = 8.25 XCTAssert(result == answer, "answer: \(answer), result: \(result)") } func testVarianceFloat(){ let x = 1.stride(to: 11, by: 1).map { Float($0) } let result = variance(x) let answer:Float = 8.25 XCTAssert(result == answer, "answer: \(answer), result: \(result)") } func testStdDouble(){ let x = 1.stride(to: 11, by: 1).map { Double($0) } let result = std(x) let answer:Double = 2.8722813232690143 XCTAssert(result == answer, "answer: \(answer), result: \(result)") } func testStdFloat(){ let x = 1.stride(to: 11, by: 1).map { Float($0) } let result = std(x) let answer:Float = 2.8722813232690143 XCTAssert(result == answer, "answer: \(answer), result: \(result)") } func testNormalizeDouble(){ let x = 1.stride(to:11, by:1).map { Double($0) } let result = normalize(x) let answer:[Double] = [-1.5666989, -1.21854359, -0.87038828, -0.52223297, -0.17407766, 0.17407766, 0.52223297, 0.87038828, 1.21854359, 1.5666989] let tol = 1e-8 let (pass, maxDiff) = testAllClose(result, answer, tol:tol) XCTAssert(pass, "tol:\(tol), maxDiff:\(maxDiff)") } func testNormalizeFloat(){ let x = 1.stride(to:11, by:1).map { Float($0) } let result = normalize(x) let answer:[Float] = [-1.5666989, -1.21854359, -0.87038828, -0.52223297, -0.17407766, 0.17407766, 0.52223297, 0.87038828, 1.21854359, 1.5666989] let tol:Float = 1e-6 let (pass, maxDiff) = testAllClose(result, answer, tol:tol) XCTAssert(pass, "tol:\(tol), maxDiff:\(maxDiff)") } func testSplitArray(){ let xd:[Double] = (1...20).map { Double($0) } let xf:[Float] = (1...20).map { Float($0) } let resultD = splitArrayIntoParts(xd, 3) let resultF = splitArrayIntoParts(xf, 3) let answerD:[[Double]] = [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20]].map { $0.map {Double($0)} } let answerF:[[Float]] = [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20]].map { $0.map {Float($0)} } XCTAssert(resultD == answerD, "answerD: \(answerD), resultD: \(resultD)") XCTAssert(resultF == answerF, "answerD: \(answerF), resultD: \(resultF)") } func testLeastPowerOfTwo(){ let result = leastPowerOfTwo(1023) let resultD = leastPowerOfTwo(1023.0) let resultF = leastPowerOfTwo(Float(1023)) let answer = 1024 let answerD:Double = 1024 let answerF:Float = 1024 XCTAssert(result == answer, "answer: \(answer), result: \(result)") XCTAssert(resultD == answerD, "answerD: \(answerD), resultD: \(resultD)") XCTAssert(resultF == answerF, "answerD: \(answerF), resultD: \(resultF)") } }
mit
6bc0e6406dec6f06b4526e8444a62291
32.397906
138
0.51223
3.301242
false
true
false
false
ZamzamInc/ZamzamKit
Tests/ZamzamKitTests/Extensions/BundleTests.swift
1
3105
// // NSBundleTests.swift // ZamzamCore // // Created by Basem Emara on 3/4/16. // Copyright © 2016 Zamzam Inc. All rights reserved. // import XCTest import ZamzamCore class BundleTests: XCTestCase { private let bundle: Bundle = .module } extension BundleTests { func testValuesFromText() { let values = bundle.string(file: "Test.txt") XCTAssert(values == "This is a test. Abc 123.\n") } func testValuesFromPlist() throws { let values = bundle.contents(plist: "Settings.plist") XCTAssertEqual(values["MyString1"] as? String, "My string value 1.") XCTAssertEqual(values["MyNumber1"] as? Int, 123) XCTAssertEqual(values["MyBool1"] as? Bool, false) XCTAssertEqual( values["MyDate1"] as? Date, Date( year: 2016, month: 03, day: 3, hour: 9, minute: 50, timeZone: TimeZone(identifier: "America/Toronto") ) ) } } extension BundleTests { func testArrayFromPlist() { let values: [String] = bundle.array(plist: "Array.plist") XCTAssertEqual(values[safe: 0], "Abc") XCTAssertEqual(values[safe: 1], "Def") XCTAssertEqual(values[safe: 2], "Ghi") } func testArrayModelsFromPlist() { let values: [[String: Any]] = bundle.array(plist: "Things.plist") XCTAssertEqual(values[safe: 0]?["id"] as? Int, 1) XCTAssertEqual(values[safe: 0]?["name"] as? String, "Test 1") XCTAssertEqual(values[safe: 0]?["description"] as? String, "This is a test for 1.") XCTAssertEqual(values[safe: 1]?["id"] as? Int, 2) XCTAssertEqual(values[safe: 1]?["name"] as? String, "Test 2") XCTAssertEqual(values[safe: 1]?["description"] as? String, "This is a test for 2.") XCTAssertEqual(values[safe: 2]?["id"] as? Int, 3) XCTAssertEqual(values[safe: 2]?["name"] as? String, "Test 3") XCTAssertEqual(values[safe: 2]?["description"] as? String, "This is a test for 3.") } } extension BundleTests { func testArrayInDictionaryFromPlist() { let values = bundle.contents(plist: "Settings.plist") let array = values["MyArray1"] as? [Any] let expected: [Any] = [ "My string for array value." as Any, 999 as Any, true as Any ] XCTAssertEqual(array?[safe: 0] as? String, expected[0] as? String) XCTAssertEqual(array?[safe: 1] as? Int, expected[1] as? Int) XCTAssertEqual(array?[safe: 2] as? Bool, expected[2] as? Bool) } func testDictFromPlist() { let values = bundle.contents(plist: "Settings.plist") let dict = values["MyDictionary1"] as? [String: Any] let expected: [String: Any] = [ "id": 7 as Any, "title": "Garden" as Any, "active": true as Any ] XCTAssertEqual(dict?["id"] as? Int, expected["id"] as? Int) XCTAssertEqual(dict?["title"] as? String, expected["title"] as? String) XCTAssertEqual(dict?["active"] as? Bool, expected["active"] as? Bool) } }
mit
bca1cfa0d92871dd0f413f11187b7ab4
32.376344
91
0.594072
3.832099
false
true
false
false
dflax/amazeballs
Legacy Versions/Swift 2.x Version/AmazeBalls/SettingsViewController.swift
1
5548
// // SettingsViewController.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 UIKit import SpriteKit // Declare a delegate protocol to send back the settings values the user selects and to handle cancellation protocol SettingsDelegateProtocol { func settingsViewController(viewController: SettingsViewController, cancelled: Bool) func settingsViewController(viewController: SettingsViewController, gravitySetting: Float, bouncySetting: Float, boundingWallSetting: Bool, accelerometerSetting: Bool, activeBall: Int) } class SettingsViewController:UIViewController, Printable { // UI Widgets to grab their values @IBOutlet weak var gravitySlider: UISlider! @IBOutlet weak var bouncynessSlider: UISlider! @IBOutlet weak var boundingSwitch: UISwitch! @IBOutlet weak var accelerometerSwitch: UISwitch! // Buttons for ball type selections @IBOutlet weak var buttonAmazeBall: UIButton! @IBOutlet weak var buttonBaseball: UIButton! @IBOutlet weak var buttonBasketball: UIButton! @IBOutlet weak var buttonFootball: UIButton! @IBOutlet weak var buttonPumpkin: UIButton! @IBOutlet weak var buttonSoccerBallOne: UIButton! @IBOutlet weak var buttonSoccerBallTwo: UIButton! @IBOutlet weak var buttonRandom: UIButton! // Property to keep track of the active ball var activeBall: Int = 2000 // Delegate to support Clown actions var delegate: SettingsDelegateProtocol? // Support the Printable protocol override var description: String { return "Swettings View Controller" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // If the user taps cancel, call the delegate method to cancel (dismissing the settings view controller) @IBAction func cancelSettingsView() { delegate?.settingsViewController(self, cancelled: true) } // If the user taps save, call the delegate method to save - with all of the widget values @IBAction func saveSetting() { delegate?.settingsViewController(self, gravitySetting: gravitySlider.value, bouncySetting: bouncynessSlider.value, boundingWallSetting: boundingSwitch.on, accelerometerSetting: accelerometerSwitch.on, activeBall: activeBall) } // When user taps on a ball type, clear all selections and update UI to demonstrate which one's been selected, also update the _activeBall value. @IBAction func selectBallType(sender : AnyObject) { // Cast the sender as a Button let senderButton = sender as! UIButton buttonAmazeBall.layer.borderWidth = 0.0 buttonBaseball.layer.borderWidth = 0.0 buttonBasketball.layer.borderWidth = 0.0 buttonFootball.layer.borderWidth = 0.0 buttonPumpkin.layer.borderWidth = 0.0 buttonSoccerBallOne.layer.borderWidth = 0.0 buttonSoccerBallTwo.layer.borderWidth = 0.0 buttonRandom.layer.borderWidth = 0.0 senderButton.layer.borderColor = UIColor(red: 0.0, green: 122.0 / 255.0, blue: 1.0, alpha: 1.0).CGColor senderButton.layer.borderWidth = 1.0 activeBall = sender.tag } // When loading the view, retrieve the prevously set values for the settings and update the switches and sliders accordingly override func viewDidLoad() { super.viewDidLoad() // Set the initial state for the view's value controls let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults() gravitySlider.value = defaults.valueForKey("gravityValue") != nil ? abs(defaults.valueForKey("gravityValue") as! Float) : 9.8 bouncynessSlider.value = defaults.valueForKey("bouncyness") != nil ? defaults.valueForKey("bouncyness") as! Float : 1.0 boundingSwitch.on = defaults.valueForKey("boundingWallSetting") != nil ? defaults.valueForKey("boundingWallSetting") as! Bool : false accelerometerSwitch.on = defaults.valueForKey("accelerometerSetting") != nil ? defaults.valueForKey("accelerometerSetting") as! Bool : false activeBall = defaults.valueForKey("activeBall") != nil ? defaults.valueForKey("activeBall") as! Int : 2000 activeBall = activeBall == 0 ? 2000 : activeBall // Visually show which ball is currently active let currentBallButton = self.view.viewWithTag(activeBall) as! UIButton currentBallButton.layer.borderColor = UIColor(red: 0.0, green: 122.0 / 255.0, blue: 1.0, alpha: 1.0).CGColor currentBallButton.layer.borderWidth = 1.0 currentBallButton.layer.hidden = false } }
mit
4a4267200baa1896f54162a67e4f1456
43.031746
226
0.757931
4.212604
false
false
false
false
google/playhvz
iOS/dev/dev/ViewController.swift
1
4125
// // ViewController.swift // dev // // Created by Evan Ovadia on 6/27/17. // // import UIKit import Firebase import FirebaseAuthUI import FirebaseGoogleAuthUI import Alamofire class MainViewController: UIViewController, FUIAuthDelegate { @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var logoutButton: UIButton! @IBOutlet weak var signingInLabel: UILabel! @IBOutlet weak var userIdLabel: UILabel! @IBOutlet weak var subscribingToNotificationsLabel: UILabel! @IBOutlet weak var registeringUserLabel: UILabel! @IBOutlet weak var registeringDeviceLabel: UILabel! @IBOutlet weak var doneTextView: UITextView! public var resultText: String? { didSet { doneTextView.text = resultText } } public var userId: String? { didSet { userIdLabel.text = "User ID: " + (userId ?? "(none)") } } public var stage: Int = 0 { didSet { print("SETTING STAGE TO ", stage) signingInLabel.isHidden = (stage <= 0) signingInLabel.text = (stage == 1 ? "Signing in..." : "Signed in!") subscribingToNotificationsLabel.isHidden = (stage <= 1) subscribingToNotificationsLabel.text = (stage == 2 ? "Subscribing to notifications..." : "Subscribed to notifications!") registeringUserLabel.isHidden = (stage <= 2) registeringUserLabel.text = (stage == 3 ? "Handshaking with server..." : "Handshaked with server!") registeringDeviceLabel.isHidden = (stage <= 3) registeringDeviceLabel.text = (stage == 4 ? "Registering device with server..." : "Registered device with server!") doneTextView.isHidden = (stage <= 4) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /** @fn authUI:didSignInWithUser:error: @brief Message sent after the sign in process has completed to report the signed in user or error encountered. @param authUI The @c FUIAuth instance sending the message. @param user The signed in user if the sign in attempt was successful. @param error The error that occurred during sign in, if any. */ func authUI(_ authUI: FUIAuth, didSignInWith user: User?, error: Error?) { } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) Auth.auth().addStateDidChangeListener() { (auth, user) in if let user = user { print("User is signed in with uid:", user.uid) self.presentLogout(user: user) } else { print("No user is signed in.") self.presentLoginScreen() } } } fileprivate func presentLoginScreen() { loginButton.isHidden = false logoutButton.isHidden = true } fileprivate func presentLogout(user: User) { loginButton.isHidden = true logoutButton.isHidden = false } @IBAction func doLogin(_ sender: Any) { login(sender: sender) } @IBAction func logout(_ sender: Any) { do { try Auth.auth().signOut() stage = 0 } catch is NSError { resultText = "Error signing out!" } } fileprivate func login(sender: Any) { stage = 1 let authUI = FUIAuth.defaultAuthUI() authUI?.delegate = self let googleAuthUI = FUIGoogleAuth.init(scopes: [kGoogleUserInfoEmailScope]) authUI?.providers = [googleAuthUI]; let authViewController = authUI?.authViewController(); self.present(authViewController!, animated: true, completion: nil) } }
apache-2.0
b1389920802cd679e6c889da23a79c9d
30.015038
101
0.592
4.975875
false
false
false
false
silt-lang/silt
Sources/Mantle/TypeChecker.swift
1
8227
/// TypeChecker.swift /// /// Copyright 2017-2018, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. import Moho import Lithosphere public struct TypeCheckerDebugOptions: OptionSet { public typealias RawValue = UInt32 public let rawValue: UInt32 public init(rawValue: RawValue) { self.rawValue = rawValue } public static let debugMetas = TypeCheckerDebugOptions(rawValue: 1 << 0) public static let debugNormalizedMetas = TypeCheckerDebugOptions(rawValue: 1 << 1) public static let debugConstraints = TypeCheckerDebugOptions(rawValue: 1 << 2) } public final class TypeChecker<PhaseState> { var state: State<PhaseState> let engine: DiagnosticEngine let options: TypeCheckerDebugOptions final class State<S> { fileprivate var signature: Signature fileprivate var environment: Environment var state: S init(_ signature: Signature, _ env: Environment, _ state: S) { self.signature = signature self.environment = env self.state = state } } public convenience init(_ state: PhaseState, _ engine: DiagnosticEngine, options: TypeCheckerDebugOptions = []) { self.init(Signature(), Environment([]), state, engine, options) } init(_ sig: Signature, _ env: Environment, _ state: PhaseState, _ engine: DiagnosticEngine, _ options: TypeCheckerDebugOptions) { self.engine = engine self.options = options self.state = State<PhaseState>(sig, env, state) } public var signature: Signature { return self.state.signature } public var environment: Environment { return self.state.environment } /// FIXME: Try harder, maybe public var wildcardToken: TokenSyntax { return SyntaxFactory.makeUnderscore(presence: .implicit) } /// FIXME: Try harder, maybe public var wildcardName: Name { return Name(name: wildcardToken) } } extension TypeChecker { func underExtendedEnvironment<A>(_ ctx: Context, _ f: () -> A) -> A { let oldS = self.environment.context self.environment.context.append(contentsOf: ctx) let val = f() self.environment.context = oldS return val } func extendEnvironment(_ ctx: Context) { self.environment.context.append(contentsOf: ctx) } func underEmptyEnvironment<A>(_ f : () -> A) -> A { let oldE = self.environment self.state.environment = Environment([]) let val = f() self.state.environment = oldE return val } func underNewScope<A>(_ f: () -> A) -> A { let oldPending = self.environment.context self.environment.scopes.append(.init(self.environment.context, [:])) self.environment.context = [] let result = f() guard let oldScope = self.environment.scopes.popLast() else { fatalError("Scope stack should never be empty") } for key in oldScope.opened.keys { self.signature.removeDefinition(key) } self.environment.context = oldPending return result } func forEachVariable<T>(in ctx: Context, _ f: (Var) -> T) -> [T] { var result = [T]() result.reserveCapacity(ctx.count) for (ix, (n, _)) in zip((0..<ctx.count).reversed(), ctx).reversed() { result.insert(f(Var(n, UInt(ix))), at: 0) } return result } } extension TypeChecker { func addMeta( in ctx: Context, from node: Expr? = nil, expect ty: Type<TT>) -> Term<TT> { let metaTy = self.rollPi(in: ctx, final: ty) let mv = self.signature.addMeta(metaTy, from: node) let metaTm = TT.apply(.meta(mv), []) return self.eliminate(metaTm, self.forEachVariable(in: ctx) { v in return Elim<TT>.apply(TT.apply(.variable(v), [])) }) } } extension TypeChecker { // Roll a Pi type containing all the types in the context, finishing with the // provided type. func rollPi(in ctx: Context, final finalTy: Type<TT>) -> Type<TT> { var type = finalTy for (_, nextTy) in ctx.reversed() { type = TT.pi(nextTy, type) } return type } // Unroll a Pi type into a telescope of names and types and the final type. public func unrollPi( _ t: Type<TT>, _ ns: [Name]? = nil) -> (Telescope<Type<TT>>, Type<TT>) { // FIXME: Try harder, maybe let defaultName = Name(name: SyntaxFactory.makeIdentifier("_")) var tel = Telescope<Type<TT>>() var ty = t var idx = 0 while case let .pi(dm, cd) = self.toWeakHeadNormalForm(ty).ignoreBlocking { defer { idx += 1 } let name = ns?[idx] ?? defaultName ty = cd tel.append((name, dm)) } return (tel, ty) } // Takes a Pi-type and replaces all it's elements with metavariables. func fillPiWithMetas(_ ty: Type<TT>) -> [Term<TT>] { var type = self.toWeakHeadNormalForm(ty).ignoreBlocking var metas = [Term<TT>]() while true { switch type { case let .pi(domain, codomain): let meta = self.addMeta(in: self.environment.asContext, expect: domain) let instCodomain = self.forceInstantiate(codomain, [meta]) type = self.toWeakHeadNormalForm(instCodomain).ignoreBlocking metas.append(meta) case .type: return metas default: fatalError("Expected Pi") } } } } extension TypeChecker { public func openContextualType( _ ctxt: ContextualType, _ args: [Term<TT>]) -> TT { assert(ctxt.telescope.count == args.count) return self.forceInstantiate(ctxt.inside, args) } public func openContextualDefinition( _ ctxt: ContextualDefinition, _ args: [Term<TT>]) -> OpenedDefinition { func openAccessor<T>(_ accessor: T) -> Opened<T, TT> { return Opened<T, TT>(accessor, args) } func openConstant(_ c: Definition.Constant) -> OpenedDefinition.Constant { switch c { case .postulate: return .postulate case let .data(dataCons): return .data(dataCons.map { Opened($0, args) }) case let .record(_, constr, ps): return .record(openAccessor(constr), ps.map(openAccessor)) case let .function(inst): return .function(inst) } } precondition(ctxt.telescope.count == args.count) switch self.forceInstantiate(ctxt.inside, args) { case let .constant(type, constant): return .constant(type, openConstant(constant)) case let .dataConstructor(dataCon, openArgs, type): return .dataConstructor(Opened<QualifiedName, TT>(dataCon, args), openArgs, type) case let .module(names): return .module(names) case let .projection(proj, tyName, ctxType): return .projection(proj, Opened<QualifiedName, TT>(tyName, args), ctxType) } } public func openDefinition( _ name: QualifiedName, _ args: [Term<TT>]) -> Opened<QualifiedName, TT> { let e = self.environment guard let lastBlock = e.scopes.last, e.context.isEmpty else { fatalError() } lastBlock.opened[name] = args return Opened<QualifiedName, TT>(name, args) } public func getOpenedDefinition( _ name: QualifiedName) -> (Opened<QualifiedName, TT>, OpenedDefinition) { func getOpenedArguments(_ name: QualifiedName) -> [TT] { precondition(!self.environment.scopes.isEmpty) var n = self.environment.context.count for block in self.environment.scopes.reversed() { if let args = block.opened[name] { return args.map { return $0.forceApplySubstitution(.weaken(n), self.eliminate) } } else { n += block.context.count } } fatalError() } let args = getOpenedArguments(name) let contextDef = self.signature.lookupDefinition(name)! let def = self.openContextualDefinition(contextDef, args) return (Opened<QualifiedName, TT>(name, args), def) } public func getTypeOfOpenedDefinition(_ t: OpenedDefinition) -> Type<TT> { switch t { case let .constant(ty, _): return ty case let .dataConstructor(_, _, ct): return self.rollPi(in: ct.telescope, final: ct.inside) case let .projection(_, _, ct): return self.rollPi(in: ct.telescope, final: ct.inside) case .module(_): fatalError() } } }
mit
f441e1912c3cb3ff6cd31f3d3eade5f8
29.812734
80
0.645193
3.857009
false
false
false
false
Harry-L/5-3-1
ios-charts-master/Charts/Classes/Data/Implementations/Realm/RealmLineDataSet.swift
2
4643
// // RealmLineDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit import Realm import Realm.Dynamic public class RealmLineDataSet: RealmLineRadarDataSet, ILineChartDataSet { public override func initialize() { circleColors.append(UIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0)) } // MARK: - Data functions and accessors // MARK: - Styling functions and accessors private var _cubicIntensity = CGFloat(0.2) /// Intensity for cubic lines (min = 0.05, max = 1) /// /// **default**: 0.2 public var cubicIntensity: CGFloat { get { return _cubicIntensity } set { _cubicIntensity = newValue if (_cubicIntensity > 1.0) { _cubicIntensity = 1.0 } if (_cubicIntensity < 0.05) { _cubicIntensity = 0.05 } } } /// If true, cubic lines are drawn instead of linear public var drawCubicEnabled = false /// - returns: true if drawing cubic lines is enabled, false if not. public var isDrawCubicEnabled: Bool { return drawCubicEnabled } /// The radius of the drawn circles. public var circleRadius = CGFloat(8.0) public var circleColors = [UIColor]() /// - returns: the color at the given index of the DataSet's circle-color array. /// Performs a IndexOutOfBounds check by modulus. public func getCircleColor(var index: Int) -> UIColor? { let size = circleColors.count index = index % size if (index >= size) { return nil } return circleColors[index] } /// Sets the one and ONLY color that should be used for this DataSet. /// Internally, this recreates the colors array and adds the specified color. public func setCircleColor(color: UIColor) { circleColors.removeAll(keepCapacity: false) circleColors.append(color) } /// Resets the circle-colors array and creates a new one public func resetCircleColors(index: Int) { circleColors.removeAll(keepCapacity: false) } /// If true, drawing circles is enabled public var drawCirclesEnabled = true /// - returns: true if drawing circles for this DataSet is enabled, false if not public var isDrawCirclesEnabled: Bool { return drawCirclesEnabled } /// The color of the inner circle (the circle-hole). public var circleHoleColor = UIColor.whiteColor() /// True if drawing circles for this DataSet is enabled, false if not public var drawCircleHoleEnabled = true /// - returns: true if drawing the circle-holes is enabled, false if not. public var isDrawCircleHoleEnabled: Bool { return drawCircleHoleEnabled } /// This is how much (in pixels) into the dash pattern are we starting from. public var lineDashPhase = CGFloat(0.0) /// This is the actual dash pattern. /// I.e. [2, 3] will paint [-- -- ] /// [1, 3, 4, 2] will paint [- ---- - ---- ] public var lineDashLengths: [CGFloat]? /// formatter for customizing the position of the fill-line private var _fillFormatter: ChartFillFormatter = BarLineChartFillFormatter() /// Sets a custom FillFormatter to the chart that handles the position of the filled-line for each DataSet. Set this to null to use the default logic. public var fillFormatter: ChartFillFormatter? { get { return _fillFormatter } set { if newValue == nil { _fillFormatter = BarLineChartFillFormatter() } else { _fillFormatter = newValue! } } } // MARK: NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! RealmLineDataSet copy.circleColors = circleColors copy.circleRadius = circleRadius copy.cubicIntensity = cubicIntensity copy.lineDashPhase = lineDashPhase copy.lineDashLengths = lineDashLengths copy.drawCirclesEnabled = drawCirclesEnabled copy.drawCubicEnabled = drawCubicEnabled return copy } }
mit
2c320f0fa973d4c7159f089a1538c029
28.96129
154
0.611243
4.882229
false
false
false
false
sammyd/UnleashingSwift_bristech2015
UnleashingSwift.playground/Pages/MoreAdvanced.xcplaygroundpage/Contents.swift
1
2343
//: [Previous](@previous) //: # Moving Forward //: ## Enums //: Raw Values enum Activity: String { case Running case Swimming case Cycling } let cycling = Activity.Cycling.rawValue let swimming = Activity.init(rawValue: "Swimming") //: Associated Values enum BillingItem { case PhoneCall(minutes: Int) case Data(bytes: Int) case SMS(number: Int) } let text = BillingItem.SMS(number: 34) let call = BillingItem.PhoneCall(minutes: 10) //: Recursive enum ArithmeticExpression { case Number(Int) indirect case Addition(ArithmeticExpression, ArithmeticExpression) indirect case Multiplication(ArithmeticExpression, ArithmeticExpression) } let seven = ArithmeticExpression.Number(6) let two = ArithmeticExpression.Number(2) let sum = ArithmeticExpression.Addition(seven, two) let product = ArithmeticExpression.Multiplication(sum, ArithmeticExpression.Number(3)) //: ## Pattern Matching func evaluate(expresion: ArithmeticExpression) -> Int { switch expresion { case .Number(let value): return value case .Addition(let left, let right): return evaluate(left) + evaluate(right) case .Multiplication(let left, let right): return evaluate(left) * evaluate(right) } } evaluate(product) func greeting(name: String) -> String { switch name { case "Dave": return "Pretty sure you still don't exist" case "Sam": return "Hi handsome" default: return "Hello \(name)" } } greeting("Dave") greeting("Sam") greeting("Esme") //: ## Optionals let names = ["Anna", "Brian", "Charlie", "Esme"] func findIndexOfName(name: String) -> Int? { for (index, testName) in names.enumerate() { if testName == name { return index } } return .None } findIndexOfName("Anna") findIndexOfName("Dave") let flatNumbers = ["12A", "1", "1234", "56"] if let annasIndex = findIndexOfName("Anna") { flatNumbers[annasIndex] } func leaveMailFor(name: String) -> String { guard let nameIndex = findIndexOfName(name) else { return "Please leave mail at reception" } return "Leave mail for \(name) at \(flatNumbers[nameIndex])" } leaveMailFor("Dave") //: ## Protocols protocol Ordered { func precedes(other: Self) -> Bool } class Number : Ordered { var value: Double = 0 func precedes(other: Number) -> Bool { return value < other.value } } //: [Next](@next)
mit
40afdd3e2305ae50e154406117d7c293
18.525
94
0.694836
3.678179
false
false
false
false
tombuildsstuff/swiftcity
SwiftCity/Entities/BuildTrigger.swift
1
573
public struct BuildTrigger { public let id: String public let type: String public let properties: Parameters init?(dictionary: [String: AnyObject]) { guard let id = dictionary["id"] as? String, let type = dictionary["type"] as? String, let propertiesDictionary = dictionary["properties"] as? [String: AnyObject], let properties = Parameters(dictionary: propertiesDictionary) else { return nil } self.id = id self.type = type self.properties = properties } }
mit
4f77e3134740de4d9e2fb29a70676425
29.157895
88
0.605585
4.939655
false
false
false
false
russelhampton05/MenMew
App Prototypes/Test_004_QRScanner/Test_004_QRScanner/Test_004_QRScanner/MainMenuViewController.swift
1
1926
// // MainMenuViewController.swift // Test_004_QRScanner // // Created by Jon Calanio on 9/17/16. // Copyright © 2016 Jon Calanio. All rights reserved. // import UIKit class MainMenuViewController: UITableViewController { @IBOutlet var openButton: UIBarButtonItem! var categoryArray: [(name: String, desc: String)] = [(name: "Breakfast", desc: "The best way to start your day."), (name: "Lunch", desc: "Dine in with our delectable entrees."), (name: "Specials", desc: "Our signature dishes."), (name: "Drinks", desc: "Refresh youself.")] var restaurant: String? @IBOutlet weak var restaurantLabel: UINavigationItem! override func viewDidLoad() { super.viewDidLoad() restaurantLabel.title = restaurant self.navigationItem.setHidesBackButton(true, animated: false) tableView.sectionHeaderHeight = 70 tableView.estimatedRowHeight = 44 tableView.rowHeight = UITableViewAutomaticDimension self.view.addGestureRecognizer(revealViewController().panGestureRecognizer()) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(("MenuCell")) as UITableViewCell! cell.textLabel!.text = categoryArray[indexPath.row].name cell.detailTextLabel!.text = categoryArray[indexPath.row].desc return cell } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return categoryArray.count } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } }
mit
e034d6d75d2d04b301fac84a3e1c9867
31.083333
276
0.673247
5.392157
false
false
false
false
dduan/swift
test/SILGen/indirect_enum.swift
2
20239
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s indirect enum TreeA<T> { case Nil case Leaf(T) case Branch(left: TreeA<T>, right: TreeA<T>) } // CHECK-LABEL: sil hidden @_TF13indirect_enum11TreeA_casesurFTx1lGOS_5TreeAx_1rGS0_x__T_ func TreeA_cases<T>(t: T, l: TreeA<T>, r: TreeA<T>) { // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type // CHECK-NEXT: [[NIL:%.*]] = enum $TreeA<T>, #TreeA.Nil!enumelt // CHECK-NEXT: release_value [[NIL]] let _ = TreeA<T>.Nil // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type // CHECK-NEXT: [[BOX:%.*]] = alloc_box $T // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: copy_addr %0 to [initialization] [[PB]] // CHECK-NEXT: [[LEAF:%.*]] = enum $TreeA<T>, #TreeA.Leaf!enumelt.1, [[BOX]] // CHECK-NEXT: release_value [[LEAF]] let _ = TreeA<T>.Leaf(t) // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeA<T>.Type // CHECK-NEXT: [[BOX:%.*]] = alloc_box $(left: TreeA<T>, right: TreeA<T>) // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]] : $*(left: TreeA<T>, right: TreeA<T>), 0 // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]] : $*(left: TreeA<T>, right: TreeA<T>), 1 // CHECK-NEXT: retain_value %1 // CHECK-NEXT: store %1 to [[LEFT]] // CHECK-NEXT: retain_value %2 // CHECK-NEXT: store %2 to [[RIGHT]] // CHECK-NEXT: [[BRANCH:%.*]] = enum $TreeA<T>, #TreeA.Branch!enumelt.1, [[BOX]] // CHECK-NEXT: release_value [[BRANCH]] // CHECK-NEXT: release_value %2 // CHECK-NEXT: release_value %1 // CHECK-NEXT: destroy_addr %0 let _ = TreeA<T>.Branch(left: l, right: r) // CHECK: return } // CHECK-LABEL: sil hidden @_TF13indirect_enum16TreeA_reabstractFFSiSiT_ func TreeA_reabstract(f: Int -> Int) { // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeA<Int -> Int>.Type // CHECK-NEXT: [[BOX:%.*]] = alloc_box $@callee_owned (@in Int) -> @out Int // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: strong_retain %0 // CHECK: [[THUNK:%.*]] = function_ref @_TTRXFo_dSi_dSi_XFo_iSi_iSi_ // CHECK-NEXT: [[FN:%.*]] = partial_apply [[THUNK]](%0) // CHECK-NEXT: store [[FN]] to [[PB]] // CHECK-NEXT: [[LEAF:%.*]] = enum $TreeA<Int -> Int>, #TreeA.Leaf!enumelt.1, [[BOX]] // CHECK-NEXT: release_value [[LEAF]] // CHECK-NEXT: strong_release %0 // CHECK: return let _ = TreeA<Int -> Int>.Leaf(f) } enum TreeB<T> { case Nil case Leaf(T) indirect case Branch(left: TreeB<T>, right: TreeB<T>) } // CHECK-LABEL: sil hidden @_TF13indirect_enum11TreeB_casesurFTx1lGOS_5TreeBx_1rGS0_x__T_ func TreeB_cases<T>(t: T, l: TreeB<T>, r: TreeB<T>) { // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type // CHECK: [[NIL:%.*]] = alloc_stack $TreeB<T> // CHECK-NEXT: inject_enum_addr [[NIL]] : $*TreeB<T>, #TreeB.Nil!enumelt // CHECK-NEXT: destroy_addr [[NIL]] // CHECK-NEXT: dealloc_stack [[NIL]] let _ = TreeB<T>.Nil // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type // CHECK-NEXT: [[LEAF:%.*]] = alloc_stack $TreeB<T> // CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[LEAF]] : $*TreeB<T>, #TreeB.Leaf!enumelt.1 // CHECK-NEXT: copy_addr %0 to [initialization] [[PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[LEAF]] : $*TreeB<T>, #TreeB.Leaf!enumelt // CHECK-NEXT: destroy_addr [[LEAF]] // CHECK-NEXT: dealloc_stack [[LEAF]] let _ = TreeB<T>.Leaf(t) // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeB<T>.Type // CHECK-NEXT: [[BOX:%.*]] = alloc_box $(left: TreeB<T>, right: TreeB<T>) // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: copy_addr %1 to [initialization] [[LEFT]] : $*TreeB<T> // CHECK-NEXT: copy_addr %2 to [initialization] [[RIGHT]] : $*TreeB<T> // CHECK-NEXT: [[BRANCH:%.*]] = alloc_stack $TreeB<T> // CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[BRANCH]] // CHECK-NEXT: store [[BOX]] to [[PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[BRANCH]] : $*TreeB<T>, #TreeB.Branch!enumelt.1 // CHECK-NEXT: destroy_addr [[BRANCH]] // CHECK-NEXT: dealloc_stack [[BRANCH]] // CHECK-NEXT: destroy_addr %2 // CHECK-NEXT: destroy_addr %1 // CHECK-NEXT: destroy_addr %0 let _ = TreeB<T>.Branch(left: l, right: r) // CHECK: return } // CHECK-LABEL: sil hidden @_TF13indirect_enum13TreeInt_casesFTSi1lOS_7TreeInt1rS0__T_ : $@convention(thin) (Int, @owned TreeInt, @owned TreeInt) -> () func TreeInt_cases(t: Int, l: TreeInt, r: TreeInt) { // CHECK: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type // CHECK-NEXT: [[NIL:%.*]] = enum $TreeInt, #TreeInt.Nil!enumelt // CHECK-NEXT: release_value [[NIL]] let _ = TreeInt.Nil // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type // CHECK-NEXT: [[LEAF:%.*]] = enum $TreeInt, #TreeInt.Leaf!enumelt.1, %0 // CHECK-NEXT: release_value [[LEAF]] let _ = TreeInt.Leaf(t) // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin TreeInt.Type // CHECK-NEXT: [[BOX:%.*]] = alloc_box $(left: TreeInt, right: TreeInt) // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PB]] // CHECK-NEXT: retain_value %1 // CHECK-NEXT: store %1 to [[LEFT]] // CHECK-NEXT: retain_value %2 // CHECK-NEXT: store %2 to [[RIGHT]] // CHECK-NEXT: [[BRANCH:%.*]] = enum $TreeInt, #TreeInt.Branch!enumelt.1, [[BOX]] // CHECK-NEXT: release_value [[BRANCH]] // CHECK-NEXT: release_value %2 // CHECK-NEXT: release_value %1 let _ = TreeInt.Branch(left: l, right: r) // CHECK: return } enum TreeInt { case Nil case Leaf(Int) indirect case Branch(left: TreeInt, right: TreeInt) } enum TrivialButIndirect { case Direct(Int) indirect case Indirect(Int) } func a() {} func b<T>(x: T) {} func c<T>(x: T, _ y: T) {} func d() {} // CHECK-LABEL: sil hidden @_TF13indirect_enum11switchTreeA func switchTreeA<T>(x: TreeA<T>) { // -- x +2 // CHECK: retain_value %0 // CHECK: switch_enum %0 : $TreeA<T> switch x { // CHECK: bb{{.*}}: // CHECK: function_ref @_TF13indirect_enum1aFT_T_ case .Nil: a() // CHECK: bb{{.*}}([[LEAF_BOX:%.*]] : $@box T): // CHECK: [[VALUE:%.*]] = project_box [[LEAF_BOX]] // CHECK: copy_addr [[VALUE]] to [initialization] [[X:%.*]] : $*T // CHECK: function_ref @_TF13indirect_enum1b // CHECK: destroy_addr [[X]] // CHECK: dealloc_stack [[X]] // -- x +1 // CHECK: strong_release [[LEAF_BOX]] // CHECK: br [[OUTER_CONT:bb[0-9]+]] case .Leaf(let x): b(x) // CHECK: bb{{.*}}([[NODE_BOX:%.*]] : $@box (left: TreeA<T>, right: TreeA<T>)): // CHECK: [[TUPLE_ADDR:%.*]] = project_box [[NODE_BOX]] // CHECK: [[TUPLE:%.*]] = load [[TUPLE_ADDR]] // CHECK: [[LEFT:%.*]] = tuple_extract [[TUPLE]] {{.*}}, 0 // CHECK: [[RIGHT:%.*]] = tuple_extract [[TUPLE]] {{.*}}, 1 // CHECK: switch_enum [[RIGHT]] {{.*}}, default [[FAIL_RIGHT:bb[0-9]+]] // CHECK: bb{{.*}}([[RIGHT_LEAF_BOX:%.*]] : $@box T): // CHECK: [[RIGHT_LEAF_VALUE:%.*]] = project_box [[RIGHT_LEAF_BOX]] // CHECK: switch_enum [[LEFT]] {{.*}}, default [[FAIL_LEFT:bb[0-9]+]] // CHECK: bb{{.*}}([[LEFT_LEAF_BOX:%.*]] : $@box T): // CHECK: [[LEFT_LEAF_VALUE:%.*]] = project_box [[LEFT_LEAF_BOX]] // CHECK: copy_addr [[LEFT_LEAF_VALUE]] // CHECK: copy_addr [[RIGHT_LEAF_VALUE]] // -- x +1 // CHECK: strong_release [[NODE_BOX]] // CHECK: br [[OUTER_CONT]] // CHECK: [[FAIL_LEFT]]: // CHECK: br [[DEFAULT:bb[0-9]+]] // CHECK: [[FAIL_RIGHT]]: // CHECK: br [[DEFAULT]] case .Branch(.Leaf(let x), .Leaf(let y)): c(x, y) // CHECK: [[DEFAULT]]: // -- x +1 // CHECK: release_value %0 default: d() } // CHECK: [[OUTER_CONT:%.*]]: // -- x +0 // CHECK: release_value %0 : $TreeA<T> } // CHECK-LABEL: sil hidden @_TF13indirect_enum11switchTreeB func switchTreeB<T>(x: TreeB<T>) { // CHECK: copy_addr %0 to [initialization] [[SCRATCH:%.*]] : // CHECK: switch_enum_addr [[SCRATCH]] switch x { // CHECK: bb{{.*}}: // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] // CHECK: function_ref @_TF13indirect_enum1aFT_T_ // CHECK: br [[OUTER_CONT:bb[0-9]+]] case .Nil: a() // CHECK: bb{{.*}}: // CHECK: copy_addr [[SCRATCH]] to [initialization] [[LEAF_COPY:%.*]] : // CHECK: [[LEAF_ADDR:%.*]] = unchecked_take_enum_data_addr [[LEAF_COPY]] // CHECK: copy_addr [take] [[LEAF_ADDR]] to [initialization] [[LEAF:%.*]] : // CHECK: function_ref @_TF13indirect_enum1b // CHECK: destroy_addr [[LEAF]] // CHECK: dealloc_stack [[LEAF]] // CHECK-NOT: destroy_addr [[LEAF_COPY]] // CHECK: dealloc_stack [[LEAF_COPY]] // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] // CHECK: br [[OUTER_CONT]] case .Leaf(let x): b(x) // CHECK: bb{{.*}}: // CHECK: copy_addr [[SCRATCH]] to [initialization] [[TREE_COPY:%.*]] : // CHECK: [[TREE_ADDR:%.*]] = unchecked_take_enum_data_addr [[TREE_COPY]] // -- box +1 immutable // CHECK: [[BOX:%.*]] = load [[TREE_ADDR]] // CHECK: [[TUPLE:%.*]] = project_box [[BOX]] // CHECK: [[LEFT:%.*]] = tuple_element_addr [[TUPLE]] // CHECK: [[RIGHT:%.*]] = tuple_element_addr [[TUPLE]] // CHECK: switch_enum_addr [[RIGHT]] {{.*}}, default [[RIGHT_FAIL:bb[0-9]+]] // CHECK: bb{{.*}}: // CHECK: copy_addr [[RIGHT]] to [initialization] [[RIGHT_COPY:%.*]] : // CHECK: [[RIGHT_LEAF:%.*]] = unchecked_take_enum_data_addr [[RIGHT_COPY]] : $*TreeB<T>, #TreeB.Leaf // CHECK: switch_enum_addr [[LEFT]] {{.*}}, default [[LEFT_FAIL:bb[0-9]+]] // CHECK: bb{{.*}}: // CHECK: copy_addr [[LEFT]] to [initialization] [[LEFT_COPY:%.*]] : // CHECK: [[LEFT_LEAF:%.*]] = unchecked_take_enum_data_addr [[LEFT_COPY]] : $*TreeB<T>, #TreeB.Leaf // CHECK: copy_addr [take] [[LEFT_LEAF]] to [initialization] [[X:%.*]] : // CHECK: copy_addr [take] [[RIGHT_LEAF]] to [initialization] [[Y:%.*]] : // CHECK: function_ref @_TF13indirect_enum1c // CHECK: destroy_addr [[Y]] // CHECK: dealloc_stack [[Y]] // CHECK: destroy_addr [[X]] // CHECK: dealloc_stack [[X]] // CHECK-NOT: destroy_addr [[LEFT_COPY]] // CHECK: dealloc_stack [[LEFT_COPY]] // CHECK-NOT: destroy_addr [[RIGHT_COPY]] // CHECK: dealloc_stack [[RIGHT_COPY]] // -- box +0 // CHECK: strong_release [[BOX]] // CHECK-NOT: destroy_addr [[TREE_COPY]] // CHECK: dealloc_stack [[TREE_COPY]] // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] case .Branch(.Leaf(let x), .Leaf(let y)): c(x, y) // CHECK: [[LEFT_FAIL]]: // CHECK: destroy_addr [[RIGHT_LEAF]] // CHECK-NOT: destroy_addr [[RIGHT_COPY]] // CHECK: dealloc_stack [[RIGHT_COPY]] // CHECK: strong_release [[BOX]] // CHECK-NOT: destroy_addr [[TREE_COPY]] // CHECK: dealloc_stack [[TREE_COPY]] // CHECK: br [[INNER_CONT:bb[0-9]+]] // CHECK: [[RIGHT_FAIL]]: // CHECK: strong_release [[BOX]] // CHECK-NOT: destroy_addr [[TREE_COPY]] // CHECK: dealloc_stack [[TREE_COPY]] // CHECK: br [[INNER_CONT:bb[0-9]+]] // CHECK: [[INNER_CONT]]: // CHECK: destroy_addr [[SCRATCH]] // CHECK: dealloc_stack [[SCRATCH]] // CHECK: function_ref @_TF13indirect_enum1dFT_T_ // CHECK: br [[OUTER_CONT]] default: d() } // CHECK: [[OUTER_CONT]]: // CHECK: destroy_addr %0 } // CHECK-LABEL: sil hidden @_TF13indirect_enum10guardTreeA func guardTreeA<T>(tree: TreeA<T>) { do { // CHECK: retain_value %0 // CHECK: switch_enum %0 : $TreeA<T>, case #TreeA.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: release_value %0 // CHECK: [[YES]]: // CHECK: release_value %0 guard case .Nil = tree else { return } // CHECK: [[X:%.*]] = alloc_stack $T // CHECK: retain_value %0 // CHECK: switch_enum %0 : $TreeA<T>, case #TreeA.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: release_value %0 // CHECK: [[YES]]([[BOX:%.*]] : $@box T): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TMP:%.*]] = alloc_stack // CHECK: copy_addr [[VALUE_ADDR]] to [initialization] [[TMP]] // CHECK: copy_addr [take] [[TMP]] to [initialization] [[X]] // CHECK: strong_release [[BOX]] guard case .Leaf(let x) = tree else { return } // CHECK: retain_value %0 // CHECK: switch_enum %0 : $TreeA<T>, case #TreeA.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: release_value %0 // CHECK: [[YES]]([[BOX:%.*]] : $@box (left: TreeA<T>, right: TreeA<T>)): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TUPLE:%.*]] = load [[VALUE_ADDR]] // CHECK: retain_value [[TUPLE]] // CHECK: [[L:%.*]] = tuple_extract [[TUPLE]] // CHECK: [[R:%.*]] = tuple_extract [[TUPLE]] // CHECK: strong_release [[BOX]] guard case .Branch(left: let l, right: let r) = tree else { return } // CHECK: release_value [[R]] // CHECK: release_value [[L]] // CHECK: destroy_addr [[X]] } do { // CHECK: retain_value %0 // CHECK: switch_enum %0 : $TreeA<T>, case #TreeA.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: release_value %0 // CHECK: [[YES]]: // CHECK: release_value %0 if case .Nil = tree { } // CHECK: [[X:%.*]] = alloc_stack $T // CHECK: retain_value %0 // CHECK: switch_enum %0 : $TreeA<T>, case #TreeA.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: release_value %0 // CHECK: [[YES]]([[BOX:%.*]] : $@box T): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TMP:%.*]] = alloc_stack // CHECK: copy_addr [[VALUE_ADDR]] to [initialization] [[TMP]] // CHECK: copy_addr [take] [[TMP]] to [initialization] [[X]] // CHECK: strong_release [[BOX]] // CHECK: destroy_addr [[X]] if case .Leaf(let x) = tree { } // CHECK: retain_value %0 // CHECK: switch_enum %0 : $TreeA<T>, case #TreeA.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: release_value %0 // CHECK: [[YES]]([[BOX:%.*]] : $@box (left: TreeA<T>, right: TreeA<T>)): // CHECK: [[VALUE_ADDR:%.*]] = project_box [[BOX]] // CHECK: [[TUPLE:%.*]] = load [[VALUE_ADDR]] // CHECK: retain_value [[TUPLE]] // CHECK: [[L:%.*]] = tuple_extract [[TUPLE]] // CHECK: [[R:%.*]] = tuple_extract [[TUPLE]] // CHECK: strong_release [[BOX]] // CHECK: release_value [[R]] // CHECK: release_value [[L]] if case .Branch(left: let l, right: let r) = tree { } } } // CHECK-LABEL: sil hidden @_TF13indirect_enum10guardTreeB func guardTreeB<T>(tree: TreeB<T>) { do { // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: destroy_addr [[TMP]] guard case .Nil = tree else { return } // CHECK: [[X:%.*]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: [[VALUE:%.*]] = unchecked_take_enum_data_addr [[TMP]] // CHECK: copy_addr [take] [[VALUE]] to [initialization] [[X]] // CHECK: dealloc_stack [[TMP]] guard case .Leaf(let x) = tree else { return } // CHECK: [[L:%.*]] = alloc_stack $TreeB // CHECK: [[R:%.*]] = alloc_stack $TreeB // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: [[BOX_ADDR:%.*]] = unchecked_take_enum_data_addr [[TMP]] // CHECK: [[BOX:%.*]] = load [[BOX_ADDR]] // CHECK: [[TUPLE_ADDR:%.*]] = project_box [[BOX]] // CHECK: copy_addr [[TUPLE_ADDR]] to [initialization] [[TUPLE_COPY:%.*]] : // CHECK: [[L_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: copy_addr [take] [[L_COPY]] to [initialization] [[L]] // CHECK: [[R_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: copy_addr [take] [[R_COPY]] to [initialization] [[R]] // CHECK: strong_release [[BOX]] guard case .Branch(left: let l, right: let r) = tree else { return } // CHECK: destroy_addr [[R]] // CHECK: destroy_addr [[L]] // CHECK: destroy_addr [[X]] } do { // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Nil!enumelt: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: destroy_addr [[TMP]] if case .Nil = tree { } // CHECK: [[X:%.*]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Leaf!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: [[VALUE:%.*]] = unchecked_take_enum_data_addr [[TMP]] // CHECK: copy_addr [take] [[VALUE]] to [initialization] [[X]] // CHECK: dealloc_stack [[TMP]] // CHECK: destroy_addr [[X]] if case .Leaf(let x) = tree { } // CHECK: [[L:%.*]] = alloc_stack $TreeB // CHECK: [[R:%.*]] = alloc_stack $TreeB // CHECK: copy_addr %0 to [initialization] [[TMP:%.*]] : // CHECK: switch_enum_addr [[TMP]] : $*TreeB<T>, case #TreeB.Branch!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: destroy_addr [[TMP]] // CHECK: [[YES]]: // CHECK: [[BOX_ADDR:%.*]] = unchecked_take_enum_data_addr [[TMP]] // CHECK: [[BOX:%.*]] = load [[BOX_ADDR]] // CHECK: [[TUPLE_ADDR:%.*]] = project_box [[BOX]] // CHECK: copy_addr [[TUPLE_ADDR]] to [initialization] [[TUPLE_COPY:%.*]] : // CHECK: [[L_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: copy_addr [take] [[L_COPY]] to [initialization] [[L]] // CHECK: [[R_COPY:%.*]] = tuple_element_addr [[TUPLE_COPY]] // CHECK: copy_addr [take] [[R_COPY]] to [initialization] [[R]] // CHECK: strong_release [[BOX]] // CHECK: destroy_addr [[R]] // CHECK: destroy_addr [[L]] if case .Branch(left: let l, right: let r) = tree { } } } func dontDisableCleanupOfIndirectPayload(x: TrivialButIndirect) { // CHECK: switch_enum %0 : $TrivialButIndirect, case #TrivialButIndirect.Direct!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK: [[NO]]: // CHECK: release_value %0 guard case .Direct(let foo) = x else { return } // -- Cleanup isn't necessary on "no" path because .Direct is trivial // CHECK: switch_enum %0 : $TrivialButIndirect, case #TrivialButIndirect.Indirect!enumelt.1: [[YES:bb[0-9]+]], default [[NO:bb[0-9]+]] // CHECK-NOT: [[NO]]: // CHECK: [[YES]]({{.*}}): guard case .Indirect(let bar) = x else { return } }
apache-2.0
ed564dc7421b53c8a40f9db7d710ee82
39.804435
151
0.53392
3.133942
false
false
false
false
russbishop/swift
test/Sema/object_literals_ios.swift
1
1365
// RUN: %target-parse-verify-swift // REQUIRES: OS=ios struct S: _ColorLiteralConvertible { init(colorLiteralRed: Float, green: Float, blue: Float, alpha: Float) {} } let y: S = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1) let y2 = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1) // expected-error{{could not infer type of color literal}} expected-note{{import UIKit to use 'UIColor' as the default color literal type}} let y3 = #colorLiteral(red: 1, bleen: 0, grue: 0, alpha: 1) // expected-error{{cannot convert value of type '(red: Int, bleen: Int, grue: Int, alpha: Int)' to expected argument type '(red: Float, green: Float, blue: Float, alpha: Float)'}} struct I: _ImageLiteralConvertible { init(imageLiteralResourceName: String) {} } let z: I = #imageLiteral(resourceName: "hello.png") let z2 = #imageLiteral(resourceName: "hello.png") // expected-error{{could not infer type of image literal}} expected-note{{import UIKit to use 'UIImage' as the default image literal type}} struct Path: _FileReferenceLiteralConvertible { init(fileReferenceLiteralResourceName: String) {} } let p1: Path = #fileLiteral(resourceName: "what.txt") let p2 = #fileLiteral(resourceName: "what.txt") // expected-error{{could not infer type of file reference literal}} expected-note{{import Foundation to use 'URL' as the default file reference literal type}}
apache-2.0
d078e39780ab7a45042c3373b8163b50
55.875
239
0.727473
3.659517
false
false
false
false
lstn-ltd/lstn-sdk-ios
Lstn/Classes/Article/Article.swift
1
1060
// // Article.swift // Pods // // Created by Dan Halliday on 09/11/2016. // // import Foundation struct Article { let key: ArticleKey let source: URL let audio: URL let image: URL let title: String let author: String let publisher: String } struct ArticleKey { let id: String let source: String let publisher: String } extension Article: Equatable { static func ==(lhs: Article, rhs: Article) -> Bool { return lhs.key == rhs.key && lhs.source == rhs.source && lhs.audio == rhs.audio && lhs.image == rhs.image && lhs.title == rhs.title && lhs.author == rhs.author && lhs.publisher == rhs.publisher } } extension ArticleKey: Equatable { static func ==(lhs: ArticleKey, rhs: ArticleKey) -> Bool { return lhs.id == rhs.id && lhs.publisher == rhs.publisher } } extension ArticleKey: Hashable { var hashValue: Int { return "\(self.id)\(self.source)\(self.publisher)".hashValue } }
mit
d8235cde754e63a13200e4d4747bae2d
15.307692
68
0.576415
3.81295
false
false
false
false
jtbandes/swift
test/decl/ext/generic.swift
5
3339
// RUN: %target-typecheck-verify-swift protocol P1 { associatedtype AssocType } protocol P2 : P1 { } protocol P3 { } struct X<T : P1, U : P2, V> { struct Inner<A, B : P3> { } struct NonGenericInner { } } extension Int : P1 { typealias AssocType = Int } extension Double : P2 { typealias AssocType = Double } extension X<Int, Double, String> { } // expected-error{{constrained extension must be declared on the unspecialized generic type 'X' with constraints specified by a 'where' clause}} // Lvalue check when the archetypes are not the same. struct LValueCheck<T> { let x = 0 } extension LValueCheck { init(newY: Int) { x = 42 } } // Member type references into another extension. struct MemberTypeCheckA<T> { } protocol MemberTypeProto { associatedtype AssocType func foo(_ a: AssocType) init(_ assoc: MemberTypeCheckA<AssocType>) } struct MemberTypeCheckB<T> : MemberTypeProto { func foo(_ a: T) {} typealias Element = T var t1: T } extension MemberTypeCheckB { typealias Underlying = MemberTypeCheckA<T> } extension MemberTypeCheckB { init(_ x: Underlying) { } } extension MemberTypeCheckB { var t2: Element { return t1 } } // rdar://problem/19795284 extension Array { var pairs: [(Element, Element)] { get { return [] } } } // rdar://problem/21001937 struct GenericOverloads<T, U> { var t: T var u: U init(t: T, u: U) { self.t = t; self.u = u } func foo() { } var prop: Int { return 0 } subscript (i: Int) -> Int { return i } } extension GenericOverloads where T : P1, U : P2 { init(t: T, u: U) { self.t = t; self.u = u } func foo() { } var prop: Int { return 1 } subscript (i: Int) -> Int { return i } } extension Array where Element : Hashable { var worseHashEver: Int { var result = 0 for elt in self { result = (result << 1) ^ elt.hashValue } return result } } func notHashableArray<T>(_ x: [T]) { x.worseHashEver // expected-error{{type 'T' does not conform to protocol 'Hashable'}} } func hashableArray<T : Hashable>(_ x: [T]) { // expected-warning @+1 {{unused}} x.worseHashEver // okay } func intArray(_ x: [Int]) { // expected-warning @+1 {{unused}} x.worseHashEver } class GenericClass<T> { } extension GenericClass where T : Equatable { func foo(_ x: T, y: T) -> Bool { return x == y } } func genericClassEquatable<T : Equatable>(_ gc: GenericClass<T>, x: T, y: T) { _ = gc.foo(x, y: y) } func genericClassNotEquatable<T>(_ gc: GenericClass<T>, x: T, y: T) { gc.foo(x, y: y) // expected-error{{type 'T' does not conform to protocol 'Equatable'}} } extension Array where Element == String { } extension GenericClass : P3 where T : P3 { } // expected-error{{extension of type 'GenericClass' with constraints cannot have an inheritance clause}} extension GenericClass where Self : P3 { } // expected-error@-1{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'GenericClass'?}} {{30-34=GenericClass}} // expected-error@-2{{type 'GenericClass<T>' in conformance requirement does not refer to a generic parameter or associated type}} protocol P4 { associatedtype T init(_: T) } protocol P5 { } struct S4<Q>: P4 { init(_: Q) { } } extension S4 where T : P5 {} struct S5<Q> { init(_: Q) { } } extension S5 : P4 {}
apache-2.0
259146b2f93c2a021cddfcc62234c8c0
19.86875
181
0.650195
3.276742
false
false
false
false
BigZhanghan/DouYuLive
DouYuLive/DouYuLive/Classes/Home/View/RecommandCycleView.swift
1
3446
// // RecommandCycleView.swift // DouYuLive // // Created by zhanghan on 2017/10/10. // Copyright © 2017年 zhanghan. All rights reserved. // import UIKit private let CycleCellId = "CycleCellId" class RecommandCycleView: UIView { var cycleTimer : Timer? var cycleModels : [CycleModel]? { didSet { collectionView.reloadData() //设置pageControl pageControl.numberOfPages = cycleModels?.count ?? 0 //默认滚动位置 let indexPath = IndexPath(item: (cycleModels?.count ?? 0) * 100, section: 0) collectionView.scrollToItem(at: indexPath, at: .left, animated: false) //添加定时器 removeCycleTimer() addCycleTimer() } } @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var pageControl: UIPageControl! override func awakeFromNib() { super.awakeFromNib() autoresizingMask = UIViewAutoresizing() collectionView.register(UINib(nibName: "CycleCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: CycleCellId) } override func layoutSubviews() { super.layoutSubviews() let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = collectionView.bounds.size } } extension RecommandCycleView { class func recommandCycleView() -> RecommandCycleView { return Bundle.main.loadNibNamed("RecommandCycleView", owner: nil, options: nil)?.first as! RecommandCycleView } } extension RecommandCycleView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (cycleModels?.count ?? 0) * 10000 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cycleModel = cycleModels?[indexPath.item % cycleModels!.count] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CycleCellId, for: indexPath) as! CycleCollectionViewCell cell.cycleModel = cycleModel return cell } } extension RecommandCycleView : UICollectionViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5 pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (cycleModels?.count ?? 1) } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { removeCycleTimer() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { addCycleTimer() } } extension RecommandCycleView { func addCycleTimer() { cycleTimer = Timer(timeInterval: 3.0, target: self, selector: #selector(self.scrollToNext), userInfo: nil, repeats: true) RunLoop.main.add(cycleTimer!, forMode: RunLoopMode.commonModes) } func removeCycleTimer() { cycleTimer?.invalidate() cycleTimer = nil } @objc private func scrollToNext() { let currentOffsetX = collectionView.contentOffset.x let offsetX = currentOffsetX + collectionView.bounds.width collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true) } }
mit
4b77cbab31124cbb18b7d4ea85502381
31.235849
131
0.668715
5.441083
false
false
false
false
mcjcloud/Show-And-Sell
Show And Sell/HttpRequestManager.swift
1
33885
// // HttpRequestManager.swift // Show And Sell // // Created by Brayden Cloud on 9/23/16. // Copyright © 2016 Brayden Cloud. All rights reserved. // // Defines a set of functions to be be used to make URL requests and manage user, group and item models from the database // import Foundation class HttpRequestManager { public static let SERVER_URL = "http://68.248.214.70:8080/showandsell" //public static let SERVER_URL = "http://192.168.1.107:8080/showandsell" static let requestTimeout = 20.0 // MARK: User // get a user with user id and password static func user(withId id: String, andPassword password: String, completion: @escaping (User?, URLResponse?, Error?) -> Void) { // the url to make the URLRequest to let requestURL = URL(string: "\(SERVER_URL)/api/users/userbyuserid?id=\(id)&password=\(password)") var request = URLRequest(url: requestURL!) request.httpMethod = "GET" request.timeoutInterval = requestTimeout // make the request and call the completion method with the new user let task = URLSession.shared.dataTask(with: request) { data, response, error in completion(User(data: data), response, error) } task.resume() } // get a user with email and password static func user(withEmail email: String, andPassword password: String, completion: @escaping (User?, URLResponse?, Error?) -> Void) { // the request URL let requestURL = URL(string: "\(SERVER_URL)/api/users/userbyemail?email=\(email)&password=\(password)") var request = URLRequest(url: requestURL!) request.httpMethod = "GET" request.timeoutInterval = requestTimeout // make the request for the user, and return it in the completion method let task = URLSession.shared.dataTask(with: request) { data, response, error in completion(User(data: data), response, error) } task.resume() } // POST google user and static func googleUser(email: String, userId: String, firstName: String, lastName: String, completion: @escaping (User?, URLResponse?, Error?) -> Void) { // create the request let requestURL = URL(string: "\(SERVER_URL)/api/users/googleuser") var request = URLRequest(url: requestURL!) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.timeoutInterval = requestTimeout // create the http body let json = ["email":"\(email)", "userId":"\(userId)", "firstName":"\(firstName)", "lastName":"\(lastName)"] let body = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) request.httpBody = body // make request let task = URLSession.shared.dataTask(with: request) { data, response, error in completion(User(data: data), response, error) } task.resume() } // create user request static func post(user: User, completion: @escaping (User?, URLResponse?, Error?) -> Void) { // instance variables let email = user.email let password = user.password let firstName = user.firstName let lastName = user.lastName // check validity of data let pattern = "[a-zA-Z0-9]" let regex = try! NSRegularExpression(pattern: pattern, options: []) if !(numberOfMatches(withRegex: regex, andStrings: password, firstName, lastName, email) > 0) { // call completion, invalid input completion(nil, nil, nil) } // create json of user data in dictionary let json = ["email":"\(email)", "password":"\(password)", "firstName":"\(firstName)", "lastName":"\(lastName)"] let body = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) // create request let requestURL = URL(string: "\(SERVER_URL)/api/users/create") var request = URLRequest(url: requestURL!) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.timeoutInterval = requestTimeout // a JSON of the user to be created. request.httpBody = body // make the request, call the completion method let task = URLSession.shared.dataTask(with: request) { data, response, error in // call the completion, creating a new user object for the user that was just created. completion(User(data: data), response, error) } task.resume() } // update user static func put(user: User, currentPassword: String, completion: @escaping (User?, URLResponse?, Error?) -> Void) { // instance variables let id = user.userId let newEmail = user.email let newPassword = user.password let newFirstName = user.firstName let newLastName = user.lastName let newGroupId = user.groupId // check validity of data let pattern = "[a-zA-Z0-9]" let regex = try! NSRegularExpression(pattern: pattern, options: []) if !(numberOfMatches(withRegex: regex, andStrings: newPassword, newFirstName, newLastName, newEmail) > 0) { // call completion, invalid input completion(nil, nil, nil) } // create json of user data in dictionary let json = ["newEmail":"\(newEmail)", "oldPassword":"\(currentPassword)", "newPassword":"\(newPassword)", "newFirstName":"\(newFirstName)", "newLastName":"\(newLastName)", "newGroupId":"\(newGroupId)"] let body = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) // create request let requestURL = URL(string: "\(SERVER_URL)/api/users/update?id=\(id)") var request = URLRequest(url: requestURL!) request.httpMethod = "PUT" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.timeoutInterval = requestTimeout // a JSON of the user to be created. request.httpBody = body // make the request, call the completion method let task = URLSession.shared.dataTask(with: request) { data, response, error in // call the completion, creating a new user object for the user that was just created. completion(User(data: data), response, error) } task.resume() } // MARK: Group // get a group by its group id. static func group(withId id: String, completion: @escaping (Group?, URLResponse?, Error?) -> Void) { // build request let requestURL = URL(string: "\(SERVER_URL)/api/groups/group?id=\(id)") var request = URLRequest(url: requestURL!) request.httpMethod = "GET" request.timeoutInterval = requestTimeout // create tast let task = URLSession.shared.dataTask(with: request) { data, response, error in // complete the task completion(Group(data: data), response, error) } task.resume() } // get all groups static func groups(completion: @escaping ([Group], URLResponse?, Error?) -> Void) { // setup request let requestURL = URL(string: "\(SERVER_URL)/api/groups/allgroups") var request = URLRequest(url: requestURL!) request.httpMethod = "GET" request.timeoutInterval = requestTimeout let session = URLSession.shared let task = session.dataTask(with: request) { data, response, error in // complete the task completion(Group.groupArray(with: data), response, error) } task.resume() } // GET group by adminId static func group(withAdminId id: String, completion: @escaping (Group?, URLResponse?, Error?) -> Void) { let requestURL = URL(string: "\(SERVER_URL)/api/groups/groupwithadmin?adminId=\(id)") var request = URLRequest(url: requestURL!) request.httpMethod = "GET" request.timeoutInterval = requestTimeout let task = URLSession.shared.dataTask(with: request) { data, response, error in // complete completion(Group(data: data), response, error) } task.resume() } // GET groups within a certain radius of the given coordinates static func groups(inRadius r: Float, fromLatitude lat: Double, longitude long: Double, completion: @escaping ([Group], URLResponse?, Error?) -> Void) { // create request let requestURL = URL(string: "\(SERVER_URL)/api/groups/groupsinradius?radius=\(r)&latitude=\(lat)&longitude=\(long)") var request = URLRequest(url: requestURL!) request.httpMethod = "GET" request.timeoutInterval = requestTimeout let task = URLSession.shared.dataTask(with: request) { data, response, error in completion(Group.groupArray(with: data), response, error) } task.resume() } // GET n closest groups to given coordinates static func groups(n: Int, closestToLatitude lat: Double, longitude long: Double, completion: @escaping ([Group], URLResponse?, Error?) -> Void) { // create request let requestURL = URL(string: "\(SERVER_URL)/api/groups/closestgroups?n=\(n)&latitude=\(lat)&longitude=\(long)") var request = URLRequest(url: requestURL!) request.httpMethod = "GET" request.timeoutInterval = requestTimeout let task = URLSession.shared.dataTask(with: request) { data, response, error in completion(Group.groupArray(with: data), response, error) } task.resume() } // GET search for groups including string static func groups(matching: String, completion: @escaping ([Group], URLResponse?, Error?) -> Void) { let requestURL = URL(string: "\(SERVER_URL)/api/groups/search?name=\(matching)") var request = URLRequest(url: requestURL!) request.httpMethod = "GET" request.timeoutInterval = requestTimeout let task = URLSession.shared.dataTask(with: request) { data, response, error in completion(Group.groupArray(with: data), response, error) } task.resume() } // GET a rating static func rating(forGroupId groupId: String, andUserId userId: String, completion: @escaping (Int?, URLResponse?, Error?) -> Void) { let requestURL = URL(string: "\(SERVER_URL)/api/groups/rating?groupId=\(groupId)&userId=\(userId)") var request = URLRequest(url: requestURL!) request.httpMethod = "GET" request.timeoutInterval = requestTimeout let task = URLSession.shared.dataTask(with: request) { data, response, error in var value: Int? = nil if let data = data, (response as? HTTPURLResponse)?.statusCode == 200 { var json: [String: Any]! do { json = try JSONSerialization.jsonObject(with: data) as! [String: Any] value = json["rating"] as? Int } catch { } } completion(value, response, error) } task.resume() } // POST rate a group static func rateGroup(withId id: String, rating: Int, userId: String, password: String, completion: @escaping (Float?, URLResponse?, Error?) -> Void) { let requestURL = URL(string: "\(SERVER_URL)/api/groups/rategroup?id=\(id)&rating=\(rating)&userId=\(userId)&password=\(password)") var request = URLRequest(url: requestURL!) request.httpMethod = "POST" request.timeoutInterval = requestTimeout let task = URLSession.shared.dataTask(with: request) { data, response, error in var value: Float? = nil if let data = data, (response as? HTTPURLResponse)?.statusCode == 200 { var json: [String: Any]! do { json = try JSONSerialization.jsonObject(with: data) as! [String: Any] value = json["rating"] as? Float } catch { } } // return the new rating completion(value, response, error) } task.resume() } // POST donate money to group static func donateToGroup(withId groupId: String, userId: String, password: String, paymentDetails: (token: String, nonce: String, amount: Double), completion: @escaping ([String: Any], URLResponse?, Error?) -> Void) { let requestURL = URL(string: "\(SERVER_URL)/api/groups/donatetogroup?id=\(groupId)&userId=\(userId)&password=\(password)") var request = URLRequest(url: requestURL!) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.timeoutInterval = requestTimeout // create request body let bodyJson: [String: Any] = ["token":paymentDetails.token, "paymentMethodNonce":paymentDetails.nonce, "amount":paymentDetails.amount] request.httpBody = try! JSONSerialization.data(withJSONObject: bodyJson, options: .prettyPrinted) // create task let task = URLSession.shared.dataTask(with: request) { data, response, error in var json: [String: Any]! do { json = try JSONSerialization.jsonObject(with: data ?? "".data(using: .utf8)!) as! [String: Any] } catch { print("error with returned data from donate") completion([String: Any](), response, error) } if json != nil { completion(json, response, error) } else { completion([String: Any](), response, error) } } task.resume() } // POST group static func post(group: Group, password: String, completion: @escaping (Group?, URLResponse?, Error?) -> Void) { // create the request let requestURL = URL(string: "\(SERVER_URL)/api/groups/create") var request = URLRequest(url: requestURL!) // request properties request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.timeoutInterval = requestTimeout // build body let bodyJson: [String: Any] = ["group":["name":"\(group.name)", "adminId":"\(group.adminId)", "address":"\(group.address)", "routing":"\(group.routing)", "latitude":group.latitude, "longitude":group.longitude, "locationDetail":"\(group.locationDetail)"], "password":"\(password)"] request.httpBody = try! JSONSerialization.data(withJSONObject: bodyJson, options: .prettyPrinted) let task = URLSession.shared.dataTask(with: request) { data, response, error in // complete the request completion(Group(data: data), response, error) } task.resume() } // MARK: Item // get an item by its ID static func item(id: String, completion: @escaping (Item?, URLResponse?, Error?) -> Void) { let requestURL = URL(string: "\(SERVER_URL)/api/items/item?id=\(id)") var request = URLRequest(url: requestURL!) request.httpMethod = "GET" let task = URLSession.shared.dataTask(with: request) { data, response, error in completion(Item(data: data), response, error) } task.resume() } // Get all items in the database. static func items(completion: @escaping ([Item], URLResponse?, Error?) -> Void) { let requestURL = URL(string: "\(SERVER_URL)/api/items/allitems") // url request var request = URLRequest(url: requestURL!) request.httpMethod = "GET" request.timeoutInterval = requestTimeout let task = URLSession.shared.dataTask(with: request) { data, response, error in // call the completion method, giving back the items and teh response completion(Item.itemArray(with: data), response, error) } task.resume() } // get items from a particular group static func items(withGroupId id: String, completion: @escaping ([Item], URLResponse?, Error?) -> Void) { let requestURL = URL(string: "\(SERVER_URL)/api/items/items?groupId=\(id)") // url request var request = URLRequest(url: requestURL!) request.httpMethod = "GET" request.timeoutInterval = requestTimeout let task = URLSession.shared.dataTask(with: request) { data, response, error in // call the completion method, giving back the items and teh response completion(Item.itemArray(with: data), response, error) } task.resume() } // get all approved items in a given range static func allApproved(inRange start: Int, to end: Int, completion: @escaping ([Item], URLResponse?, Error?) -> Void) { let requestURL = URL(string: "\(SERVER_URL)/api/items/allapprovedinrange?start=\(start)&end=\(end)") // request var request = URLRequest(url: requestURL!) request.httpMethod = "GET" request.timeoutInterval = requestTimeout let task = URLSession.shared.dataTask(with: request) { data, response, error in // call the completion handler completion(Item.approvedArray(with: data), response, error) } task.resume() } // get all approved items within a group static func approvedItems(withGroupId id: String, completion: @escaping ([Item], URLResponse?, Error?) -> Void) { let requestURL = URL(string: "\(SERVER_URL)/api/items/approved?groupId=\(id)") // url request var request = URLRequest(url: requestURL!) request.httpMethod = "GET" request.timeoutInterval = requestTimeout let task = URLSession.shared.dataTask(with: request) { data, response, error in // call the completion method, giving back the items and teh response completion(Item.approvedArray(with: data), response, error) } task.resume() } // get all approved items in a group within a certain range static func approvedItems(withGroupId id: String, inRange start: Int, to end: Int, completion: @escaping ([Item], URLResponse?, Error?) -> Void) { let requestURL = URL(string: "\(SERVER_URL)/api/items/approvedinrange?groupId=\(id)&start=\(start)&end=\(end)") // url request var request = URLRequest(url: requestURL!) request.httpMethod = "GET" request.timeoutInterval = requestTimeout let task = URLSession.shared.dataTask(with: request) { data, response, error in // call the completion method, giving back the items and teh response completion(Item.approvedArray(with: data), response, error) } task.resume() } // get a purchase token static func paymentToken(completion: @escaping (String?) -> Void) { let requestURL = URL(string: "\(SERVER_URL)/api/items/paymenttoken") var request = URLRequest(url: requestURL!) request.httpMethod = "GET" // make request let task = URLSession.shared.dataTask(with: request) { data, response, error in if let d = data { completion(String(data: d, encoding: .utf8)) } else { completion(nil) } } task.resume() } // post an item to a group static func post(item: Item, completion: @escaping (Item?, URLResponse?, Error?) -> Void) { // create the request let requestURL = URL(string: "\(SERVER_URL)/api/items/create") var request = URLRequest(url: requestURL!) // request properties request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.timeoutInterval = requestTimeout // build body let bodyJson: [String: String] = ["groupId":"\(item.groupId)", "ownerId":"\(item.ownerId)", "name":"\(item.name)", "price":"\(item.price)", "condition":"\(item.condition)", "description":"\(item.itemDescription)", "thumbnail":"\(item.thumbnail)"] request.httpBody = try! JSONSerialization.data(withJSONObject: bodyJson, options: .prettyPrinted) let task = URLSession.shared.dataTask(with: request) { data, response, error in if let e = error { print("error: \(e)") completion(nil, nil, nil) } // complete the request completion(Item(data: data), response, error) } task.resume() } // update an item to a group static func put(item: Item, itemId: String, adminPassword: String, completion: @escaping (Item?, URLResponse?, Error?) -> Void) { // create the request let requestURL = URL(string: "\(SERVER_URL)/api/items/update?id=\(itemId)&adminPassword=\(adminPassword)") var request = URLRequest(url: requestURL!) // request properties request.httpMethod = "PUT" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.timeoutInterval = requestTimeout // build body let bodyJson: [String: String] = ["newName":"\(item.name)", "newPrice":"\(item.price)", "newCondition":"\(item.condition)", "newDescription":"\(item.itemDescription)", "newThumbnail":"\(item.thumbnail)", "approved":"\(item.approved)"] request.httpBody = try! JSONSerialization.data(withJSONObject: bodyJson, options: .prettyPrinted) let task = URLSession.shared.dataTask(with: request) { data, response, error in // complete the request completion(Item(data: data), response, error) } task.resume() } // delete an item static func delete(itemWithId id: String, password: String, completion: @escaping (Item?, URLResponse?, Error?) -> Void) { let requestURL = URL(string: "\(SERVER_URL)/api/items/delete?id=\(id)&password=\(password)") // url request var request = URLRequest(url: requestURL!) request.httpMethod = "DELETE" request.timeoutInterval = requestTimeout // create task let task = URLSession.shared.dataTask(with: request) { data, response, error in // call the completion method, giving back the items and teh response completion(Item(data: data), response, error) } task.resume() } // buy an item static func buy(itemWithId id: String, userId: String, password: String, paymentDetails: (token: String, nonce: String, amount: Double), completion: @escaping ([String: Any], URLResponse?, Error?) -> Void) { let requestURL = URL(string: "\(SERVER_URL)/api/items/buyitem?id=\(id)&userId=\(userId)&password=\(password)") var request = URLRequest(url: requestURL!) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.timeoutInterval = requestTimeout // create request body let bodyJson: [String: Any] = ["token":paymentDetails.token, "paymentMethodNonce":paymentDetails.nonce, "amount":paymentDetails.amount] request.httpBody = try! JSONSerialization.data(withJSONObject: bodyJson, options: .prettyPrinted) // create task let task = URLSession.shared.dataTask(with: request) { data, response, error in var json: [String: Any]! do { json = try JSONSerialization.jsonObject(with: data ?? "".data(using: .utf8)!) as! [String: Any] } catch { print("error with returned data from BUY") completion([String: Any](), response, error) } completion(json, response, error) } task.resume() } // GET the full size image for an item static func fullImage(forId id: String, completion: @escaping (String?) -> Void) { // TODO: implement after fixed server side } // MARK: Bookmark // get bookmarks for a user with the given ID static func bookmarks(forUserWithId id: String, password: String, completion: @escaping ([Item: String]?, URLResponse?, Error?) -> Void) { let requestURL = URL(string: "\(SERVER_URL)/api/bookmarks/bookmarks?userId=\(id)&password=\(password)") var request = URLRequest(url: requestURL!) request.httpMethod = "GET" request.timeoutInterval = requestTimeout let session = URLSession.shared let task = session.dataTask(with: request) { data, response, error in var json: [[String: Any]]! if let d = data { do { //print("bookmark data: \(String(data: d, encoding: .utf8))") let res = response as? HTTPURLResponse print("response: \(res?.statusCode)") json = try JSONSerialization.jsonObject(with: d) as? [[String: Any]] } catch { print("ERROR CONVERTING BOOKMARK JSON") } } else { print("BOOKMARK DATA NIL") } var bookmarks = [Item: String]() // parse Json into Bookmark dictionary. if let bookmarkArray = json { for bookmark in bookmarkArray { if let bookmarkId = bookmark["bookmarkId"] as? String, let itemDict = bookmark["item"] as? [String: Any] { let item = Item(itemId: itemDict["ssItemId"] as! String, groupId: itemDict["groupId"] as! String, ownerId: itemDict["ownerId"] as! String, name: itemDict["name"] as! String, price: itemDict["price"] as! String, condition: itemDict["condition"] as! String, itemDescription: itemDict["description"] as! String, thumbnail: itemDict["thumbnail"] as! String, approved: itemDict["approved"] as! Bool) bookmarks[item] = bookmarkId } else { print("ERROR PARSING BOOKMARK DICTIONARY") } } } // completion completion(bookmarks, response, error) } task.resume() } // post a bookmark to the server static func post(bookmarkForUserWithId id: String, itemId: String, completion: @escaping ((bookmarkId: String?, itemId: String?, userId: String?), URLResponse?, Error?) -> Void) { // create the request let requestURL = URL(string: "\(SERVER_URL)/api/bookmarks/create?userId=\(id)&itemId=\(itemId)") var request = URLRequest(url: requestURL!) // request properties request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.timeoutInterval = requestTimeout let session = URLSession.shared let task = session.dataTask(with: request) { data, response, error in var json: [String: Any]! do { json = try JSONSerialization.jsonObject(with: data!) as? [String: Any] } catch { print("error parsing resulting json") completion((nil, nil, nil), response, error) } if let bookmarkId = json["ssBookmarkId"] as? String, let itemId = json["itemId"] as? String, let userId = json["userId"] as? String { // completion completion((bookmarkId, userId, itemId), response, error) } else { completion((nil, nil, nil), response, error) } } task.resume() } // delete a bookmark with the given bookmark id static func delete(bookmarkWithId id: String, completion: (((bookmarkId: String?, userId: String?, itemId: String?), URLResponse?, Error?) -> Void)?) { let requestURL = URL(string: "\(SERVER_URL)/api/bookmarks/delete?id=\(id)") var request = URLRequest(url: requestURL!) request.httpMethod = "DELETE" request.timeoutInterval = requestTimeout let session = URLSession.shared let task = session.dataTask(with: request) { data, response, error in var json: [String: Any]! do { json = try JSONSerialization.jsonObject(with: data!) as? [String: Any] } catch { print("Error parsing bookmark") } if let bookmarkId = json["ssBookmarkId"] as? String, let itemId = json["itemId"] as? String, let userId = json["userId"] as? String { // completion completion?((bookmarkId, userId, itemId), response, error) } else { completion?((nil, nil, nil), response, error) } } task.resume() } // get messages for an Item static func messages(forItemId id: String, completion: @escaping ([Message], URLResponse?, Error?) -> Void) { let requestURL = URL(string: "\(SERVER_URL)/api/chat/messages?itemId=\(id)") var request = URLRequest(url: requestURL!) request.httpMethod = "GET" request.timeoutInterval = requestTimeout // create task let task = URLSession.shared.dataTask(with: request) { data, response, error in // complete completion(Message.messageArray(with: data), response, error) } task.resume() } // post a message static func post(messageWithPosterId id: String, posterPassword: String, itemId: String, text: String, completion: @escaping (Message?, URLResponse?, Error?) -> Void) { let requestURL = URL(string: "\(SERVER_URL)/api/chat/create?posterId=\(id)&password=\(posterPassword)") var request = URLRequest(url: requestURL!) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.timeoutInterval = requestTimeout let body = ["itemId":"\(itemId)", "body":"\(text)"] request.httpBody = try! JSONSerialization.data(withJSONObject: body, options: .prettyPrinted) let task = URLSession.shared.dataTask(with: request) { data, response, error in // complete completion(Message(data: data), response, error) } task.resume() } // MARK: Helper static func numberOfMatches(withRegex regex: NSRegularExpression, andStrings strings: String...) -> Int { var matchCount = 0 for string in strings { if regex.numberOfMatches(in: string, options: [], range: NSRange(location: 0, length: string.characters.count)) > 0 { matchCount += 1 } } return matchCount } static func encrypt(_ text: String) -> String { // Caesar shift +1 var result = "" for char in text.utf16 { let u = UnicodeScalar(char + 1)! result += String(Character(u)) } // base64 encode let resultData = result.data(using: .utf8) let encrypted = resultData!.base64EncodedString() // return encrypted return encrypted } static func decrypt(_ text: String) -> String { // convert from base64 let data = Data(base64Encoded: text) var decrypted = "" if let data = data { let decodedString = String(data: data, encoding: .utf8) // caesar shift - 1 for char in (decodedString ?? "").utf16 { let u = UnicodeScalar(char - 1)! decrypted += String(Character(u)) } } // return the decoded string return decrypted } }
apache-2.0
28c67336565c2a81ff6ee5b9d26362ca
41.675063
418
0.58839
4.850272
false
false
false
false
leelili/Alamofire
Source/ParameterEncoding.swift
19
11046
// ParameterEncoding.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // 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 /** HTTP method definitions. See https://tools.ietf.org/html/rfc7231#section-4.3 */ public enum Method: String { case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT } // MARK: ParameterEncoding /** Used to specify the way in which a set of parameters are applied to a URL request. - `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`). - `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same implementation as the `.URL` case, but always applies the encoded result to the URL. - `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. - `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`. - `Custom`: Uses the associated closure value to construct a new request given an existing request and parameters. */ public enum ParameterEncoding { case URL case URLEncodedInURL case JSON case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions) case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?)) /** Creates a URL request by encoding parameters and applying them onto an existing request. - parameter URLRequest: The request to have parameters applied - parameter parameters: The parameters to apply - returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any. */ public func encode( URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSMutableURLRequest, NSError?) { var mutableURLRequest = URLRequest.URLRequest guard let parameters = parameters else { return (mutableURLRequest, nil) } var encodingError: NSError? = nil switch self { case .URL, .URLEncodedInURL: func query(parameters: [String: AnyObject]) -> String { var components: [(String, String)] = [] for key in Array(parameters.keys).sort(<) { let value = parameters[key]! components += queryComponents(key, value) } return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&") } func encodesParametersInURL(method: Method) -> Bool { switch self { case .URLEncodedInURL: return true default: break } switch method { case .GET, .HEAD, .DELETE: return true default: return false } } if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) { if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) { let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) URLComponents.percentEncodedQuery = percentEncodedQuery mutableURLRequest.URL = URLComponents.URL } } else { if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { mutableURLRequest.setValue( "application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type" ) } mutableURLRequest.HTTPBody = query(parameters).dataUsingEncoding( NSUTF8StringEncoding, allowLossyConversion: false ) } case .JSON: do { let options = NSJSONWritingOptions() let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options) mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableURLRequest.HTTPBody = data } catch { encodingError = error as NSError } case .PropertyList(let format, let options): do { let data = try NSPropertyListSerialization.dataWithPropertyList( parameters, format: format, options: options ) mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") mutableURLRequest.HTTPBody = data } catch { encodingError = error as NSError } case .Custom(let closure): (mutableURLRequest, encodingError) = closure(mutableURLRequest, parameters) } return (mutableURLRequest, encodingError) } /** Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. - parameter key: The key of the query component. - parameter value: The value of the query component. - returns: The percent-escaped, URL encoded query string components. */ public func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { components += queryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { for value in array { components += queryComponents("\(key)[]", value) } } else { components.append((escape(key), escape("\(value)"))) } return components } /** Returns a percent-escaped string following RFC 3986 for a query string key or value. RFC 3986 states that the following characters are "reserved" characters. - General Delimiters: ":", "#", "[", "]", "@", "?", "/" - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" should be percent-escaped in the query string. - parameter string: The string to be percent-escaped. - returns: The percent-escaped string. */ public func escape(string: String) -> String { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" let allowedCharacterSet = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet allowedCharacterSet.removeCharactersInString(generalDelimitersToEncode + subDelimitersToEncode) var escaped = "" //========================================================================================================== // // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few // hundred Chinense characters causes various malloc error crashes. To avoid this issue until iOS 8 is no // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more // info, please refer to: // // - https://github.com/Alamofire/Alamofire/issues/206 // //========================================================================================================== if #available(iOS 8.3, OSX 10.10, *) { escaped = string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? string } else { let batchSize = 50 var index = string.startIndex while index != string.endIndex { let startIndex = index let endIndex = index.advancedBy(batchSize, limit: string.endIndex) let range = Range(start: startIndex, end: endIndex) let substring = string.substringWithRange(range) escaped += substring.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? substring index = endIndex } } return escaped } }
mit
8879064256358597b3fff66d1e877b22
43.353414
124
0.592629
5.643332
false
false
false
false
lojals/semanasanta
Semana Santa/Semana Santa/Classes/Connection.swift
1
2484
// // Connection.swift // Yo Intervengo // // Created by Jorge Raul Ovalle Zuleta on 2/5/15. // Copyright (c) 2015 Olinguito. All rights reserved. // import UIKit import Foundation class Connection: NSObject { let db = SQLiteDB.sharedInstance() override init() { super.init() } // GET MONUMENTS func getMonuments() -> NSMutableArray{ var returnArray = NSMutableArray() let data = db.query("SELECT * FROM monuments") for key in data{ var monument: Dictionary<String, String> = [:] if let _id = key["id"] { monument["ID"] = _id.asString() } if let name = key["name"] { monument["NAME"] = name.asString() } if let name = key["subtitle"] { monument["DESCRIPTION"] = name.asString() } if let name = key["pray1"] { monument["PRAY1"] = name.asString() } if let name = key["pray2"] { monument["PRAY2"] = name.asString() } if let name = key["prad"] { monument["PRAY3"] = name.asString() } if let name = key["text3"] { monument["TEXT3"] = name.asString() } returnArray.addObject(monument) } return returnArray } // GET VIACRUSIS func getViaCrusis() -> NSMutableArray{ var returnArray = NSMutableArray() let data = db.query("SELECT * FROM viacrusis") for key in data{ var monument: Dictionary<String, String> = [:] if let _id = key["id_day"] { monument["ID"] = _id.asString() } if let name = key["alias"] { monument["ALIAS"] = name.asString() } if let name = key["name"] { monument["NAME"] = name.asString() } if let name = key["text_day"] { monument["TEXT1"] = name.asString() } if let name = key["prays"] { monument["PRAY1"] = name.asString() } if let name = key["text2_day"] { monument["TEXT2"] = name.asString() } if let name = key["tit"] { monument["TIT"] = name.asString() } returnArray.addObject(monument) } return returnArray } }
gpl-2.0
68a6fb0093c0708cb63d01140383508e
27.883721
58
0.468196
4.231687
false
false
false
false
tadeuzagallo/GithubPulse
widget/GithubPulse/Models/Contributions.swift
2
3547
// // Contributions.swift // GithubPulse // // Created by Tadeu Zagallo on 12/30/14. // Copyright (c) 2014 Tadeu Zagallo. All rights reserved. // import Foundation typealias FetchCallback = ((Bool, [Int], Int, Int) -> Void)! class Contributions { var username = "" var year = [Int]() var commits = [Int]() var today = 0 var streak = 0 var succeeded = false var state = 0 var callback: FetchCallback = nil let streakRegex = try? NSRegularExpression(pattern: "Current streak</span>\\s*<span[^>]*?>(\\d+)\\s*days", options: NSRegularExpressionOptions.CaseInsensitive) let dayRegex = try? NSRegularExpression(pattern: "<rect.*?data-count=\"(\\d+)\"", options: []) class func fetch(username: String, completionBlock: FetchCallback) { Contributions().fetch(username, completionBlock: completionBlock) } private func baseFetch(URLString: String, completionBlock: (String) -> Void) { let url = NSURL(string: URLString) let request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 30) request.HTTPShouldHandleCookies = false NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) in if error != nil || data == nil { self.invokeCallback(false) return } completionBlock(String(data: data!, encoding: NSUTF8StringEncoding)!) } } func fetch(username: String, completionBlock: FetchCallback) { self.username = username self.year = [] self.callback = completionBlock baseFetch("https://github.com/\(username)") { (body) in self.parse(body) } } func fetchContributions() { baseFetch("https://github.com/users/\(username)/contributions") { (body) in let range = self.getRange(body) if range.location == NSNotFound { self.invokeCallback(false) return } self.parseStreak(body, range: range) self.invokeCallback(true) } } private func invokeCallback(success: Bool) { if callback != nil { callback(success, commits, streak, today) } self.callback = nil } private func getRange(input: String) -> NSRange { let start = (input as NSString).rangeOfString("<svg") return NSMakeRange(start.location, (input as NSString).length - start.location) } func parse(string: String) { let range = getRange(string) if range.location == NSNotFound { parseCommits(string, range: NSMakeRange(0, (string as NSString).length)) fetchContributions() return } parseCommits(string, range: range) parseStreak(string, range: range) invokeCallback(true) } func parseStreak(string: String, range: NSRange) { let streakMatch = streakRegex?.firstMatchInString(string, options: [], range: range) if streakMatch != nil { if let streak = Int((string as NSString).substringWithRange(streakMatch!.rangeAtIndex(1))) { self.streak = streak } } } func parseCommits(string: String, range: NSRange) { let dayMatches = dayRegex?.matchesInString(string, options: [], range: range) if dayMatches != nil { var a = 30 for dayMatch in dayMatches!.reverse() { if let day = Int((string as NSString).substringWithRange(dayMatch.rangeAtIndex(1))) { commits.insert(day, atIndex: 0) } if --a == 0 { break } } } if let today = commits.last { self.today = today } } }
mit
40abce40f71f3f877090bebe64af7204
27.845528
161
0.656047
4.212589
false
false
false
false
A752575700/HOMEWORK
Day8_1/Day8_1.playground/Contents.swift
1
4284
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" ////////////////////////////////////////////////////////////// //排序 //时间复杂度--研究重点 ////最好情况(n:12345) 最差情况(n^2/2) 平均情况 ////快排方法:On(log n) ////二分查找:log n // O(n) y=k(x) 线性时间 在12345 // O(n^2) // O(log n) 到后面增长没那么多 //空间复杂度--企业级和科研级 ////////////////////////////////////////////////////////// var NumberList = [11, 25,5 , 5, 2, 78, 23, 15] var NumberList2 = [1, 9, 18, 27 ,35, 77 ,90] var NumberList3 = [1,3] public func FindOne (number: Int) -> Bool { var i = 0 for i in NumberList{ if i == number{ return true } } return false } public func ErfenFind (indexA: Int, indexB: Int, number: Int){ var ifFound = false var middle : Int = (indexB + indexA) / 2 if number == NumberList2[middle]{ ifFound = true println("found") return //return true } else if indexA == indexB{ println("not found") } else if number < NumberList2[middle]{ ErfenFind(indexA, middle - 1, number) } else { ErfenFind(middle + 1, indexB, number) } } //插入排序 public func InsertionSort() { for var i = 0; i < NumberList.count ; i++ { //println("haha") for var k = 0; k < i; k++ { if NumberList[i] < NumberList[k]{ NumberList.insert(NumberList[i], atIndex: k) NumberList.removeAtIndex(i + 1) } } } } //冒泡排序 public func BubbleSort(){ println(NumberList) for var k = 0; k < NumberList.count; k++ { //第一轮结束后最大的已经排在最右边 for var i = 0; i < NumberList.count - k - 1 ; i++ { if NumberList[i] > NumberList[i+1]{ var item = NumberList[i] NumberList[i] = NumberList[i+1] NumberList[i+1] = item println(NumberList) } } } } public func QuickSort(array: Array<Int>) -> Array<Int> { if array.count > 1{ var key = array[0] var less : [Int] = [] var equal : [Int] = [] var more : [Int] = [] for i in array { if i < key { less.append(i) } else if i > key { more.append(i) } else { equal.append(i) } } return (QuickSort(less) + equal + QuickSort(more)) } else{ return array } } public func merge (array1: Array<Int> , array2: Array<Int>) -> Array<Int> { var outcome : [Int] = [] var inarray1 = array1 var inarray2 = array2 while inarray1.count != 0 && inarray2.count != 0 { var item0 = inarray1[0] var item1 = inarray2[0] if item0 > item1{ outcome.append(item1) inarray2.removeAtIndex(0) } else{ outcome.append(item0) inarray1.removeAtIndex(0) } } if inarray1.count == 0 { return outcome + inarray2 } else { return outcome + inarray1 } } //println(merge([1], [2])) //println(merge([1,4,7,8,9,77,99], [0])) public func MergeSort(array: Array<Int>) -> Array<Int> { if array.count > 1{ var array1 : [Int] = [] var array2 : [Int] = [] for var i = 0; i < array.count/2 ; i++ { array1.append(array[i]) } for var i = array.count/2 ; i < array.count ; i++ { array2.append(array[i]) } return merge(MergeSort(array1), MergeSort(array2)) } return array } /* } if ((less.count == 0) && (more.count == 0)) { return equal } else if less.count == 0 { return (equal + QuickSort(more)) } else if more.count == 0 { return (QuickSort(less) + equal) } return (QuickSort(less) + equal + QuickSort(more)) */ //FindOne(7) //FindOne(78) //ErfenFind(0, 6, 9) //ErfenFind(0, 4, 18) //InsertionSort() //BubbleSort() println(MergeSort(NumberList))
mit
ce765bd84beff8cc7021e6d97b800e3d
20.636842
75
0.481752
3.330632
false
false
false
false
icylydia/PlayWithLeetCode
451. Sort Characters By Frequency/Solution.swift
1
493
class Solution { func frequencySort(_ s: String) -> String { var dict = [Character: Int]() for c in s.characters { if let n = dict[c] { dict[c] = n + 1 } else { dict[c] = 1 } } let sortedKeys = dict.keys.sorted{dict[$0]! > dict[$1]!} var ans = "" for key in sortedKeys { for _ in 0..<dict[key]! { ans += String(key) } } return ans } }
mit
cb06ceb0feb52c362bbd980125b927d8
23.7
64
0.409736
3.821705
false
false
false
false
anthonyliao/UICollectionGridView
UICollectionGridView/ViewController.swift
1
3010
// // ViewController.swift // UICollectionGridView // // Created by anthony on 12/23/14. // Copyright (c) 2014 com.anthonyliao. All rights reserved. // import UIKit class ViewController: UIViewController, UICollectionGridViewSortDelegate { var gridViewController: UICollectionGridViewController! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. gridViewController = UICollectionGridViewController() gridViewController.setColumns(["Contact", "Sent", "Received", "Open Rate"]) gridViewController.addRow(["john smith", "100", "88", "10%"]) gridViewController.addRow(["john doe", "23", "16", "81%"]) gridViewController.addRow(["derrick favors", "43", "65", "93%"]) gridViewController.addRow(["jared black", "75", "2", "43%"]) gridViewController.addRow(["james olmos", "43", "12", "33%"]) gridViewController.addRow(["thomas frank", "13", "87", "45%"]) gridViewController.addRow(["laura james", "33", "22", "15%"]) gridViewController.sortDelegate = self view.addSubview(gridViewController.view) } override func viewDidLayoutSubviews() { gridViewController.view.frame = CGRectMake(0, 50, view.frame.width, view.frame.height-60) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func sort(colIndex: Int, asc: Bool, rows: [[AnyObject]]) -> [[AnyObject]] { var sortedRows = rows.sorted { (firstRow: [AnyObject], secondRow: [AnyObject]) -> Bool in var firstRowValue = firstRow[colIndex] as String var secondRowValue = secondRow[colIndex] as String if colIndex == 0 { //If name column, compare lexographically if asc { return firstRowValue < secondRowValue } return firstRowValue > secondRowValue } else if colIndex == 1 || colIndex == 2 { //Else Received/Sent column, compare as integers if asc { return firstRowValue.toInt()! < secondRowValue.toInt()! } return firstRowValue.toInt()! > secondRowValue.toInt()! } //Last column is percent, strip off the % character then compare as integers var firstRowValuePercent = firstRowValue.substringWithRange(Range(start: firstRowValue.startIndex, end: advance(firstRowValue.endIndex, -1))).toInt()! var secondRowValuePercent = secondRowValue.substringWithRange(Range(start: secondRowValue.startIndex, end: advance(secondRowValue.endIndex, -1))).toInt()! if asc { return firstRowValuePercent < secondRowValuePercent } return firstRowValuePercent > secondRowValuePercent } return sortedRows } }
mit
3c850ce40d1253d3323ea8f2a02b2b33
42.623188
166
0.625249
4.725275
false
false
false
false
00aney/Briefinsta
Briefinsta/Sources/Module/TopMost/InstagramMediumCell.swift
1
5105
// // InstagramMediumCell.swift // Briefinsta // // Created by aney on 2017. 10. 28.. // Copyright © 2017년 Ted Kim. All rights reserved. // import UIKit protocol InstagramMediumCellType { func configure(viewModel: InstagramMediaViewModel) } final class InstagramMediumCell: UICollectionViewCell, InstagramMediumCellType { // MARK: Constants fileprivate struct Metric { static let likeImageViewTop: CGFloat = 6.0 static let likeImageViewWidthHeight: CGFloat = 16.0 static let likeLabelLeft: CGFloat = 4.0 static let likeLabelHeight: CGFloat = 16.0 static let commentImageViewTop: CGFloat = 6.0 static let commentImageViewWidthHeight: CGFloat = Font.textLabel.lineHeight static let commentLabelLeft: CGFloat = 4.0 static let commentLabelHeight: CGFloat = Font.textLabel.lineHeight } fileprivate struct Font { static let textLabel = UIFont.systemFont(ofSize: 15) } // MARK: Initializing override init(frame: CGRect) { super.init(frame: frame) self.setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: UI let imageView: UIImageView = { let image = UIImageView() image.contentMode = .scaleAspectFill image.layer.cornerRadius = 8 image.layer.masksToBounds = true image.isHidden = true return image }() let likeImageView: UIImageView = { let image = UIImageView() image.contentMode = .scaleAspectFill image.layer.masksToBounds = true image.tintColor = .red image.image = UIImage(named: "icon-heart")?.withRenderingMode(.alwaysTemplate) image.isHidden = true return image }() let commentImageView: UIImageView = { let image = UIImageView() image.contentMode = .scaleAspectFill image.layer.masksToBounds = true image.tintColor = .bi_charcoal image.image = UIImage(named: "icon-comment")?.withRenderingMode(.alwaysTemplate) image.isHidden = true return image }() let likeLabel: UILabel = { let label = UILabel() label.font = Font.textLabel return label }() let commentLabel: UILabel = { let label = UILabel() label.font = Font.textLabel label.textColor = .bi_slate return label }() fileprivate func setupUI() { self.addSubview(self.imageView) self.addSubview(self.likeImageView) self.addSubview(self.likeLabel) self.addSubview(self.commentImageView) self.addSubview(self.commentLabel) } override func prepareForReuse() { self.imageView.image = UIImage(named: "placeholder") self.commentLabel.text = "" self.likeLabel.text = "" self.imageView.isHidden = true self.likeImageView.isHidden = true self.commentImageView.isHidden = true } // MARK: Configuring func configure(viewModel: InstagramMediaViewModel) { if !viewModel.imageURL.isEmpty { self.imageView.kf.setImage(with: URL(string: viewModel.imageURL)) } else { self.imageView.image = UIImage(named: "placeholder")?.withRenderingMode(.alwaysOriginal) } self.commentLabel.text = "\(viewModel.comments)" self.likeLabel.text = "\(viewModel.likes)" self.imageView.isHidden = false self.likeImageView.isHidden = false self.commentImageView.isHidden = false self.layoutIfNeeded() } // MARK: Layout override func layoutSubviews() { self.imageView.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.width) self.likeImageView.frame = CGRect(x: 0, y: self.frame.width + Metric.likeImageViewTop, width: Metric.likeImageViewWidthHeight, height: Metric.likeImageViewWidthHeight) self.likeLabel.frame = CGRect(x: self.likeImageView.right + Metric.likeLabelLeft, y: self.likeImageView.top, width: self.frame.width - self.likeImageView.right - Metric.likeLabelLeft * 2, height: Metric.likeLabelHeight) self.commentImageView.frame = CGRect(x: 0, y: self.likeImageView.bottom + Metric.commentImageViewTop, width: Metric.commentImageViewWidthHeight, height: Metric.commentImageViewWidthHeight) self.commentLabel.frame = CGRect(x: self.commentImageView.right + Metric.commentLabelLeft, y: self.commentImageView.top, width: self.frame.width - self.commentImageView.right - Metric.commentLabelLeft * 2, height: Metric.commentImageViewWidthHeight) } class func height() -> CGFloat { var height: CGFloat = 0.0 height += Metric.likeImageViewTop + Metric.likeImageViewWidthHeight height += Metric.commentImageViewTop + Metric.commentImageViewWidthHeight return height } }
mit
d399104aa2ea2d53ff2def32b5b4b781
29.550898
121
0.643669
4.795113
false
false
false
false
exshin/PokePuzzler
PokePuzzler/Elements.swift
1
714
// // Elements.swift // CookieCrunch // // Created by Eugene on 12/24/16. // Copyright © 2016 Razeware LLC. All rights reserved. // class Elements: Hashable, CustomStringConvertible { // The Cookies that are part of this chain. var cookies = [Cookie]() enum ChainType: CustomStringConvertible { case horizontal case vertical // Note: add any other shapes you want to detect to this list. //case ChainTypeLShape //case ChainTypeTShape var description: String { switch self { case .horizontal: return "Horizontal" case .vertical: return "Vertical" } } } } func ==(lhs: Chain, rhs: Chain) -> Bool { return lhs.cookies == rhs.cookies }
apache-2.0
9fe09bde7438427a0fabf04530471f89
21.28125
66
0.649369
4.074286
false
false
false
false