repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
jianghongbing/APIReferenceDemo
UIKit/UISplitViewController/UISplitViewController/MasterViewController.swift
1
2416
// // MasterViewController.swift // UISplitViewController // // Created by pantosoft on 2017/6/15. // Copyright © 2017年 jianghongbing. All rights reserved. // import UIKit class MasterViewController: UITableViewController { let colorNames: [(String,UIColor)] = [("red", .red), ("blue", .blue), ("green", .green), ("yellow", .yellow), ("gray", .gray), ("purple", .purple), ("orange", .orange)] let cellIdentifier = "MasterViewCell" override func viewDidLoad() { super.viewDidLoad() title = "masterViewController" tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: cellIdentifier) tableView.tableFooterView = UIView() navigationItem.rightBarButtonItem = UIBarButtonItem(title: "show", style: .plain, target: self, action: #selector(splitControlleShowVC(_:))) } func splitControlleShowVC(_ barButtonItem:UIBarButtonItem) { let colorViewController = ColorViewController() colorViewController.view.backgroundColor = UIColor(colorLiteralRed: Float(arc4random_uniform(255)) / 255.0, green: Float(arc4random_uniform(255)) / 255.0, blue: Float(arc4random_uniform(255)) / 255.0, alpha: 1.0) // show(colorViewController, sender: nil) splitViewController?.show(colorViewController, sender: nil) // showDetailViewController(colorViewController, sender: nil) } // #MARK UITableViewDelegate override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return colorNames.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) cell.textLabel?.text = colorNames[indexPath.row].0 cell.accessoryType = .disclosureIndicator return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let colorViewController = ColorViewController() let color = colorNames[indexPath.row] colorViewController.title = color.0 colorViewController.view.backgroundColor = color.1 let navigationController = UINavigationController(rootViewController: colorViewController) showDetailViewController(navigationController, sender: nil) } }
mit
920af94ed60d3644ac0d13509464ada2
43.685185
220
0.702031
5.037578
false
false
false
false
icylydia/PlayWithLeetCode
19. Remove Nth Node From End of List/solution.swift
1
686
/** * Definition for singly-linked list. * public class ListNode { * public var val: Int * public var next: ListNode? * public init(_ val: Int) { * self.val = val * self.next = nil * } * } */ class Solution { func removeNthFromEnd(head: ListNode?, _ n: Int) -> ListNode? { var index = 0 var rmv: ListNode? = nil var prev: ListNode? = nil var cur = head while(cur != nil) { index++ if(index == n) { rmv = head } else if(index > n) { prev = rmv rmv = rmv?.next } cur = cur?.next } if(prev != nil) { prev!.next = rmv?.next return head } else { return head?.next } } }
mit
f39bc295652b342bc9463fd1da4ff82f
18.628571
65
0.516035
2.8
false
false
false
false
hejunbinlan/RealmResultsController
Example/RealmResultsController/ViewController.swift
1
7202
// // ViewController.swift // RealmResultsController // // Created by Pol Quintana on 5/8/15. // Copyright © 2015 Redbooth. // import Foundation import UIKit import RealmSwift import RealmResultsController class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, RealmResultsControllerDelegate { let tableView: UITableView = UITableView(frame: CGRectZero, style: .Grouped) var rrc: RealmResultsController<TaskModelObject, TaskObject>? var realm: Realm! let button: UIButton = UIButton() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() if let _ = NSClassFromString("XCTest") { return } realm = try! Realm(path: NSBundle.mainBundle().resourcePath! + "/example.realm") try! realm.write { self.realm.deleteAll() } populateDB() let request = RealmRequest<TaskModelObject>(predicate: NSPredicate(value: true), realm: realm, sortDescriptors: [SortDescriptor(property: "projectID") , SortDescriptor(property: "name")]) rrc = try! RealmResultsController<TaskModelObject, TaskObject>(request: request, sectionKeyPath: "projectID", mapper: TaskObject.map) rrc!.delegate = self rrc!.performFetch() setupSubviews() } func populateDB() { try! realm.write { for i in 1...2 { let task = TaskModelObject() task.id = i task.name = "Task-\(i)" task.projectID = 0 let user = UserObject() user.id = i user.name = String(Int(arc4random_uniform(1000))) task.user = user self.realm.add(task) } for i in 3...4 { let task = TaskModelObject() task.id = i task.name = "Task-\(i)" task.projectID = 1 let user = UserObject() user.id = i user.name = String(Int(arc4random_uniform(1000))) task.user = user self.realm.add(task) } for i in 5...6 { let task = TaskModelObject() task.id = i task.name = "Task-\(i)" task.projectID = 2 let user = UserObject() user.id = i user.name = String(Int(arc4random_uniform(1000))) task.user = user self.realm.add(task) } } } func setupSubviews() { let height: CGFloat = 50 button.frame = CGRectMake(0, view.frame.height - height, view.frame.width, height) button.backgroundColor = UIColor.redColor() button.setTitle("Add Row", forState: .Normal) button.addTarget(self, action: "addNewObject", forControlEvents: .TouchUpInside) view.addSubview(button) tableView.frame = CGRectMake(0, 0, view.frame.width, view.frame.height - height) tableView.delegate = self tableView.dataSource = self view.addSubview(tableView) } func addNewObject() { let projectID = Int(arc4random_uniform(3)) try! realm.write { let task = TaskModelObject() task.id = Int(arc4random_uniform(9999)) task.name = "Task-\(task.id)" task.projectID = projectID let user = UserObject() user.id = task.id user.name = String(Int(arc4random_uniform(1000))) task.user = user self.realm.addNotified(task, update: true) } } // MARK: Table view protocols func numberOfSectionsInTableView(tableView: UITableView) -> Int { return rrc!.numberOfSections } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return rrc!.numberOfObjectsAt(section) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("celltask") if cell == nil { cell = UITableViewCell(style: .Default, reuseIdentifier: "celltask") } let task = rrc!.objectAt(indexPath) cell?.textLabel?.text = task.name + " :: " + String(task.projectID) return cell! } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let task = rrc!.objectAt(indexPath) try! realm.write { let model = self.realm.objectForPrimaryKey(TaskModelObject.self, key: task.id)! self.realm.deleteNotified(model) } } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let keyPath: String = rrc!.sections[section].keyPath return "ProjectID \(keyPath)" } func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { return section == 2 ? "Tap on a row to delete it" : nil } // MARK: RealmResult func willChangeResults(controller: AnyObject) { print("🎁 WILLChangeResults") tableView.beginUpdates() } func didChangeObject<U>(controller: AnyObject, object: U, oldIndexPath: NSIndexPath, newIndexPath: NSIndexPath, changeType: RealmResultsChangeType) { print("🎁 didChangeObject '\((object as! TaskModelObject).name)' from: [\(oldIndexPath.section):\(oldIndexPath.row)] to: [\(newIndexPath.section):\(newIndexPath.row)] --> \(changeType)") switch changeType { case .Delete: tableView.deleteRowsAtIndexPaths([newIndexPath], withRowAnimation: UITableViewRowAnimation.Automatic) break case .Insert: tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: UITableViewRowAnimation.Automatic) break case .Move: tableView.deleteRowsAtIndexPaths([oldIndexPath], withRowAnimation: UITableViewRowAnimation.Automatic) tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: UITableViewRowAnimation.Automatic) break case .Update: tableView.reloadRowsAtIndexPaths([newIndexPath], withRowAnimation: UITableViewRowAnimation.Automatic) break } } func didChangeSection<U>(controller: AnyObject, section: RealmSection<U>, index: Int, changeType: RealmResultsChangeType) { print("🎁 didChangeSection \(index) --> \(changeType)") switch changeType { case .Delete: tableView.deleteSections(NSIndexSet(index: index), withRowAnimation: UITableViewRowAnimation.Automatic) break case .Insert: tableView.insertSections(NSIndexSet(index: index), withRowAnimation: UITableViewRowAnimation.Automatic) break default: break } } func didChangeResults(controller: AnyObject) { print("🎁 DIDChangeResults") tableView.endUpdates() } }
mit
3235044d069379f1b69a669608ed7161
36.447917
196
0.606482
5.027273
false
false
false
false
ReXSwift/ReX
ReXDemo/Utils/Alert.swift
1
2222
// // Alert.swift // RxSwiftX // // Created by DianQK on 08/12/2016. // Copyright © 2016 T. All rights reserved. // import UIKit import RxSwift func topViewController(_ base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? { if let nav = base as? UINavigationController { return topViewController(nav.visibleViewController) } if let tab = base as? UITabBarController { if let selected = tab.selectedViewController { return topViewController(selected) } } if let presented = base?.presentedViewController { return topViewController(presented) } return base } let showTextField: () -> Observable<String> = { return Observable.create { observer in let alert = UIAlertController(title: "添加新的待办事项", message: nil, preferredStyle: .alert) alert.addTextField(configurationHandler: { (textField) in }) alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { _ in observer.on(.completed) })) alert.addAction(UIAlertAction(title: "好", style: .default, handler: { _ in if let text = alert.textFields?.first?.text { observer.on(.next(text)) } observer.on(.completed) })) topViewController()?.showDetailViewController(alert, sender: nil) return Disposables.create { alert.dismiss(animated: true, completion: nil) } } } let showEnsure: (_ title: String) -> Observable<Void> = { title in return Observable.create { observer in let alert = UIAlertController(title: title, message: nil, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { _ in observer.on(.completed) })) alert.addAction(UIAlertAction(title: "好", style: .default, handler: { _ in observer.on(.next(())) observer.on(.completed) })) topViewController()?.showDetailViewController(alert, sender: nil) return Disposables.create { alert.dismiss(animated: true, completion: nil) } } }
mit
d7544693ae01b77de91dff206a4ef85c
33.265625
125
0.626995
4.587866
false
false
false
false
jonnguy/HSTracker
HSTracker/Database/Models/Deck.swift
2
4456
// // Deck.swift // HSTracker // // Created by Benjamin Michotte on 19/02/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation import RealmSwift import HearthMirror func generateId() -> String { return "\(UUID().uuidString)-\(Date().timeIntervalSince1970)" } class Deck: Object { @objc dynamic var deckId: String = generateId() @objc dynamic var name = "" @objc private dynamic var _playerClass = CardClass.neutral.rawValue var playerClass: CardClass { get { return CardClass(rawValue: _playerClass)! } set { _playerClass = newValue.rawValue } } @objc dynamic var heroId = "" @objc dynamic var deckMajorVersion: Int = 1 @objc dynamic var deckMinorVersion: Int = 0 @objc dynamic var creationDate = Date() let hearthstatsId = RealmOptional<Int>() let hearthstatsVersionId = RealmOptional<Int>() let hearthStatsArenaId = RealmOptional<Int>() @objc dynamic var isActive = true @objc dynamic var isArena = false let hsDeckId = RealmOptional<Int64>() let cards = List<RealmCard>() let gameStats = List<GameStats>() override static func primaryKey() -> String? { return "deckId" } func add(card: Card) { if card.count == 0 { card.count = 1 } if let _card = cards.filter("id = '\(card.id)'").first { _card.count += card.count } else { cards.append(RealmCard(id: card.id, count: card.count)) } } func remove(card: Card) { if let _card = cards.filter("id = '\(card.id)'").first { _card.count -= 1 if _card.count <= 0 { if let index = cards.index(of: _card) { cards.remove(at: index) } } } reset() } private var _cacheCards: [Card]? var sortedCards: [Card] { if let cards = _cacheCards { return cards } var cache: [Card] = [] for deckCard in cards { if let card = Cards.by(cardId: deckCard.id) { card.count = deckCard.count cache.append(card) } } cache = cache.sortCardList() _cacheCards = cache return cache } func reset() { _cacheCards = nil } func countCards() -> Int { return sortedCards.countCards() } func isValid() -> Bool { let count = countCards() return count == 30 } func arenaFinished() -> Bool { if !isArena { return false } var win = 0 var loss = 0 for stat in gameStats { if stat.result == .loss { loss += 1 } else if stat.result == .win { win += 1 } } return win == 12 || loss == 3 } func standardViable() -> Bool { return !isArena && !sortedCards.any { $0.set != nil && CardSet.wildSets().contains($0.set!) } } var isWildDeck: Bool { return sortedCards.any { CardSet.wildSets().contains($0.set ?? .all) } } /** * Compares the card content to the other deck */ func isContentEqualTo(mirrorDeck: MirrorDeck) -> Bool { let mirrorCards = mirrorDeck.cards for c in self.cards { guard let othercard = mirrorCards.first(where: {$0.cardId == c.id}) else { return false } if c.count != othercard.count.intValue { return false } } return true } func diffTo(mirrorDeck: MirrorDeck) -> (cards: [Card], success: Bool) { var diffs = [Card]() let mirrorCards = mirrorDeck.cards for c in self.cards { guard let othercard = mirrorCards.first(where: {$0.cardId == c.id}) else { diffs.append(Card(fromRealCard: c)) continue } if c.count != othercard.count.intValue { let diffc = Card(fromRealCard: c) diffc.count = abs(c.count - othercard.count.intValue) diffs.append(diffc) } } return (diffs, true) } func incrementVersion(major: Int) { self.deckMajorVersion += major } func incrementVersion(minor: Int) { self.deckMinorVersion += minor } }
mit
c5a8ccefba4ca345c17803f20b9b4503
25.205882
86
0.530415
4.242857
false
false
false
false
Fenrikur/ef-app_ios
EurofurenceTests/Presenter Tests/Schedule/Test Doubles/CapturingScheduleScene.swift
1
2337
@testable import Eurofurence import EurofurenceModel import UIKit.UIViewController class CapturingScheduleScene: UIViewController, ScheduleScene { private(set) var delegate: ScheduleSceneDelegate? func setDelegate(_ delegate: ScheduleSceneDelegate) { self.delegate = delegate } private(set) var capturedTitle: String? func setScheduleTitle(_ title: String) { capturedTitle = title } private(set) var didShowRefreshIndicator = false func showRefreshIndicator() { didShowRefreshIndicator = true } private(set) var didHideRefreshIndicator = false func hideRefreshIndicator() { didHideRefreshIndicator = true } private(set) var boundNumberOfDays: Int? private(set) var daysBinder: ScheduleDaysBinder? func bind(numberOfDays: Int, using binder: ScheduleDaysBinder) { boundNumberOfDays = numberOfDays daysBinder = binder } private(set) var boundItemsPerSection: [Int] = [] private(set) var binder: ScheduleSceneBinder? func bind(numberOfItemsPerSection: [Int], using binder: ScheduleSceneBinder) { boundItemsPerSection = numberOfItemsPerSection self.binder = binder } private(set) var selectedDayIndex: Int? func selectDay(at index: Int) { selectedDayIndex = index } private(set) var deselectedEventIndexPath: IndexPath? func deselectEvent(at indexPath: IndexPath) { deselectedEventIndexPath = indexPath } private(set) var deselectedSearchResultIndexPath: IndexPath? func deselectSearchResult(at indexPath: IndexPath) { deselectedSearchResultIndexPath = indexPath } private(set) var boundSearchItemsPerSection = [Int]() private(set) var searchResultsBinder: ScheduleSceneBinder? func bindSearchResults(numberOfItemsPerSection: [Int], using binder: ScheduleSceneBinder) { boundSearchItemsPerSection = numberOfItemsPerSection searchResultsBinder = binder } private(set) var didShowSearchResults = false private(set) var didShowSearchResultsCount = 0 func showSearchResults() { didShowSearchResults = true didShowSearchResultsCount += 1 } private(set) var didHideSearchResults = false func hideSearchResults() { didHideSearchResults = true } }
mit
0cd9fddfbed4f3662dd257da3b22826d
30.16
95
0.715875
5.047516
false
false
false
false
jlecomte/iOSTwitterApp
Twiddlator/HomeTimelineViewController.swift
1
3354
// // ViewController.swift // Twiddlator // // Created by Julien Lecomte on 9/26/14. // Copyright (c) 2014 Julien Lecomte. All rights reserved. // import UIKit class HomeTimelineViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var tweetListTableView: UITableView! var tweets: [Tweet] = [] let client = TwitterClient.sharedInstance var refreshControl: UIRefreshControl! override func viewDidLoad() { super.viewDidLoad() MMProgressHUD.setPresentationStyle(MMProgressHUDPresentationStyle.None) tweetListTableView.delegate = self tweetListTableView.dataSource = self tweetListTableView.estimatedRowHeight = 95 tweetListTableView.rowHeight = UITableViewAutomaticDimension refreshControl = UIRefreshControl() refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh...") refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged) tweetListTableView.addSubview(refreshControl) fetchTweets(nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func fetchTweets(since_id: String!) { client.getHomeTimeline(nil, max_id: nil) { (tweets: [Tweet]!, error: NSError!) -> Void in self.refreshControl.endRefreshing() if error == nil { self.tweets = tweets + self.tweets self.tweetListTableView.reloadData() } else { // TODO println(error) } } } func refresh(sender:AnyObject) { var since_id: String! = nil if tweets.count > 0 { since_id = tweets[0].uid } fetchTweets(since_id) } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tweets.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("TweetTableViewCell") as TweetTableViewCell var tweet = tweets[indexPath.row] cell.profileImage.setImageWithURL(NSURL(string: tweet.author!.profileImageUrl!)) cell.userNameLabel.text = "@\(tweet.author!.screenName!)" cell.screenNameLabel.text = tweet.author?.userName cell.createdAtLabel.text = tweet.createdAt cell.bodyLabel.text = tweet.body // Additional data used for segue... cell.tweet = tweet return cell } @IBAction func onSignOut(sender: AnyObject) { client.deauthorize() let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate appDelegate.showLogin() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "TweetDetail" { var cell = sender as TweetTableViewCell var detailViewController = segue.destinationViewController as TweetDetailViewController detailViewController.tweet = cell.tweet } } }
mit
29a07c5c4357a0a406d797bc2abccac1
30.641509
109
0.668157
5.462541
false
false
false
false
NunoAlexandre/broccoli_mobile
ios/Carthage/Checkouts/Eureka/Tests/SelectableSectionTests.swift
1
8015
// SelectableSectionTests.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import XCTest @testable import Eureka class SelectableSectionTests: XCTestCase { var formVC = FormViewController() override func setUp() { super.setUp() let form = Form() //create a form with two sections. The second one is of multiple selection let continents = ["Africa", "Antarctica", "Asia", "Australia", "Europe", "North America", "South America"] let oceans = ["Arctic", "Atlantic", "Indian", "Pacific", "Southern"] form +++ SelectableSection<ListCheckRow<String>>() { _ in } for option in continents { form.last! <<< ListCheckRow<String>(option){ lrow in lrow.title = option lrow.selectableValue = option lrow.value = nil } } form +++ SelectableSection<ListCheckRow<String>>("And which of the following oceans have you taken a bath in?", selectionType: .multipleSelection) for option in oceans { form.last! <<< ListCheckRow<String>(option){ lrow in lrow.title = option lrow.selectableValue = option } } form +++ SelectableSection<ListCheckRow<String>>("", selectionType: .singleSelection(enableDeselection: false)) for option in oceans { form.last! <<< ListCheckRow<String>("\(option)2"){ lrow in lrow.title = option lrow.selectableValue = option } } formVC.form = form // load the view to test the cells formVC.view.frame = CGRect(x: 0, y: 0, width: 375, height: 3000) formVC.tableView?.frame = formVC.view.frame } override func tearDown() { super.tearDown() } func testSections() { formVC.tableView(formVC.tableView!, didSelectRowAt: IndexPath(row: 1, section: 0)) formVC.tableView(formVC.tableView!, didSelectRowAt: IndexPath(row: 1, section: 1)) formVC.tableView(formVC.tableView!, didSelectRowAt: IndexPath(row: 3, section: 1)) let value1 = (formVC.form[0] as! SelectableSection<ListCheckRow<String>>).selectedRow()?.baseValue let value2 = (formVC.form[1] as! SelectableSection<ListCheckRow<String>>).selectedRows().map({$0.baseValue}) XCTAssertEqual(value1 as? String, "Antarctica") XCTAssertTrue(value2.count == 2) XCTAssertEqual((value2[0] as? String), "Atlantic") XCTAssertEqual((value2[1] as? String), "Pacific") //Now deselect One of the multiple selection section and change the value of the first section formVC.tableView(formVC.tableView!, didSelectRowAt: IndexPath(row: 6, section: 0)) formVC.tableView(formVC.tableView!, didSelectRowAt: IndexPath(row: 1, section: 1)) let value3 = (formVC.form[0] as! SelectableSection<ListCheckRow<String>>).selectedRow()?.baseValue let value4 = (formVC.form[1] as! SelectableSection<ListCheckRow<String>>).selectedRows().map({$0.baseValue}) XCTAssertEqual(value3 as? String, "South America") XCTAssertTrue(value4.count == 1) XCTAssertEqual((value4[0] as? String), "Pacific") } func testDeselectionDisabled() { formVC.tableView(formVC.tableView!, didSelectRowAt: IndexPath(row: 0, section: 2)) var value1 = (formVC.form[2] as! SelectableSection<ListCheckRow<String>>).selectedRow()?.baseValue XCTAssertEqual(value1 as? String, "Arctic") // now try deselecting one of each and see that nothing changes. formVC.tableView(formVC.tableView!, didSelectRowAt: IndexPath(row: 0, section: 2)) value1 = (formVC.form[2] as! SelectableSection<ListCheckRow<String>>).selectedRow()?.baseValue XCTAssertEqual(value1 as? String, "Arctic") // But we can change the value in the first section formVC.tableView(formVC.tableView!, didSelectRowAt: IndexPath(row: 2, section: 2)) value1 = (formVC.form[2] as! SelectableSection<ListCheckRow<String>>).selectedRow()?.baseValue XCTAssertEqual(value1 as? String, "Indian") } func testSectionedSections() { let selectorViewController = SelectorViewController<String>(nibName: nil, bundle: nil) selectorViewController.row = PushRow<String>() { row in row.options = ["Africa", "Antarctica", "Asia", "Australia", "Europe", "North America", "South America"] } enum Hemisphere: Int { case west, east, none } selectorViewController.sectionKeyForValue = { option in switch option { case "Africa", "Asia", "Australia", "Europe": return String(Hemisphere.west.rawValue) case "North America", "South America": return String(Hemisphere.east.rawValue) default: return String(Hemisphere.none.rawValue) } } selectorViewController.sectionHeaderTitleForKey = { key in switch Hemisphere(rawValue: Int(key)!)! { case .west: return "West hemisphere" case .east: return "East hemisphere" case .none: return "" } } selectorViewController.sectionFooterTitleForKey = { key in switch Hemisphere(rawValue: Int(key)!)! { case .west: return "West hemisphere" case .east: return "East hemisphere" case .none: return "" } } selectorViewController.view.frame = CGRect(x: 0, y: 0, width: 375, height: 3000) selectorViewController.tableView?.frame = selectorViewController.view.frame let form = selectorViewController.form XCTAssertEqual(form.count, 3) XCTAssertEqual(form[0].count, 4) XCTAssertEqual(form[1].count, 2) XCTAssertEqual(form[2].count, 1) XCTAssertEqual(form[0].header?.title, "West hemisphere") XCTAssertEqual(form[1].header?.title, "East hemisphere") XCTAssertEqual(form[2].header?.title, "") XCTAssertEqual(form[0].footer?.title, "West hemisphere") XCTAssertEqual(form[1].footer?.title, "East hemisphere") XCTAssertEqual(form[2].footer?.title, "") XCTAssertEqual(form[0].flatMap({ ($0 as! ListCheckRow<String>).selectableValue }), ["Africa", "Asia", "Australia", "Europe"]) XCTAssertEqual(form[1].flatMap({ ($0 as! ListCheckRow<String>).selectableValue }), ["North America", "South America"]) XCTAssertEqual(form[2].flatMap({ ($0 as! ListCheckRow<String>).selectableValue }), ["Antarctica"]) } }
mit
006a1c255da02302aa9daeff55fb37e2
42.559783
154
0.630568
4.785075
false
false
false
false
rob-brown/SwiftRedux
Example/SwiftRedux/AsyncViewController.swift
1
2324
// // AsyncViewController.swift // SwiftRedux // // Created by Robert Brown on 11/14/15. // Copyright © 2015 Robert Brown. All rights reserved. // import UIKit class AsyncViewController: UIViewController, ReduxTarget { @IBOutlet weak var activityIndicator: UIActivityIndicatorView? @IBOutlet weak var randomNumberLabel: UILabel? var store: Store<History<AppState>>? var notifier: Notifier? private var unsubscribers = [Unsubscriber]() deinit { unsubscribers.forEach { $0() } } override func viewDidLoad() { super.viewDidLoad() guard let notifier = notifier else { return } let unsubscriber1 = notifier.randomNumberNotifier.subscribe(numberChanged) let unsubscriber2 = notifier.randomNumberLoadingNotifier.subscribe(loadingChanged) unsubscribers = [unsubscriber1, unsubscriber2] } func numberChanged(number: Int) { dispatch_main_queue { self.randomNumberLabel?.text = String(number) } } func loadingChanged(loading: Bool) { dispatch_main_queue { if loading { self.activityIndicator?.startAnimating() } else { self.activityIndicator?.stopAnimating() } } } @IBAction func tappedGenerate(sender: UIButton) { let action = AsyncAction<History<AppState>>(type: RandomAction.RandomNumber.rawValue) { dispatcher, stateFetcher in let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) dispatch_async(queue) { let startAction = RandomActionCreater.randomNumberLoading(true) _ = try? dispatcher(startAction) let delay = dispatch_time(DISPATCH_TIME_NOW, 3 * Int64(NSEC_PER_SEC)) dispatch_after(delay, queue) { let number = Int(arc4random_uniform(100)) let resultAction = RandomActionCreater.randomNumber(number) _ = try? dispatcher(resultAction) let endAction = RandomActionCreater.randomNumberLoading(false) _ = try? dispatcher(endAction) } } } _ = try? store?.dispatch(action) } }
mit
a0375a9acaecd504d1fe099b04d4f38f
33.161765
123
0.60353
4.849687
false
false
false
false
PlutoMa/SwiftProjects
021.CoreDataApp/CoreDataApp/CoreDataApp/AppDelegate.swift
1
4592
// // AppDelegate.swift // CoreDataApp // // Created by Dareway on 2017/11/3. // Copyright © 2017年 Pluto. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "CoreDataApp") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
42be58bf2342be787d5a3fc0d3a04394
48.344086
285
0.685988
5.853316
false
false
false
false
blokadaorg/blokada
ios/App/Repository/SheetRepo.swift
1
5289
// // This file is part of Blokada. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. // // Copyright © 2021 Blocka AB. All rights reserved. // // @author Karol Gusak // import Foundation import Combine class SheetRepo: Startable { var currentSheet: AnyPublisher<ActiveSheet?, Never> { writeCurrentSheet.removeDuplicates().eraseToAnyPublisher() } var showPauseMenu: AnyPublisher<Bool, Never> { writeShowPauseMenu.removeDuplicates().compactMap { $0 }.eraseToAnyPublisher() } fileprivate let writeCurrentSheet = CurrentValueSubject<ActiveSheet?, Never>(nil) fileprivate let writeSheetQueue = CurrentValueSubject<[ActiveSheet?], Never>([nil]) fileprivate let writeShowPauseMenu = CurrentValueSubject<Bool?, Never>(nil) fileprivate let addSheetT = Tasker<ActiveSheet?, Ignored>("addSheet", debounce: 0) fileprivate let removeSheetT = SimpleTasker<Ignored>("removeSheet", debounce: 0) fileprivate let syncClosedSheetT = SimpleTasker<Ignored>("syncClosedSheet", debounce: 0) private let bgQueue = DispatchQueue(label: "SheetRepoBgQueue") private var cancellables = Set<AnyCancellable>() func start() { onAddSheet() onRemoveSheet() onSyncClosedSheet() onSheetQueue_pushToCurrent() onSheetDismissed_displayNextAfterShortTime() } func showSheet(_ sheet: ActiveSheet, params: Any? = nil) { currentSheet.first() .flatMap { it -> AnyPublisher<Ignored, Error> in if it != nil { return self.dismiss() .delay(for: 1.0, scheduler: self.bgQueue) .eraseToAnyPublisher() } else { return Just(true) .setFailureType(to: Error.self) .eraseToAnyPublisher() } } .flatMap { _ in self.addSheetT.send(sheet) } .sink() .store(in: &cancellables) } func dismiss() -> AnyPublisher<Ignored, Error> { return removeSheetT.send() } func onDismissed() { self.removeSheetT.send() } func showPauseMenu(_ show: Bool) { writeShowPauseMenu.send(show) } private func onAddSheet() { addSheetT.setTask { sheet in self.writeSheetQueue.first() .receive(on: RunLoop.main) .map { it in if it.count == 1 && it.first ?? nil == nil { // Put the new sheet directly to avoid delay return [sheet] } else { return it + [sheet] } } .map { it in self.writeSheetQueue.send(it) } .tryMap { _ in true } .eraseToAnyPublisher() } } private func onRemoveSheet() { removeSheetT.setTask { _ in self.writeSheetQueue.first() .receive(on: RunLoop.main) .map { it in if it.first ?? nil != nil { return [nil] + Array(it.dropFirst()) } else { return it } } .map { it in self.writeSheetQueue.send(it) } .tryMap { _ in true } .eraseToAnyPublisher() } } private func onSyncClosedSheet() { syncClosedSheetT.setTask { _ in self.writeSheetQueue.first() .receive(on: RunLoop.main) .map { it in if it.first ?? nil != nil { return [nil] + Array(it.dropFirst()) } else { return it } } .map { it in self.writeSheetQueue.send(it) } .tryMap { _ in true } .eraseToAnyPublisher() } } private func onSheetQueue_pushToCurrent() { writeSheetQueue .flatMap { queue in Publishers.CombineLatest(Just(queue), self.currentSheet.first()) } .map { it in let (queue, _) = it let firstInQueue = queue.first ?? nil return firstInQueue } .sink(onValue: { it in self.writeCurrentSheet.send(it) }) .store(in: &cancellables) } private func onSheetDismissed_displayNextAfterShortTime() { writeSheetQueue .filter { it in it.count >= 2 } .filter { it in it[0] == nil } .debounce(for: 1.0, scheduler: bgQueue) .sink(onValue: { it in let next = Array(it.dropFirst()) self.writeSheetQueue.send(next) }) .store(in: &cancellables) } } class DebugSheetRepo: SheetRepo { private let log = Logger("Sheet") private var cancellables = Set<AnyCancellable>() override func start() { super.start() currentSheet.sink( onValue: { it in self.log.v("Current: \(it)") } ) .store(in: &cancellables) writeSheetQueue.sink( onValue: { it in self.log.v("Queue: \(it)") } ) .store(in: &cancellables) } }
mpl-2.0
3d93a761a406b2c261312a80f874746e
28.377778
92
0.543873
4.38111
false
false
false
false
ben-ng/swift
stdlib/public/SDK/Foundation/NSDictionary.swift
1
9473
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module //===----------------------------------------------------------------------===// // Dictionaries //===----------------------------------------------------------------------===// extension NSDictionary : ExpressibleByDictionaryLiteral { public required convenience init( dictionaryLiteral elements: (Any, Any)... ) { // FIXME: Unfortunate that the `NSCopying` check has to be done at runtime. self.init( objects: elements.map { $0.1 as AnyObject }, forKeys: elements.map { $0.0 as AnyObject as! NSCopying }, count: elements.count) } } extension Dictionary { /// Private initializer used for bridging. /// /// The provided `NSDictionary` will be copied to ensure that the copy can /// not be mutated by other code. public init(_cocoaDictionary: _NSDictionary) { _sanityCheck( _isBridgedVerbatimToObjectiveC(Key.self) && _isBridgedVerbatimToObjectiveC(Value.self), "Dictionary can be backed by NSDictionary storage only when both key and value are bridged verbatim to Objective-C") // FIXME: We would like to call CFDictionaryCreateCopy() to avoid doing an // objc_msgSend() for instances of CoreFoundation types. We can't do that // today because CFDictionaryCreateCopy() copies dictionary contents // unconditionally, resulting in O(n) copies even for immutable dictionaries. // // <rdar://problem/20690755> CFDictionaryCreateCopy() does not call copyWithZone: // // The bug is fixed in: OS X 10.11.0, iOS 9.0, all versions of tvOS // and watchOS. self = Dictionary( _immutableCocoaDictionary: unsafeBitCast(_cocoaDictionary.copy(with: nil) as AnyObject, to: _NSDictionary.self)) } } // Dictionary<Key, Value> is conditionally bridged to NSDictionary extension Dictionary : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSDictionary { return unsafeBitCast(_bridgeToObjectiveCImpl() as AnyObject, to: NSDictionary.self) } public static func _forceBridgeFromObjectiveC( _ d: NSDictionary, result: inout Dictionary? ) { if let native = [Key : Value]._bridgeFromObjectiveCAdoptingNativeStorageOf( d as AnyObject) { result = native return } if _isBridgedVerbatimToObjectiveC(Key.self) && _isBridgedVerbatimToObjectiveC(Value.self) { result = [Key : Value]( _cocoaDictionary: unsafeBitCast(d as AnyObject, to: _NSDictionary.self)) return } // `Dictionary<Key, Value>` where either `Key` or `Value` is a value type // may not be backed by an NSDictionary. var builder = _DictionaryBuilder<Key, Value>(count: d.count) d.enumerateKeysAndObjects({ (anyKey: Any, anyValue: Any, stop: UnsafeMutablePointer<ObjCBool>) in let anyObjectKey = anyKey as AnyObject let anyObjectValue = anyValue as AnyObject builder.add( key: Swift._forceBridgeFromObjectiveC(anyObjectKey, Key.self), value: Swift._forceBridgeFromObjectiveC(anyObjectValue, Value.self)) }) result = builder.take() } public static func _conditionallyBridgeFromObjectiveC( _ x: NSDictionary, result: inout Dictionary? ) -> Bool { let anyDict = x as [NSObject : AnyObject] if _isBridgedVerbatimToObjectiveC(Key.self) && _isBridgedVerbatimToObjectiveC(Value.self) { result = Swift._dictionaryDownCastConditional(anyDict) return result != nil } result = Swift._dictionaryBridgeFromObjectiveCConditional(anyDict) return result != nil } public static func _unconditionallyBridgeFromObjectiveC( _ d: NSDictionary? ) -> Dictionary { // `nil` has historically been used as a stand-in for an empty // dictionary; map it to an empty dictionary. if _slowPath(d == nil) { return Dictionary() } if let native = [Key : Value]._bridgeFromObjectiveCAdoptingNativeStorageOf( d! as AnyObject) { return native } if _isBridgedVerbatimToObjectiveC(Key.self) && _isBridgedVerbatimToObjectiveC(Value.self) { return [Key : Value]( _cocoaDictionary: unsafeBitCast(d! as AnyObject, to: _NSDictionary.self)) } // `Dictionary<Key, Value>` where either `Key` or `Value` is a value type // may not be backed by an NSDictionary. var builder = _DictionaryBuilder<Key, Value>(count: d!.count) d!.enumerateKeysAndObjects({ (anyKey: Any, anyValue: Any, stop: UnsafeMutablePointer<ObjCBool>) in builder.add( key: Swift._forceBridgeFromObjectiveC(anyKey as AnyObject, Key.self), value: Swift._forceBridgeFromObjectiveC(anyValue as AnyObject, Value.self)) }) return builder.take() } } extension NSDictionary : Sequence { // FIXME: A class because we can't pass a struct with class fields through an // [objc] interface without prematurely destroying the references. final public class Iterator : IteratorProtocol { var _fastIterator: NSFastEnumerationIterator var _dictionary: NSDictionary { return _fastIterator.enumerable as! NSDictionary } public func next() -> (key: Any, value: Any)? { if let key = _fastIterator.next() { // Deliberately avoid the subscript operator in case the dictionary // contains non-copyable keys. This is rare since NSMutableDictionary // requires them, but we don't want to paint ourselves into a corner. return (key: key, value: _dictionary.object(forKey: key)!) } return nil } internal init(_ _dict: NSDictionary) { _fastIterator = NSFastEnumerationIterator(_dict) } } // Bridging subscript. @objc public subscript(key: Any) -> Any? { @objc(_swift_objectForKeyedSubscript:) get { // Deliberately avoid the subscript operator in case the dictionary // contains non-copyable keys. This is rare since NSMutableDictionary // requires them, but we don't want to paint ourselves into a corner. return self.object(forKey: key) } } /// Return an *iterator* over the elements of this *sequence*. /// /// - Complexity: O(1). public func makeIterator() -> Iterator { return Iterator(self) } } extension NSMutableDictionary { // Bridging subscript. override public subscript(key: Any) -> Any? { get { return self.object(forKey: key) } @objc(_swift_setObject:forKeyedSubscript:) set { // FIXME: Unfortunate that the `NSCopying` check has to be done at // runtime. let copyingKey = key as AnyObject as! NSCopying if let newValue = newValue { self.setObject(newValue, forKey: copyingKey) } else { self.removeObject(forKey: copyingKey) } } } } extension NSDictionary { /// Initializes a newly allocated dictionary and adds to it objects from /// another given dictionary. /// /// - Returns: An initialized dictionary—which might be different /// than the original receiver—containing the keys and values /// found in `otherDictionary`. @objc(_swiftInitWithDictionary_NSDictionary:) public convenience init(dictionary otherDictionary: NSDictionary) { // FIXME(performance)(compiler limitation): we actually want to do just // `self = otherDictionary.copy()`, but Swift does not have factory // initializers right now. let numElems = otherDictionary.count let stride = MemoryLayout<AnyObject>.stride let alignment = MemoryLayout<AnyObject>.alignment let singleSize = stride * numElems let totalSize = singleSize * 2 _sanityCheck(stride == MemoryLayout<NSCopying>.stride) _sanityCheck(alignment == MemoryLayout<NSCopying>.alignment) // Allocate a buffer containing both the keys and values. let buffer = UnsafeMutableRawPointer.allocate( bytes: totalSize, alignedTo: alignment) defer { buffer.deallocate(bytes: totalSize, alignedTo: alignment) _fixLifetime(otherDictionary) } let valueBuffer = buffer.bindMemory(to: AnyObject.self, capacity: numElems) let buffer2 = buffer + singleSize let keyBuffer = buffer2.bindMemory(to: AnyObject.self, capacity: numElems) _stdlib_NSDictionary_getObjects( nsDictionary: otherDictionary, objects: valueBuffer, andKeys: keyBuffer) let keyBufferCopying = buffer2.assumingMemoryBound(to: NSCopying.self) self.init(objects: valueBuffer, forKeys: keyBufferCopying, count: numElems) } } @_silgen_name("__NSDictionaryGetObjects") func _stdlib_NSDictionary_getObjects( nsDictionary: NSDictionary, objects: UnsafeMutablePointer<AnyObject>?, andKeys keys: UnsafeMutablePointer<AnyObject>? ) extension NSDictionary : CustomReflectable { public var customMirror: Mirror { return Mirror(reflecting: self as [NSObject : AnyObject]) } } extension Dictionary: CVarArg {}
apache-2.0
750a92e0f2e0b20ffff4f1660bc4a00c
35.003802
122
0.66892
4.845957
false
false
false
false
nineteen-apps/swift
lessons-02/lesson2/Sources/main.swift
1
2594
// // Curso - Swift para Iniciantes // Pequeno programa que valida os dígitos do CPF // // MIT License // // Copyright (c) 2017 Nineteen Apps // // 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 enum InputError { case inputOk case invalidCpfSize case cpfContainsLetters case cpfContainsInvalidCharacters } enum SelectedOption { case cpf(String) case cnpj(String) case invalid } func getCmdLineOption(arguments: [String]) -> SelectedOption { if let idx = arguments.index(of: "-c") { return .cpf(arguments[idx + 1]) } if let idx = arguments.index(of: "-j") { return .cnpj(arguments[idx + 1]) } return .invalid } if CommandLine.arguments.count == 1 { print("Uso: \(CommandLine.arguments[0]) [-c <cpf>] [-j <cnpj>]") print("\tonde:") print("\t\t-c: Verifica um CPF") print("\t\tcpf é o número do CPF sem pontos, espaços ou traços (somente dígitos)") print("\t\t-j: Verifica um CNPJ") print("\t\tcnpj é o número do CNPJ sem pontos, espaços ou traços (somente dígitos)") } else { var checkSum: Checksum? let value = getCmdLineOption(arguments: CommandLine.arguments) switch value { case .cpf(let rawCpf): checkSum = CPF(cpf: rawCpf) case .cnpj(let rawCnpj): checkSum = CNPJ(cnpj: rawCnpj) case .invalid: print("Opção inválida") } if let checkSum = checkSum { if checkSum.isValid() { print("Valor válido") } else { print("Valor inválido") } } }
mit
6187501a6b0c79e13d3b477a8e978343
32.921053
88
0.683476
3.769006
false
false
false
false
adrfer/swift
test/ClangModules/omit_needless_words.swift
11
2791
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -verify -Womit-needless-words -enable-infer-default-arguments %s // REQUIRES: objc_interop import Foundation import AppKit func dropDefaultedNil(array: NSArray, sel: Selector, body: ((AnyObject!, Int, UnsafeMutablePointer<ObjCBool>) -> Void)?) { array.makeObjectsPerformSelector(sel, withObject: nil) // expected-warning{{'makeObjectsPerformSelector(_:withObject:)' could be named 'makeObjectsPerform(_:withObject:)'}}{{9-35=makeObjectsPerform}} array.makeObjectsPerformSelector(sel, withObject: nil, withObject: nil) // expected-warning{{'makeObjectsPerformSelector(_:withObject:withObject:)' could be named 'makeObjectsPerform(_:withObject:withObject:)'}}{{9-35=makeObjectsPerform}} array.enumerateObjectsRandomlyWithBlock(nil) // expected-warning{{'enumerateObjectsRandomlyWithBlock' could be named 'enumerateObjectsRandomly(block:)'}}{{9-42=enumerateObjectsRandomly}}{{43-46=}} array.enumerateObjectsRandomlyWithBlock(body) // expected-warning{{'enumerateObjectsRandomlyWithBlock' could be named 'enumerateObjectsRandomly(block:)'}}{{9-42=enumerateObjectsRandomly}}{{43-43=block: }} } func dropDefaultedOptionSet(array: NSArray) { array.enumerateObjectsWithOptions([]) { obj, idx, stop in print("foo") } // expected-warning{{'enumerateObjectsWithOptions(_:usingBlock:)' could be named 'enumerateObjects(options:usingBlock:)'}}{{9-36=enumerateObjects}}{{36-40=}} array.enumerateObjectsWithOptions([], usingBlock: { obj, idx, stop in print("foo") }) // expected-warning{{'enumerateObjectsWithOptions(_:usingBlock:)' could be named 'enumerateObjects(options:usingBlock:)'}}{{9-36=enumerateObjects}}{{37-41=}} array.enumerateObjectsWhileOrderingPizza(true, withOptions: [], usingBlock: { obj, idx, stop in print("foo") }) // expected-warning{{call to 'enumerateObjectsWhileOrderingPizza(_:withOptions:usingBlock:)' has extraneous arguments that could use defaults}}{{48-65=}} } func dropDefaultedWithoutRename(domain: String, code: Int, array: NSArray) { array.enumerateObjectsHaphazardly(nil) // expected-warning{{call to 'enumerateObjectsHaphazardly' has extraneous arguments that could use defaults}}{{37-40=}} array.optionallyEnumerateObjects([], body: { obj, idx, stop in print("foo") }) // expected-warning{{call to 'optionallyEnumerateObjects(_:body:)' has extraneous arguments that could use defaults}}{{36-40=}} } func dontDropUnnamedSetterArg(str: NSString) { str.setTextColor(nil) // don't drop this } func renameTrailingClosure(array: NSArray) { array.enumerateObjectsWithNullableBlock { _, _, _ in print("foo") } // expected-warning{{enumerateObjectsWithNullableBlock' could be named 'enumerateObjects(nullableBlock:)' [-Womit-needless-words]}}{{9-42=enumerateObjects}} }
apache-2.0
38c36415aedcb7aa0f04b553ce368a0c
81.088235
267
0.766392
4.327132
false
false
false
false
FXSolutions/FXDemoXCodeInjectionPlugin
testinjection/Stevia+Aligngment.swift
2
1344
// // Stevia+Aligngment.swift // Stevia // // Created by Sacha Durand Saint Omer on 10/02/16. // Copyright © 2016 Sacha Durand Saint Omer. All rights reserved. // import Foundation import UIKit public func alignHorizontally(views:[UIView]) { align(.Horizontal, views: views) } public func alignVertically(views:[UIView]) { align(.Vertical, views: views) } public func align(axis:UILayoutConstraintAxis, views:[UIView]) { for (i,v) in views.enumerate() { if views.count > i+1 { let v2 = views[i+1] if axis == .Horizontal { alignHorizontally(v, with: v2) } else { alignVertically(v, with: v2) } } } } public func alignCenter(v1:UIView, with v2:UIView) { alignHorizontally(v1, with: v2) alignVertically(v1, with: v2) } public func alignHorizontally(v1:UIView, with v2:UIView) { align(.Horizontal, v1: v1, with: v2) } public func alignVertically(v1:UIView, with v2:UIView) { align(.Vertical, v1: v1, with: v2) } private func align(axis:UILayoutConstraintAxis,v1:UIView, with v2:UIView) { if let spv = v1.superview { let center:NSLayoutAttribute = axis == .Horizontal ? .CenterY : .CenterX let c = constraint(item: v1, attribute: center, toItem: v2) spv.addConstraint(c) } }
mit
17222d601f18d23ebd012fde73bcbc61
24.339623
80
0.634401
3.417303
false
false
false
false
tuannme/Up
Up+/Up+/Controller/CameraKeyBoardViewController.swift
1
5819
// // CameraKeyBoardViewController.swift // Up+ // // Created by Dream on 8/23/17. // Copyright © 2017 Dreamup. All rights reserved. // import UIKit import Photos private let photoCell = "photoCell" private let cameraCell = "cameraCell" private let optionCell = "optionCell" protocol CameraKeyBoardDeleagete:class { func willSendPhoto(photo:UIImage) func willShowCamera() func willShowPhotoLibrary() } class CameraKeyBoardViewController: UIViewController { weak var delegate:CameraKeyBoardDeleagete? var collectionView:UICollectionView! var assetCollection: PHAssetCollection! var photosAsset: PHFetchResult<PHAsset>! let photoSize = CGSize(width: KEYBOARD_HEIGHT/2 - 0.5, height: KEYBOARD_HEIGHT/2 - 0.5) let assetThumbnailSize = CGSize(width: 200, height: 200) override func viewDidLoad() { super.viewDidLoad() self.view.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: KEYBOARD_HEIGHT) self.view.backgroundColor = UIColor.green let fetchOptions = PHFetchOptions() self.photosAsset = PHAsset.fetchAssets(with: fetchOptions) // Do any additional setup after loading the view, typically from a nib. let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() layout.minimumLineSpacing = 1.0 layout.minimumInteritemSpacing = 1.0 layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right:5) layout.scrollDirection = .horizontal self.collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout) self.collectionView.dataSource = self self.collectionView.delegate = self self.collectionView.backgroundColor = UIColor.white self.collectionView.register(PhotoViewCell.self, forCellWithReuseIdentifier: photoCell) self.collectionView.register(CameraViewCell.self, forCellWithReuseIdentifier: cameraCell) self.collectionView.register(OptionViewCell.self, forCellWithReuseIdentifier: optionCell) self.view.addSubview(collectionView) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.collectionView.setContentOffset(CGPoint(x: 150, y: 0), animated: false) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension CameraKeyBoardViewController:UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{ func numberOfSections(in collectionView: UICollectionView) -> Int { return 3 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { switch section { case 0,1: return 1 default: return self.photosAsset.count } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { switch indexPath.section { case 0: let option = collectionView.dequeueReusableCell(withReuseIdentifier: optionCell, for: indexPath) as! OptionViewCell option.addEventAction(completion: { [weak self] option in guard let _self = self else{return} if option == .camera{ _self.delegate?.willShowCamera() }else{ _self.delegate?.willShowPhotoLibrary() } }) return option case 1: let camera = collectionView.dequeueReusableCell(withReuseIdentifier: cameraCell, for: indexPath) as! CameraViewCell camera.addEventSelectPhoto(completion: { [weak self](image) in guard let _self = self else{return} _self.delegate?.willSendPhoto(photo: image) }) return camera default: let item = collectionView.dequeueReusableCell(withReuseIdentifier: photoCell, for: indexPath) as! PhotoViewCell let asset: PHAsset = self.photosAsset[indexPath.item] PHImageManager.default().requestImage(for: asset, targetSize: self.assetThumbnailSize, contentMode: .aspectFit, options: nil, resultHandler: {(image, info)in if image != nil { DispatchQueue.main.async { item.imageView.image = image } } }) return item } } // MARK: UICollectionViewDelegateFlowLayout func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { switch indexPath.section { case 0: return CGSize(width: 150, height: KEYBOARD_HEIGHT) case 1: return CGSize(width: 170, height: KEYBOARD_HEIGHT) default: return photoSize } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { switch indexPath.section { case 0: break case 1: break default: let asset: PHAsset = self.photosAsset[indexPath.item] PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width: 500, height: 500), contentMode: .aspectFit, options: nil, resultHandler: {(image, info)in if let _image = image { self.delegate?.willSendPhoto(photo: _image) } }) break } } }
mit
4020f60446af923f2c04f9087c3d8d24
34.91358
177
0.630457
5.417132
false
false
false
false
knehez/edx-app-ios
Test/CourseDataManagerTests.swift
3
2806
// // CourseDataManagerTests.swift // edX // // Created by Akiva Leffert on 7/2/15. // Copyright (c) 2015 edX. All rights reserved. // import edX import UIKit import XCTest class CourseDataManagerTests: XCTestCase { let networkManager = MockNetworkManager(authorizationHeaderProvider: nil, baseURL: NSURL(string : "http://example.com")!) let outline = CourseOutlineTestDataFactory.freshCourseOutline(OEXCourse.freshCourse().course_id!) override func tearDown() { networkManager.reset() } func checkOutlineLoadsWithQuerier(querier : CourseOutlineQuerier, rootID : CourseBlockID, line : UInt = __LINE__, file : String = __FILE__) { let rootStream = querier.blockWithID(nil) let expectation = self.expectationWithDescription("Outline loads from network") rootStream.listenOnce(self) {rootBlock in XCTAssertEqual(rootBlock.value!.blockID, rootID, file : file, line : line) expectation.fulfill() } waitForExpectations() } func addInterceptorForOutline(outline : CourseOutline) { networkManager.interceptWhenMatching({_ in true}, successResponse: { return (NSData(), outline) }) } func loadAndVerifyOutline() -> CourseDataManager { let manager = CourseDataManager(interface: nil, networkManager: networkManager) addInterceptorForOutline(outline) var querier = manager.querierForCourseWithID(outline.root) checkOutlineLoadsWithQuerier(querier, rootID: outline.root) return manager } func testQuerierCaches() { let manager = loadAndVerifyOutline() // Now remove network interception networkManager.reset() // The course should still load since the querier saves it let querier = manager.querierForCourseWithID(outline.root) checkOutlineLoadsWithQuerier(querier, rootID: outline.root) } func testQuerierClearedOnSignOut() { let manager = loadAndVerifyOutline() let defaultsMockRemover = OEXMockUserDefaults().installAsStandardUserDefaults() let session = OEXSession(credentialStore: OEXMockCredentialStorage()) // Close session so the course data should be cleared session.closeAndClearSession() networkManager.reset() let querier = manager.querierForCourseWithID(outline.root) let newOutline = CourseOutlineTestDataFactory.freshCourseOutline(OEXCourse.freshCourse().course_id!) addInterceptorForOutline(newOutline) checkOutlineLoadsWithQuerier(querier, rootID: newOutline.root) XCTAssertNotEqual(newOutline.root, outline.root, "Fresh Courses should be distinct") defaultsMockRemover.remove() } }
apache-2.0
357f0a696a679caf739db28ee1444f30
36.918919
145
0.68995
4.905594
false
true
false
false
aidangomez/RandKit
Source/Distributions/Discrete/Geometric.swift
1
747
// Copyright © 2016 Aidan Gomez. // // This file is part of RandKit. The full RandKit copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. public class GeometricDistribution: DiscreteDistributionType { public typealias Element = DiscreteValue public let probability: Double public init(probability: Double) { self.probability = probability } public func random() -> Element { return geometric(probability: probability) } } public func geometric(probability p: Double) -> DiscreteValue { var x = 0 while bernoulli(probability: p) != 1 { x += 1 } return x }
mit
3ec9bffd556116d1d099071c209f6371
25.642857
77
0.69437
4.440476
false
false
false
false
flypaper0/ethereum-wallet
ethereum-wallet/Classes/BusinessLayer/Core/Services/Transaction/New/InputBuilder.swift
1
1409
// Copyright © 2018 Conicoin LLC. All rights reserved. // Created by Artur Guseinov import Foundation protocol EthTxInputBuilder { func createInput(amount: Decimal, receiverAddress: String) throws -> Data } class EthDefaultTxInputBuilder: EthTxInputBuilder { func createInput(amount: Decimal, receiverAddress: String) throws -> Data { return Data(hex: "0x") } } // TODO: - Connect to transaction service class EthTokenTxInputBuilder: EthTxInputBuilder { let decimals: Int init(decimals: Int) { self.decimals = decimals } /// The first 32 bit a9059cbb is the first 32 bit of the hash of the function. /// In this case the function is transfer(address _to, uint256 _value). /// This is followed by 256 bit for each argument, so in this case the address and amount to send func createInput(amount: Decimal, receiverAddress: String) throws -> Data { let transferSignature = Data(bytes: [0xa9, 0x05, 0x9c, 0xbb]) let address = receiverAddress.lowercased().replacingOccurrences(of: "0x", with: "") let weiAmount = amount * pow(10, decimals) let hexAmount = weiAmount.toHex().withLeadingZero(64) let hexData = transferSignature.hex() + "000000000000000000000000" + address + hexAmount guard let data = hexData.toHexData() else { throw Errors.badSignature } return data } enum Errors: Error { case badSignature } }
gpl-3.0
cebd985113010529b8eb14be1943a234
29.608696
99
0.708807
3.868132
false
false
false
false
joerocca/GitHawk
Classes/Issues/Assignees/IssueAssigneeSummaryModel.swift
2
956
// // IssueAssigneeSummaryModel.swift // Freetime // // Created by Ryan Nystrom on 7/13/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation import IGListKit final class IssueAssigneeSummaryModel: ListDiffable { let title: String let urls: [URL] let expanded: Bool private let urlHash: String init(title: String, urls: [URL], expanded: Bool) { self.title = title self.urls = urls self.expanded = expanded self.urlHash = urls.reduce("") { $0 + $1.path } } // MARK: ListDiffable func diffIdentifier() -> NSObjectProtocol { return title as NSObjectProtocol } func isEqual(toDiffableObject object: ListDiffable?) -> Bool { if self === object { return true } guard let object = object as? IssueAssigneeSummaryModel else { return false } return expanded == object.expanded && urlHash == object.urlHash } }
mit
9a501a50ff8901a3d4ec603c4f930a5b
23.487179
85
0.641885
4.360731
false
false
false
false
xwu/swift
test/IRGen/objc_protocols.swift
8
11109
// RUN: %empty-directory(%t) // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-module -o %t %S/Inputs/objc_protocols_Bas.swift // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop import gizmo import objc_protocols_Bas // -- Protocol "Frungible" inherits only objc protocols and should have no // out-of-line inherited witnesses in its witness table. // CHECK: [[ZIM_FRUNGIBLE_WITNESS:@"\$s14objc_protocols3ZimCAA9FrungibleAAWP"]] = hidden constant [2 x i8*] [ // CHECK: i8* bitcast (void (%T14objc_protocols3ZimC*, %swift.type*, i8**)* @"$s14objc_protocols3ZimCAA9FrungibleA2aDP6frungeyyFTW" to i8*) // CHECK: ] protocol Ansible { func anse() } class Foo : NSRuncing, NSFunging, Ansible { @objc func runce() {} @objc func funge() {} @objc func foo() {} func anse() {} } // CHECK: @_INSTANCE_METHODS__TtC14objc_protocols3Foo = internal constant { i32, i32, [3 x { i8*, i8*, i8* }] } { // CHECK: i32 24, i32 3, // CHECK: [3 x { i8*, i8*, i8* }] [ // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(runce)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC:@[0-9]+]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @"$s14objc_protocols3FooC5runceyyFTo" to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(funge)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @"$s14objc_protocols3FooC5fungeyyFTo" to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @"$s14objc_protocols3FooC3fooyyFTo" to i8*) // CHECK: }] // CHECK: }, section "__DATA, {{.*}}", align 8 class Bar { func bar() {} } // -- Bar does not directly have objc methods... // CHECK-NOT: @_INSTANCE_METHODS_Bar extension Bar : NSRuncing, NSFunging { @objc func runce() {} @objc func funge() {} @objc func foo() {} func notObjC() {} } // -- ...but the ObjC protocol conformances on its extension add some // CHECK: @"_CATEGORY_INSTANCE_METHODS__TtC14objc_protocols3Bar_$_objc_protocols" = internal constant { i32, i32, [3 x { i8*, i8*, i8* }] } { // CHECK: i32 24, i32 3, // CHECK: [3 x { i8*, i8*, i8* }] [ // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(runce)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @"$s14objc_protocols3BarC5runceyyFTo" to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(funge)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @"$s14objc_protocols3BarC5fungeyyFTo" to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @"$s14objc_protocols3BarC3fooyyFTo" to i8*) } // CHECK: ] // CHECK: }, section "__DATA, {{.*}}", align 8 // class Bas from objc_protocols_Bas module extension Bas : NSRuncing { // -- The runce() implementation comes from the original definition. @objc public func foo() {} } // CHECK: @"_CATEGORY_INSTANCE_METHODS__TtC18objc_protocols_Bas3Bas_$_objc_protocols" = internal constant { i32, i32, [1 x { i8*, i8*, i8* }] } { // CHECK: i32 24, i32 1, // CHECK: [1 x { i8*, i8*, i8* }] [ // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @"$s18objc_protocols_Bas0C0C0a1_B0E3fooyyFTo" to i8*) } // CHECK: ] // CHECK: }, section "__DATA, {{.*}}", align 8 // -- Swift protocol refinement of ObjC protocols. protocol Frungible : NSRuncing, NSFunging { func frunge() } class Zim : Frungible { @objc func runce() {} @objc func funge() {} @objc func foo() {} func frunge() {} } // CHECK: @_INSTANCE_METHODS__TtC14objc_protocols3Zim = internal constant { i32, i32, [3 x { i8*, i8*, i8* }] } { // CHECK: i32 24, i32 3, // CHECK: [3 x { i8*, i8*, i8* }] [ // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(runce)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @"$s14objc_protocols3ZimC5runceyyFTo" to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(funge)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @"$s14objc_protocols3ZimC5fungeyyFTo" to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @"$s14objc_protocols3ZimC3fooyyFTo" to i8*) } // CHECK: ] // CHECK: }, section "__DATA, {{.*}}", align 8 // class Zang from objc_protocols_Bas module extension Zang : Frungible { @objc public func runce() {} // funge() implementation from original definition of Zang @objc public func foo() {} func frunge() {} } // CHECK: @"_CATEGORY_INSTANCE_METHODS__TtC18objc_protocols_Bas4Zang_$_objc_protocols" = internal constant { i32, i32, [2 x { i8*, i8*, i8* }] } { // CHECK: i32 24, i32 2, // CHECK: [2 x { i8*, i8*, i8* }] [ // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(runce)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @"$s18objc_protocols_Bas4ZangC0a1_B0E5runceyyFTo" to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @"$s18objc_protocols_Bas4ZangC0a1_B0E3fooyyFTo" to i8*) } // CHECK: ] // CHECK: }, section "__DATA, {{.*}}", align 8 @objc protocol BaseProtocol { } protocol InheritingProtocol : BaseProtocol { } // -- Make sure that base protocol conformance is registered // CHECK: @_PROTOCOLS__TtC14objc_protocols17ImplementingClass {{.*}} @_PROTOCOL__TtP14objc_protocols12BaseProtocol_ class ImplementingClass : InheritingProtocol { } // CHECK: @_PROTOCOL_PROTOCOLS_NSDoubleInheritedFunging = internal constant{{.*}}i64 2{{.*}} @_PROTOCOL_NSFungingAndRuncing {{.*}}@_PROTOCOL_NSFunging // -- Force generation of witness for Zim. // CHECK: define hidden swiftcc { %objc_object*, i8** } @"$s14objc_protocols22mixed_heritage_erasure{{[_0-9a-zA-Z]*}}F" func mixed_heritage_erasure(_ x: Zim) -> Frungible { return x // CHECK: [[T0:%.*]] = insertvalue { %objc_object*, i8** } undef, %objc_object* {{%.*}}, 0 // CHECK: insertvalue { %objc_object*, i8** } [[T0]], i8** getelementptr inbounds ([2 x i8*], [2 x i8*]* [[ZIM_FRUNGIBLE_WITNESS]], i32 0, i32 0), 1 } // CHECK-LABEL: define hidden swiftcc void @"$s14objc_protocols0A8_generic{{[_0-9a-zA-Z]*}}F"(%objc_object* %0, %swift.type* %T) {{.*}} { func objc_generic<T : NSRuncing>(_ x: T) { x.runce() // CHECK: [[SELECTOR:%.*]] = load i8*, i8** @"\01L_selector(runce)", align 8 // CHECK: bitcast %objc_object* %0 to [[OBJTYPE:.*]]* // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[SELECTOR]]) } // CHECK-LABEL: define hidden swiftcc void @"$s14objc_protocols05call_A8_generic{{[_0-9a-zA-Z]*}}F"(%objc_object* %0, %swift.type* %T) {{.*}} { // CHECK: call swiftcc void @"$s14objc_protocols0A8_generic{{[_0-9a-zA-Z]*}}F"(%objc_object* %0, %swift.type* %T) func call_objc_generic<T : NSRuncing>(_ x: T) { objc_generic(x) } // CHECK-LABEL: define hidden swiftcc void @"$s14objc_protocols0A9_protocol{{[_0-9a-zA-Z]*}}F"(%objc_object* %0) {{.*}} { func objc_protocol(_ x: NSRuncing) { x.runce() // CHECK: [[SELECTOR:%.*]] = load i8*, i8** @"\01L_selector(runce)", align 8 // CHECK: bitcast %objc_object* %0 to [[OBJTYPE:.*]]* // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[SELECTOR]]) } // CHECK: define hidden swiftcc %objc_object* @"$s14objc_protocols0A8_erasure{{[_0-9a-zA-Z]*}}F"(%TSo7NSSpoonC* %0) {{.*}} { func objc_erasure(_ x: NSSpoon) -> NSRuncing { return x // CHECK: [[RES:%.*]] = bitcast %TSo7NSSpoonC* {{%.*}} to %objc_object* // CHECK: ret %objc_object* [[RES]] } // CHECK: define hidden swiftcc void @"$s14objc_protocols0A21_protocol_composition{{[_0-9a-zA-Z]*}}F"(%objc_object* %0) func objc_protocol_composition(_ x: NSRuncing & NSFunging) { x.runce() // CHECK: [[RUNCE:%.*]] = load i8*, i8** @"\01L_selector(runce)", align 8 // CHECK: bitcast %objc_object* %0 to [[OBJTYPE:.*]]* // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[RUNCE]]) x.funge() // CHECK: [[FUNGE:%.*]] = load i8*, i8** @"\01L_selector(funge)", align 8 // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[FUNGE]]) } // CHECK: define hidden swiftcc void @"$s14objc_protocols0A27_swift_protocol_composition{{[_0-9a-zA-Z]*}}F"(%objc_object* %0, i8** %1) func objc_swift_protocol_composition (_ x: NSRuncing & Ansible & NSFunging) { x.runce() // CHECK: [[RUNCE:%.*]] = load i8*, i8** @"\01L_selector(runce)", align 8 // CHECK: bitcast %objc_object* %0 to [[OBJTYPE:.*]]* // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[RUNCE]]) /* TODO: Abstraction difference from ObjC protocol composition to * opaque protocol x.anse() */ x.funge() // CHECK: [[FUNGE:%.*]] = load i8*, i8** @"\01L_selector(funge)", align 8 // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[FUNGE]]) } // TODO: Mixed class-bounded/fully general protocol compositions. @objc protocol SettableProperty { var reqt: NSRuncing { get set } } func instantiateArchetype<T: SettableProperty>(_ x: T) { let y = x.reqt x.reqt = y } // rdar://problem/21029254 @objc protocol Appaloosa { } protocol Palomino {} protocol Vanner : Palomino, Appaloosa { } struct Stirrup<T : Palomino> { } func canter<T : Palomino>(_ t: Stirrup<T>) {} func gallop<T : Vanner>(_ t: Stirrup<T>) { canter(t) } // SR-7130 func triggerDoubleInheritedFunging() -> AnyObject { return NSDoubleInheritedFunging.self as AnyObject }
apache-2.0
8980e3e2a396c4dd3eb0ed5860c75ae3
49.958716
289
0.614727
2.872027
false
false
false
false
radex/swift-compiler-crashes
crashes-duplicates/18156-swift-sourcemanager-getmessage.swift
11
2267
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing 0.C <d { class static let a { (e { func a<d where g: T where H.a struct A { struct A { let start = b func b Void{ func b protocol B : d class c case c typealias f = B) (([Void{ class case <T : e == 0.c, protocol P { class if true { d } } { let h = a<T>: c { } } { d[Void{ func a protocol P { } { } let end = [] } let t: b { (() as a func b protocol c : e { case c, } class static let a { typealias f : A { st } Void{ () as a<T : e) func a<T>: d { enum b { func c, case c] = [ [Void{ case c } struct A { enum b { struct A { func g : T where g: f.c func b func c func a<T where B : f.e : A { case c, struct c, d let t: d func a<T : c : a { func c, struct B<T where g: Any)? func a func c, case c] [] <T { } class A { class A { (") d<H : b { class A { st for h = [Void{ let end = B<T where H.C func d<T where g where H.c, class A {} protocol P { case c] = c, typealias e : e, leng func c, } class let t: a<T where g: a { } } protocol A { struct B<H : e) } class a struct A.e : d st case c typealias e : A.a class class 0.a } func b <I : a { case c } case c, { protocol A { struct A { protocol P { func b<T where H.C let a { class func a } struct d: b { func a") class A { class A { enum B : a { class case c, struct B<v { func b func a } protocol P { } st 0.C struct A { ([Void{ 0.C <H : f.c] = 1 protocol P {} func a struct B<T { { typealias e : a<T : Array<H : A { { class func c class c case c, case c func a" struct A.g : a" { case c { protocol e : b { func c func a case c, typealias f : T where g: A.<H : e : e) case c, static let end = f.a struct B<I : Any) { struct B<T : a { st class A { var d { func b struct B<H : b { { protocol e { { } { { } struct d<d { let t: f.<T where A.c, ([] protocol a { func b>: a func a 0.c case c, class a" enum b { func b: A.a [Int] = B<T where H.g = b<d where B : e { case c, class func c, struct d func c extension NSData { func b class protocol e : f.c, { typealias e : a {} let h { func c] ] = [Void{ func c] = b } func a protocol P { case c } protocol a { { class A { var d { let h = F>([Void{ class { [h] = 0.c, enum b { protocol a {} ((e : A { 0.c : A :
mit
9238ced673ca0ab1109742b2a5cc9b73
9.165919
87
0.588002
2.244554
false
false
false
false
937447974/YJCocoa
YJCocoa/Classes/AppFrameworks/Foundation/Extension/URLExt.swift
1
1513
// // URLExt.swift // YJCocoa // // HomePage:https://github.com/937447974/YJCocoa // YJ技术支持群:557445088 // // Created by 阳君 on 2019/8/1. // Copyright © 2016-现在 YJCocoa. All rights reserved. // import UIKit public extension URL { /// http 中文链接utf8转码初始化 static func utf8(_ string: String) -> URL? { guard let data = string.data(using: .utf8) else { return URL(string: string) } return URL(dataRepresentation: data, relativeTo: nil) } /// 文件类型 var fileExtension: String? { guard self.pathExtension == "" else { return self.pathExtension } guard let data = try? Data(contentsOf: self) else { return nil } let bytes = [UInt8](data) guard bytes.count > 2 else { return nil } let extDict = ["255216" : "jpg", "13780" : "png", "7173" : "gif", "6677" : "bmp", "8075":"zip", "8297":"rar", "70105":"log", "102100":"txt"] return extDict["\(bytes[0])\(bytes[1])"] } /// 添加文件夹路径 func appendingDirectory(_ pathComponent: String) -> URL { let url = self.appendingPathComponent(pathComponent, isDirectory: true) let fm = FileManager.default if !fm.directoryExists(atPath: url.path) { try? fm.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil) } return url } }
mit
6491ef684789247867a370eea9727f90
28.08
96
0.559147
3.846561
false
false
false
false
tedinpcshool/classmaster
classmaster_good/Pods/InteractiveSideMenu/Sources/MenuAnimator.swift
3
17614
// // MenuAnimator.swift // // Copyright 2017 Handsome LLC // // 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 TransitionOptionsBuilder { public var duration: TimeInterval = 0.5 { willSet(newDuration) { if(newDuration < 0) { fatalError("Invalid duration value (\(newDuration)). It must be non negative") } } } public var contentScale: CGFloat = 0.88 { willSet(newContentScale) { if(newContentScale < 0) { fatalError("Invalid contentScale value (\(newContentScale)). It must be non negative") } } } public var visibleContentWidth: CGFloat = 56.0 public var useFinishingSpringOption = true public var useCancelingSpringOption = true public var finishingSpringOption = SpringOption(presentSpringParams: SpringParams(dampingRatio: 0.7, velocity: 0.3), dismissSpringParams: SpringParams(dampingRatio: 0.8, velocity: 0.3)) public var cancelingSpringOption = SpringOption(presentSpringParams: SpringParams(dampingRatio: 0.7, velocity: 0.0), dismissSpringParams: SpringParams(dampingRatio: 0.7, velocity: 0.0)) public var animationOptions: UIViewAnimationOptions = .curveEaseInOut public init(building: (TransitionOptionsBuilder) -> Void) { building(self) } class func defaultOptionsBuilder() -> TransitionOptionsBuilder { return TransitionOptionsBuilder(){_ in } } } public struct SpringParams { let dampingRatio: CGFloat let velocity: CGFloat } public struct SpringOption { let presentSpringParams: SpringParams let dismissSpringParams: SpringParams } class MenuTransitioningDelegate: NSObject, UIViewControllerTransitioningDelegate { var interactiveTransition: MenuInteractiveTransition! func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { interactiveTransition.present = true return interactiveTransition } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { interactiveTransition.present = false return interactiveTransition } func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return interactiveTransition.interactionInProgress ? interactiveTransition : nil } func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return interactiveTransition.interactionInProgress ? interactiveTransition : nil } } class MenuInteractiveTransition: NSObject, UIViewControllerInteractiveTransitioning, UIViewControllerAnimatedTransitioning { typealias Action = () -> () //MARK: - Properties var present: Bool = false var interactionInProgress: Bool = false private var transitionDuration: TimeInterval! private var scaleDiff: CGFloat! private var visibleContentWidth: CGFloat! private var useFinishingSpringOption: Bool! private var useCancelingSpringOption: Bool! private var finishingSpringOption: SpringOption! private var cancelingSpringOption: SpringOption! private var animationOptions: UIViewAnimationOptions! private var presentAction: Action! private var dismissAction: Action! private var transitionShouldStarted = false private var transitionStarted = false private var transitionContext: UIViewControllerContextTransitioning! private var contentSnapshotView: UIView! private var tapRecognizer: UITapGestureRecognizer! private var panRecognizer: UIPanGestureRecognizer! required init(presentAction: @escaping Action, dismissAction: @escaping Action, transitionOptionsBuilder: TransitionOptionsBuilder? = nil) { super.init() self.presentAction = presentAction self.dismissAction = dismissAction let options = transitionOptionsBuilder ?? TransitionOptionsBuilder.defaultOptionsBuilder() self.transitionDuration = options.duration self.scaleDiff = 1 - options.contentScale self.visibleContentWidth = options.visibleContentWidth self.useFinishingSpringOption = options.useFinishingSpringOption self.useCancelingSpringOption = options.useCancelingSpringOption self.finishingSpringOption = options.finishingSpringOption self.cancelingSpringOption = options.cancelingSpringOption self.animationOptions = options.animationOptions } //MARK: - Delegate methods func startInteractiveTransition(_ transitionContext: UIViewControllerContextTransitioning) { startTransition(transitionContext: transitionContext) } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return transitionDuration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { startTransition(transitionContext: transitionContext) finishTransition(currentPercentComplete: 0) } func handlePanPresentation(recognizer: UIPanGestureRecognizer) { present = true handlePan(recognizer: recognizer) } func handlePanDismission(recognizer: UIPanGestureRecognizer) { present = false handlePan(recognizer: recognizer) } private func createSnapshotView(from: UIView) -> UIView { let snapshotView = from.snapshotView(afterScreenUpdates: true)! snapshotView.frame = from.frame addShadow(toView: snapshotView) return snapshotView } private func addShadow(toView: UIView) { toView.layer.shadowColor = UIColor.black.cgColor toView.layer.shadowOpacity = 0.3 toView.layer.shadowOffset = CGSize(width: -5, height: 5) } private func removeShadow(fromView: UIView) { fromView.layer.shadowOffset = CGSize(width: 0, height: 0) } private func startTransition(transitionContext: UIViewControllerContextTransitioning) { transitionStarted = true self.transitionContext = transitionContext let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)! let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)! let containerView = transitionContext.containerView let screenWidth = containerView.frame.size.width if present { containerView.insertSubview(toViewController.view, belowSubview: fromViewController.view) self.tapRecognizer = UITapGestureRecognizer(target: toViewController as! MenuViewController, action: #selector(MenuViewController.handleTap(recognizer:))) self.panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(MenuInteractiveTransition.handlePanDismission(recognizer:))) contentSnapshotView = createSnapshotView(from: fromViewController.view) containerView.addSubview(contentSnapshotView) fromViewController.view.isHidden = true } else { containerView.addSubview(toViewController.view) toViewController.view.transform = CGAffineTransform(scaleX: 1 - scaleDiff, y: 1 - scaleDiff) addShadow(toView: toViewController.view) let newOrigin = CGPoint(x: screenWidth - visibleContentWidth, y: toViewController.view.frame.origin.y) let rect = CGRect(origin: newOrigin, size: toViewController.view.frame.size) toViewController.view.frame = rect } toViewController.view.isUserInteractionEnabled = false fromViewController.view.isUserInteractionEnabled = false } private func updateTransition(percentComplete: CGFloat) { let containerView = transitionContext.containerView let screenWidth = containerView.frame.size.width let totalWidth = screenWidth - visibleContentWidth if present { let newScale = 1 - (scaleDiff * percentComplete) let newX = totalWidth * percentComplete contentSnapshotView.transform = CGAffineTransform(scaleX: newScale, y: newScale) let newOrigin = CGPoint(x: newX, y: contentSnapshotView.frame.origin.y) let rect = CGRect(origin: newOrigin, size: contentSnapshotView.frame.size) contentSnapshotView.frame = rect } else { contentSnapshotView.isHidden = true let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)! let newX = totalWidth * (1 - percentComplete) let newScale = 1 - scaleDiff + (scaleDiff * percentComplete) toViewController.view.transform = CGAffineTransform(scaleX: newScale, y: newScale) let newOrigin = CGPoint(x: newX, y: toViewController.view.frame.origin.y) let rect = CGRect(origin: newOrigin, size: toViewController.view.frame.size) toViewController.view.frame = rect } } private func finishTransition(currentPercentComplete : CGFloat) { transitionStarted = false let animation : () -> Void = { [weak self] in self?.updateTransition(percentComplete: 1.0) } let completion : (Bool) -> Void = { [weak self] _ in if let transition = self { let fromViewController = transition.transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)! let toViewController = transition.transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)! if transition.present { fromViewController.view.isHidden = false transition.contentSnapshotView.removeFromSuperview() transition.contentSnapshotView.addGestureRecognizer(transition.panRecognizer) transition.contentSnapshotView.addGestureRecognizer(transition.tapRecognizer) toViewController.view.addSubview(transition.contentSnapshotView) } else { toViewController.view.isHidden = false transition.removeShadow(fromView: toViewController.view) } toViewController.view.isUserInteractionEnabled = true fromViewController.view.isUserInteractionEnabled = true transition.transitionContext.completeTransition(true) } } guard let useFinishingSpringOption = self.useFinishingSpringOption else { return } if useFinishingSpringOption { UIView.animate(withDuration: transitionDuration - transitionDuration * Double(currentPercentComplete), delay: 0, usingSpringWithDamping: present ? finishingSpringOption.presentSpringParams.dampingRatio : finishingSpringOption.dismissSpringParams.dampingRatio, initialSpringVelocity: present ? finishingSpringOption.presentSpringParams.velocity : finishingSpringOption.dismissSpringParams.velocity, options: animationOptions, animations: animation, completion: completion) } else { UIView.animate(withDuration: transitionDuration - transitionDuration * Double(currentPercentComplete), delay: 0, options: animationOptions, animations: animation, completion: completion) } } private func cancelTransition(currentPercentComplete : CGFloat) { transitionStarted = false let animation : () -> Void = { [weak self] in self?.updateTransition(percentComplete: 0) } let completion : (Bool) -> Void = { [weak self] _ in if let transition = self { let fromViewController = transition.transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)! let toViewController = transition.transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)! if transition.present { fromViewController.view.isHidden = false } else { toViewController.view.removeFromSuperview() transition.contentSnapshotView.isHidden = false fromViewController.view.isUserInteractionEnabled = true } toViewController.view.isUserInteractionEnabled = true fromViewController.view.isUserInteractionEnabled = true transition.transitionContext.completeTransition(false) } } guard let useCancelingSpringOption = self.useCancelingSpringOption else { return } if useCancelingSpringOption { UIView.animate(withDuration: transitionDuration - transitionDuration * Double(currentPercentComplete), delay: 0, usingSpringWithDamping: present ? cancelingSpringOption.presentSpringParams.dampingRatio : cancelingSpringOption.dismissSpringParams.dampingRatio, initialSpringVelocity: present ? cancelingSpringOption.presentSpringParams.velocity : cancelingSpringOption.dismissSpringParams.velocity, options: animationOptions, animations: animation, completion: completion) } else { UIView.animate(withDuration: transitionDuration - transitionDuration * Double(currentPercentComplete), delay: 0, options: animationOptions, animations: animation, completion: completion) } } private func handlePan(recognizer: UIPanGestureRecognizer) { let translation = recognizer.translation(in: recognizer.view!.superview!) let dx = translation.x / recognizer.view!.bounds.width let progress: CGFloat = abs(dx) var velocity = recognizer.velocity(in: recognizer.view!.superview!).x if !present { velocity = -velocity } switch recognizer.state { case .began: interactionInProgress = true if velocity >= 0 { transitionShouldStarted = true if present { presentAction() } else { dismissAction() } } case .changed: if transitionStarted && (present && dx > 0 || !present && dx < 0) { updateTransition(percentComplete: progress) transitionContext.updateInteractiveTransition(progress) } case .cancelled, .ended: if transitionStarted { if progress > 0.4 && velocity >= 0 || progress > 0.01 && velocity > 100 { finishTransition(currentPercentComplete: progress) transitionContext.finishInteractiveTransition() } else { cancelTransition(currentPercentComplete: progress) transitionContext.cancelInteractiveTransition() } } else if transitionShouldStarted && !transitionStarted { if transitionStarted { DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { if self.transitionStarted { self.cancelTransition(currentPercentComplete: progress) self.transitionContext.cancelInteractiveTransition() } } } } transitionShouldStarted = false interactionInProgress = false default: break } } }
mit
58841f3e7d9a3606da6bf571068afa61
41.856448
173
0.638299
6.456745
false
false
false
false
qualaroo/QualarooSDKiOS
QualarooTests/Interactors/AnswerTextInteractorSpec.swift
1
3476
// // AnswerTextInteractorSpec.swift // QualarooTests // // Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved. // // Please refer to the LICENSE.md file for the terms and conditions // under which redistribution and use of this file is permitted. // import Foundation import Quick import Nimble @testable import Qualaroo class AnswerTextInteractorSpec: QuickSpec { override func spec() { super.spec() describe("AnswerTextInteractor") { var interactor: AnswerTextInteractor! var builder: AnswerTextResponseBuilder! var validator: AnswerTextValidator! var buttonHandler: SurveyPresenterMock! var answerHandler: SurveyInteractorMock! beforeEach { let question = try! QuestionFactory(with: JsonLibrary.question(type: "text")).build() builder = AnswerTextResponseBuilder(question: question) validator = AnswerTextValidator(question: question) buttonHandler = SurveyPresenterMock() answerHandler = SurveyInteractorMock() interactor = AnswerTextInteractor(responseBuilder: builder, validator: validator, buttonHandler: buttonHandler, answerHandler: answerHandler) } it("starts with button enabled for valid answer") { expect(buttonHandler.enableButtonFlag).to(beTrue()) } it("starts with button disabled for required question") { let dict = JsonLibrary.question(type: "text", isRequired: true) let question = try! QuestionFactory(with: dict).build() builder = AnswerTextResponseBuilder(question: question) validator = AnswerTextValidator(question: question) buttonHandler = SurveyPresenterMock() interactor = AnswerTextInteractor(responseBuilder: builder, validator: validator, buttonHandler: buttonHandler, answerHandler: SurveyInteractorMock()) expect(buttonHandler.disableButtonFlag).to(beTrue()) } it("enables button for valid answer") { buttonHandler.enableButtonFlag = false interactor.setAnswer("valid") expect(buttonHandler.enableButtonFlag).to(beTrue()) } it("disables button for invalid answer") { let dict = JsonLibrary.question(type: "text", isRequired: true) let question = try! QuestionFactory(with: dict).build() builder = AnswerTextResponseBuilder(question: question) validator = AnswerTextValidator(question: question) buttonHandler = SurveyPresenterMock() answerHandler = SurveyInteractorMock() interactor = AnswerTextInteractor(responseBuilder: builder, validator: validator, buttonHandler: buttonHandler, answerHandler: answerHandler) buttonHandler.disableButtonFlag = false interactor.setAnswer("") expect(buttonHandler.disableButtonFlag).to(beTrue()) } it("passes answer to handler") { expect(answerHandler.answerChangedValue).to(beNil()) interactor.setAnswer("test") expect(answerHandler.answerChangedValue).notTo(beNil()) } } } }
mit
9b3e124d60d63674b09f296dc119b308
41.91358
93
0.616801
5.372488
false
false
false
false
stasel/WWDC2015
StasSeldin/StasSeldin/Skills Scene/SkillsViewController.swift
1
1046
// // SkillsViewController.swift // StasSeldin // // Created by Stas Seldin on 22/04/2015. // Copyright (c) 2015 Stas Seldin. All rights reserved. // import UIKit import SpriteKit import CoreMotion class SkillsViewController: UIViewController { let scene = SkillsScene(fileNamed: "SkillsScene") override func viewDidLoad() { super.viewDidLoad() } override func viewWillLayoutSubviews() { if let skView = self.view as? SKView { if skView.scene == nil { scene!.size = self.view.frame.size scene!.scaleMode = .aspectFill skView.presentScene(scene) } } } override var shouldAutorotate: Bool { return false } @IBAction func backButtonTouched(_ sender: AnyObject) { self.dismiss(animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
a122095da7b1f84865ea078a69c5c740
22.772727
59
0.611855
4.798165
false
false
false
false
Sharelink/Bahamut
Bahamut/LinkedUserListController.swift
1
8881
// // LinkedUserListController.swift // Bahamut // // Created by AlexChow on 15/8/8. // Copyright (c) 2015年 GStudio. All rights reserved. // import UIKit //MARK: LinkedUserListController class LinkedUserListController: UITableViewController { var userListModel:[(latinLetter:String , items:[Sharelinker])] = [(latinLetter:String , items:[Sharelinker])](){ didSet{ self.tableView.reloadData() } } var linkMessageModel:[LinkMessage] = [LinkMessage]() private(set) var fileService:FileService! private(set) var userService:UserService! private var isShowing:Bool = false private(set) var notificationService:NotificationService! //MARK: notify func onServiceLogout(sender:AnyObject) { if userService != nil { ServiceContainer.instance.removeObserver(self) userService.removeObserver(self) userService = nil } } func myLinkedUsersUpdated(sender:AnyObject) { dispatch_async(dispatch_get_main_queue()){()->Void in let newValues = self.userService.myLinkedUsers let dict = self.userService.getUsersDivideWithLatinLetter(newValues) self.userListModel = dict } } func linkMessageUpdated(sender:AnyObject) { dispatch_async(dispatch_get_main_queue()){()->Void in self.linkMessageModel = self.userService.linkMessageList self.tableView.reloadData() } } func refresh() { userService.refreshMyLinkedUsers() userService.refreshLinkMessage() myLinkedUsersUpdated(userService) } override func viewDidLoad() { super.viewDidLoad() changeNavigationBarColor() self.tableView.showsHorizontalScrollIndicator = false self.tableView.showsVerticalScrollIndicator = false tableView.estimatedRowHeight = tableView.rowHeight tableView.rowHeight = UITableViewAutomaticDimension let uiview = UIView() uiview.backgroundColor = UIColor.clearColor() tableView.tableFooterView = uiview self.fileService = ServiceContainer.getService(FileService) self.userService = ServiceContainer.getService(UserService) self.notificationService = ServiceContainer.getService(NotificationService) self.initObservers() refresh() } func initObservers(){ userService.addObserver(self, selector: #selector(LinkedUserListController.myLinkedUsersUpdated(_:)), name: UserService.userListUpdated, object: nil) userService.addObserver(self, selector: #selector(LinkedUserListController.linkMessageUpdated(_:)), name: UserService.linkMessageUpdated, object: nil) userService.addObserver(self, selector: #selector(LinkedUserListController.myLinkedUsersUpdated(_:)), name: UserService.myUserInfoRefreshed, object: nil) ServiceContainer.instance.addObserver(self, selector: #selector(LinkedUserListController.onServiceLogout(_:)), name: ServiceContainer.OnServicesWillLogout, object: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) isShowing = true if let nc = self.navigationController as? UIOrientationsNavigationController { nc.lockOrientationPortrait = false } MobClick.beginLogPageView("SharelinkerList") } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) isShowing = false MobClick.endLogPageView("SharelinkerList") } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) tableView.reloadData() } //MARK: new linker @IBAction func addNewLink(sender: AnyObject) { #if APP_VERSION userService.shareAddLinkMessageToSNS(self) #else self.showAppVersionOnlyTips() #endif } @IBAction func showMyQRCode(sender: AnyObject) { let alert = UIAlertController(title: "QRCODE".localizedString(), message: nil, preferredStyle: .ActionSheet) alert.addAction(UIAlertAction(title: "SCAN_QRCODE".localizedString(), style: .Destructive) { _ in self.userService.showScanQRViewController(self.navigationController!) }) alert.addAction(UIAlertAction(title:"MY_QRCODE".localizedString(), style: .Destructive) { _ in self.userService.showMyQRViewController(self.navigationController!,sharelinkUserId: self.userService.myUserId ,avataImage: nil) }) alert.addAction(UIAlertAction(title: "CANCEL".localizedString(), style: .Cancel){ _ in}) presentViewController(alert, animated: true, completion: nil) } //MARK: actions func scrollTableViewToTop() { if userListModel.count > 0 || linkMessageModel.count > 0 { self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: .Top, animated: true) } } //MARK: table view delegate var indexOfUserList:Int{ return linkMessageModel.count > 0 ? 1 : 0 } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { //asking list,talking list + userlist.count return indexOfUserList + userListModel.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 && linkMessageModel.count > 0 { return linkMessageModel.count }else { return userListModel[section - indexOfUserList].items.count } } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIView(frame: CGRectMake(0, 0, 23, 23)) headerView.backgroundColor = UIColor.headerColor let label = UILabel(frame: CGRectMake(7, 0, 23, 23)) headerView.addSubview(label) if section == 0 && linkMessageModel.count > 0 { label.text = "LINK_MESSAGE".localizedString() }else { label.text = userListModel[section - indexOfUserList].latinLetter } label.sizeToFit() return headerView } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 0 && linkMessageModel.count > 0 { let model = linkMessageModel[indexPath.row] if model.type == LinkMessageType.AskLink.rawValue { let cell = tableView.dequeueReusableCellWithIdentifier(UIUserListAskingLinkCell.cellIdentifier, forIndexPath: indexPath) as! UIUserListAskingLinkCell cell.rootController = self cell.model = model return cell }else { let cell = tableView.dequeueReusableCellWithIdentifier(UIUserListMessageCell.cellIdentifier, forIndexPath: indexPath) as! UIUserListMessageCell cell.rootController = self cell.model = model return cell } }else { let cell = tableView.dequeueReusableCellWithIdentifier(UIUserListCell.cellIdentifier, forIndexPath: indexPath) let userModel = userListModel[indexPath.section - indexOfUserList].items[indexPath.row] as Sharelinker if let userCell = cell as? UIUserListCell { userCell.rootController = self userCell.userModel = userModel } return cell } } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { if indexPath.section == 0 && linkMessageModel.count > 0 { return true }else { return false } } override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { if indexPath.section == 0 && linkMessageModel.count > 0 { let model = linkMessageModel[indexPath.row] var actionTitle = "I_SEE".localizedString() if model.type == LinkMessageType.AskLink.rawValue { actionTitle = "IGNORE".localizedString() } let action = UITableViewRowAction(style: .Default, title: actionTitle, handler: { (ac, indexPath) -> Void in self.userService.deleteLinkMessage(model.id) }) return [action] }else { return nil } } }
mit
af8dba6ac5461dabfd6ff8896534cb3a
34.662651
176
0.637684
5.238348
false
false
false
false
ethanhuang13/blahker
Blahker/BlockerListViewController.swift
1
3249
// // ListViewController.swift // Blahker // // Created by Ethanhuang on 2016/12/4. // Copyright © 2016年 Elaborapp Co., Ltd. All rights reserved. // import UIKit class BlockerListViewController: UITableViewController { var rules = [String: [String]]() var sortedRules = [String]() override func viewDidLoad() { super.viewDidLoad() reloadData() let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(reloadData), for: .valueChanged) refreshControl.attributedTitle = NSAttributedString(string: "更新擋廣告網站清單", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]) if #available(iOS 10.0, *) { tableView.refreshControl = refreshControl } else { tableView.addSubview(refreshControl) } tableView.indicatorStyle = .white } @objc func reloadData() { guard let url = URL(string: "https://raw.githubusercontent.com/ethanhuang13/blahker/master/Blahker.safariextension/blockerList.json") else { return } UIApplication.shared.isNetworkActivityIndicatorVisible = true let session = URLSession(configuration: .default) let request = URLRequest(url: url) let task = session.dataTask(with: request) { (data, response, connectionError) in DispatchQueue.main.async { if #available(iOS 10.0, *) { self.tableView.refreshControl?.endRefreshing() } UIApplication.shared.isNetworkActivityIndicatorVisible = false } guard let data = data, let rules = try? JSONDecoder().decode([Rule].self, from: data) else { return } self.rules = [:] for rule in rules { if let domains = rule.trigger.ifDomain, let selector = rule.action.selector { for domain in domains { var selectors = self.rules[domain] ?? [] selectors.append(selector) self.rules[domain] = selectors } } else if let selector = rule.action.selector { var selectors = self.rules["Any"] ?? [] selectors.append(selector) self.rules["Any"] = selectors } } DispatchQueue.main.async { self.tableView.reloadData() } } task.resume() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { sortedRules = rules.keys.sorted() { $0 < $1 } return rules.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "rule", for: indexPath) let domain = sortedRules[indexPath.row] cell.textLabel?.text = domain cell.detailTextLabel?.text = " " + (rules[domain]?.joined(separator: ", ") ?? "") cell.detailTextLabel?.numberOfLines = 0 return cell } }
mit
bdbbd2647e152a8591da7c8c6ed8eb37
33.340426
149
0.579306
5.004651
false
false
false
false
LYM-mg/MGDS_Swift
MGDS_Swift/MGDS_Swift/Class/Music/Controller/MGRankListViewController.swift
1
4421
// // MGRankListViewController.swift // MGDS_Swift // // Created by i-Techsys.com on 17/3/1. // Copyright © 2017年 i-Techsys. All rights reserved. // import UIKit import MJRefresh private let kRankListCellID = "kRankListCellID" class MGRankListViewController: UIViewController { // MARK: 定义属性 lazy var dataSource = [SongGroup]() lazy var collectionView: UICollectionView = {[unowned self] in // 1.创建布局 let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: MGScreenW, height: MGScreenW*0.4) layout.minimumLineSpacing = 5 layout.minimumInteritemSpacing = 5 layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) // 2.创建UICollectionView let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.white collectionView.dataSource = self collectionView.delegate = self collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] collectionView.register(RankListCell.self, forCellWithReuseIdentifier: kRankListCellID) return collectionView }() override func viewDidLoad() { super.viewDidLoad() setUpMainView() setUpRefresh() } } // MARK: - UI 和 data extension MGRankListViewController { fileprivate func setUpMainView() { view.addSubview(collectionView) self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .search, target: self, action: #selector(self.searchClick)) } @objc fileprivate func searchClick() { show(SearchMusicViewController(), sender: nil) } fileprivate func setUpRefresh() { weak var weakSelf = self // 头部刷新 self.collectionView.mj_header = MJRefreshGifHeader(refreshingBlock: { let strongSelf = weakSelf strongSelf?.loadData() }) // 设置自动切换透明度(在导航栏下面自动隐藏) collectionView.mj_header?.isAutomaticallyChangeAlpha = true self.collectionView.mj_header?.beginRefreshing() } // http://tingapi.ting.baidu.com/v1/restserver/ting?channel=appstore&format=json&from=ios&kflag=1&method=baidu.ting.billboard.billCategory&operator=1&version=5.5.6 fileprivate func loadData() { let parameters: [String: Any] = ["method":"baidu.ting.billboard.billCategory","kflag":"1","from":"ios","version":"5.5.6","channel":"appstore","operator":"1","format":"json"] NetWorkTools.requestData(type: .get, urlString: "http://tingapi.ting.baidu.com/v1/restserver/ting",parameters: parameters,succeed: { [weak self] (result, err) in // 1.将result转成字典类型 guard let resultDict = result as? [String : Any] else { return } // 2.根据data该key,获取数组 guard let dataArray = resultDict["content"] as? [[String : Any]] else { return } for mdict in dataArray { self!.dataSource.append(SongGroup(dict: mdict)) } self!.collectionView.reloadData() self!.collectionView.mj_header?.endRefreshing() }) { (err) in if err != nil { self.showHint(hint: "网络请求错误❌") } self.collectionView.mj_header?.endRefreshing() } } } // MARK: - UICollectionViewDataSource extension MGRankListViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSource.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kRankListCellID, for: indexPath) as! RankListCell cell.model = dataSource[indexPath.item] return cell } } // MARK: - UICollectionViewDelegate extension MGRankListViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let vc = MGRankListDetailViewController(songGroup: dataSource[indexPath.item]) show(vc, sender: nil) } }
mit
1d1ccb935fd3a3eeee6392c5e4b988c3
36.137931
181
0.662488
4.813408
false
false
false
false
eugeneego/utilities-ios
Sources/Network/Http/Serializers/JsonModelHttpSerializer.swift
1
8590
// // JsonModelHttpSerializer // Legacy // // Copyright (c) 2015 Eugene Egorov. // License: MIT, https://github.com/eugeneego/legacy/blob/master/LICENSE // import Foundation public enum JsonModelTransformerHttpSerializerError: Error { case serialization(Error) case deserialization(Error) case transformation(Error?) } public struct JsonModelLightTransformerHttpSerializer<T: LightTransformer>: HttpSerializer { public typealias Value = T.T public typealias Error = JsonModelTransformerHttpSerializerError public let contentType: String = "application/json" public let transformer: T public init(transformer: T) { self.transformer = transformer } public func serialize(_ value: Value?) -> Result<Data, HttpSerializationError> { guard let value = transformer.to(any: value) else { return .success(Data()) } return Result( catching: { try JSONSerialization.data(withJSONObject: value, options: []) }, unknown: { HttpSerializationError.error(Error.serialization($0)) } ) } public func deserialize(_ data: Data?) -> Result<Value, HttpSerializationError> { guard let data = data, !data.isEmpty else { return Result(transformer.from(any: ()), HttpSerializationError.error(Error.transformation(nil))) } let json = Result( catching: { try JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed) }, unknown: { HttpSerializationError.error(Error.deserialization($0)) } ) return json.flatMap { json in Result(transformer.from(any: json), HttpSerializationError.error(Error.transformation(nil))) } } } public struct JsonModelTransformerHttpSerializer<T: Transformer>: HttpSerializer where T.Source == Any { public typealias Value = T.Destination public typealias Error = JsonModelTransformerHttpSerializerError public let contentType: String = "application/json" public let transformer: T public init(transformer: T) { self.transformer = transformer } public func serialize(_ value: Value?) -> Result<Data, HttpSerializationError> { guard let value = value else { return .success(Data()) } let json = transformer.transform(destination: value) return json.map( success: { json in Result( catching: { try JSONSerialization.data(withJSONObject: json, options: []) }, unknown: { HttpSerializationError.error(Error.serialization($0)) } ) }, failure: { .failure(HttpSerializationError.error(Error.transformation($0))) } ) } public func deserialize(_ data: Data?) -> Result<Value, HttpSerializationError> { guard let data = data, !data.isEmpty else { return transformer.transform(source: ()).mapError { HttpSerializationError.error(Error.transformation($0)) } } let json = Result( catching: { try JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed) }, unknown: { HttpSerializationError.error(Error.deserialization($0)) } ) return json.flatMap { json in transformer.transform(source: json).mapError { HttpSerializationError.error(Error.transformation($0)) } } } } public enum JsonModelCodableHttpSerializerError: Error { case decoding(Error) case encoding(Error) case notSupported } public struct JsonModelCodableHttpSerializer<T: Codable>: HttpSerializer { public typealias Value = T public typealias Error = JsonModelCodableHttpSerializerError public let contentType: String = "application/json" private let decoder: JSONDecoder private let encoder: JSONEncoder public init(decoder: JSONDecoder, encoder: JSONEncoder) { self.decoder = decoder self.encoder = encoder } public init( dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .deferredToDate, dataDecodingStrategy: JSONDecoder.DataDecodingStrategy = .base64, keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys, dateEncodingStrategy: JSONEncoder.DateEncodingStrategy = .deferredToDate, dataEncodingStrategy: JSONEncoder.DataEncodingStrategy = .base64, keyEncodingStrategy: JSONEncoder.KeyEncodingStrategy = .useDefaultKeys, outputFormatting: JSONEncoder.OutputFormatting = [] ) { decoder = JSONDecoder() decoder.dateDecodingStrategy = dateDecodingStrategy decoder.dataDecodingStrategy = dataDecodingStrategy decoder.keyDecodingStrategy = keyDecodingStrategy encoder = JSONEncoder() encoder.dateEncodingStrategy = dateEncodingStrategy encoder.dataEncodingStrategy = dataEncodingStrategy encoder.keyEncodingStrategy = keyEncodingStrategy encoder.outputFormatting = outputFormatting } public func serialize(_ value: Value?) -> Result<Data, HttpSerializationError> { guard let value = value else { return .success(Data()) } return Result( catching: { try encoder.encode(value) }, unknown: { HttpSerializationError.error(Error.encoding($0)) } ) } public func deserialize(_ data: Data?) -> Result<Value, HttpSerializationError> { if let nilValue = Nil() as? Value { return .success(nilValue) } guard let data = data else { return .failure(.noData) } return Result( catching: { try decoder.decode(T.self, from: data) }, unknown: { HttpSerializationError.error(Error.decoding($0)) } ) } } public struct JsonModelDecodableHttpSerializer<T: Decodable>: HttpSerializer { public typealias Value = T public typealias Error = JsonModelCodableHttpSerializerError public let contentType: String = "application/json" private let decoder: JSONDecoder public init(decoder: JSONDecoder) { self.decoder = decoder } public init( dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .deferredToDate, dataDecodingStrategy: JSONDecoder.DataDecodingStrategy = .base64, keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys ) { decoder = JSONDecoder() decoder.dateDecodingStrategy = dateDecodingStrategy decoder.dataDecodingStrategy = dataDecodingStrategy decoder.keyDecodingStrategy = keyDecodingStrategy } public func serialize(_ value: Value?) -> Result<Data, HttpSerializationError> { .failure(HttpSerializationError.error(Error.notSupported)) } public func deserialize(_ data: Data?) -> Result<Value, HttpSerializationError> { if let nilValue = Nil() as? Value { return .success(nilValue) } guard let data = data else { return .failure(.noData) } return Result( catching: { try decoder.decode(T.self, from: data) }, unknown: { HttpSerializationError.error(Error.decoding($0)) } ) } } public struct JsonModelEncodableHttpSerializer<T: Encodable>: HttpSerializer { public typealias Value = T public typealias Error = JsonModelCodableHttpSerializerError public let contentType: String = "application/json" private let encoder: JSONEncoder public init(encoder: JSONEncoder) { self.encoder = encoder } public init( dateEncodingStrategy: JSONEncoder.DateEncodingStrategy = .deferredToDate, dataEncodingStrategy: JSONEncoder.DataEncodingStrategy = .base64, keyEncodingStrategy: JSONEncoder.KeyEncodingStrategy = .useDefaultKeys, outputFormatting: JSONEncoder.OutputFormatting = [] ) { encoder = JSONEncoder() encoder.dateEncodingStrategy = dateEncodingStrategy encoder.dataEncodingStrategy = dataEncodingStrategy encoder.keyEncodingStrategy = keyEncodingStrategy encoder.outputFormatting = outputFormatting } public func serialize(_ value: Value?) -> Result<Data, HttpSerializationError> { guard let value = value else { return .success(Data()) } return Result( catching: { try encoder.encode(value) }, unknown: { HttpSerializationError.error(Error.encoding($0)) } ) } public func deserialize(_ data: Data?) -> Result<Value, HttpSerializationError> { .failure(HttpSerializationError.error(Error.notSupported)) } } public struct Nil: Codable { }
mit
c271055d2a970478c1831c3f984d7462
34.791667
120
0.679627
5.34204
false
false
false
false
jindulys/EbloVaporServer
Sources/App/Models/StringParsedDateComponents.swift
1
2963
// // DateTool.swift // EbloVaporServer // // Created by yansong li on 2017-05-24. // // import Foundation /// A tool for handling all kinds of date related operation. enum StringParsedDateComponents { static let monthPattern = "Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)?|Nov(ember)?|Dec(ember)?" static let dayPattern = "\\d{2}|\\d{1}" static let yearPattern = "\\d{4}" case Month(Int) case Day(Int) case Year(Int) case None /// Return first met month from a string static func month(from: String) -> StringParsedDateComponents { let matched = from.match(pattern: self.monthPattern) if matched != "" { switch matched { case "Jan", "January": return .Month(1) case "Feb", "February": return .Month(2) case "Mar", "March": return .Month(3) case "Apr", "April": return .Month(4) case "May": return .Month(5) case "Jun", "June": return .Month(6) case "Jul", "July": return .Month(7) case "Aug", "August": return .Month(8) case "Sep", "September": return .Month(9) case "Oct", "October": return .Month(10) case "Nov", "November": return .Month(11) case "Dec", "December": return .Month(12) default: return .None } } return .None } /// Return first met day from a string static func day(from: String) -> StringParsedDateComponents { let matched = from.match(pattern: self.dayPattern) if matched != "", let matchedInt = Int(matched) { return .Day(matchedInt) } return .None } /// Return first met year from a string static func year(from: String) -> StringParsedDateComponents { let matched = from.match(pattern: self.yearPattern) if matched != "", let matchedInt = Int(matched) { return .Year(matchedInt) } return .None } } extension StringParsedDateComponents: CustomDebugStringConvertible { var debugDescription: String { switch self { case let .Month(month): return "Month \(month)" case let .Day(day): return "Day \(day)" case let .Year(year): return "Year \(year)" case .None: return "None" } } } extension StringParsedDateComponents { // Generate a date from enumeration. static func dateFrom(year: StringParsedDateComponents, month: StringParsedDateComponents, day: StringParsedDateComponents) -> Date? { guard case let .Year(yearInt) = year, case let .Month(monthInt) = month, case let .Day(dayInt) = day else { return nil } let calendar = NSCalendar(identifier: .gregorian) var components = DateComponents() components.year = yearInt components.month = monthInt components.day = dayInt return calendar?.date(from: components) } }
mit
8b06865b8848c138be37c9dd5e7872da
24.765217
148
0.603105
3.99865
false
false
false
false
ReactiveX/RxSwift
Tests/RxCocoaTests/Driver+Test.swift
1
20581
// // Driver+Test.swift // Tests // // Created by Krunoslav Zaher on 10/14/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Dispatch import RxSwift import RxCocoa import RxRelay import XCTest import RxTest class DriverTest: SharedSequenceTest { } // MARK: properties extension DriverTest { func testDriverSharing_WhenErroring() { let scheduler = TestScheduler(initialClock: 0) let observer1 = scheduler.createObserver(Int.self) let observer2 = scheduler.createObserver(Int.self) let observer3 = scheduler.createObserver(Int.self) var disposable1: Disposable! var disposable2: Disposable! var disposable3: Disposable! let coldObservable = scheduler.createColdObservable([ .next(10, 0), .next(20, 1), .next(30, 2), .next(40, 3), .error(50, testError) ]) let driver = coldObservable.asDriver(onErrorJustReturn: -1) scheduler.scheduleAt(200) { disposable1 = driver.asObservable().subscribe(observer1) } scheduler.scheduleAt(225) { disposable2 = driver.asObservable().subscribe(observer2) } scheduler.scheduleAt(235) { disposable1.dispose() } scheduler.scheduleAt(260) { disposable2.dispose() } // resubscription scheduler.scheduleAt(260) { disposable3 = driver.asObservable().subscribe(observer3) } scheduler.scheduleAt(285) { disposable3.dispose() } scheduler.start() XCTAssertEqual(observer1.events, [ .next(210, 0), .next(220, 1), .next(230, 2) ]) XCTAssertEqual(observer2.events, [ .next(225, 1), .next(230, 2), .next(240, 3), .next(250, -1), .completed(250) ]) XCTAssertEqual(observer3.events, [ .next(270, 0), .next(280, 1), ]) XCTAssertEqual(coldObservable.subscriptions, [ Subscription(200, 250), Subscription(260, 285), ]) } func testDriverSharing_WhenCompleted() { let scheduler = TestScheduler(initialClock: 0) let observer1 = scheduler.createObserver(Int.self) let observer2 = scheduler.createObserver(Int.self) let observer3 = scheduler.createObserver(Int.self) var disposable1: Disposable! var disposable2: Disposable! var disposable3: Disposable! let coldObservable = scheduler.createColdObservable([ .next(10, 0), .next(20, 1), .next(30, 2), .next(40, 3), .completed(50) ]) let driver = coldObservable.asDriver(onErrorJustReturn: -1) scheduler.scheduleAt(200) { disposable1 = driver.asObservable().subscribe(observer1) } scheduler.scheduleAt(225) { disposable2 = driver.asObservable().subscribe(observer2) } scheduler.scheduleAt(235) { disposable1.dispose() } scheduler.scheduleAt(260) { disposable2.dispose() } // resubscription scheduler.scheduleAt(260) { disposable3 = driver.asObservable().subscribe(observer3) } scheduler.scheduleAt(285) { disposable3.dispose() } scheduler.start() XCTAssertEqual(observer1.events, [ .next(210, 0), .next(220, 1), .next(230, 2) ]) XCTAssertEqual(observer2.events, [ .next(225, 1), .next(230, 2), .next(240, 3), .completed(250) ]) XCTAssertEqual(observer3.events, [ .next(270, 0), .next(280, 1), ]) XCTAssertEqual(coldObservable.subscriptions, [ Subscription(200, 250), Subscription(260, 285), ]) } } // MARK: conversions extension DriverTest { func testBehaviorRelayAsDriver() { let hotObservable: BehaviorRelay<Int> = BehaviorRelay(value: 0) let xs = Driver.zip(hotObservable.asDriver(), Driver.of(0, 0, 0)) { x, _ in return x } let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(xs, expectationFulfilled: { $0 == 2 }) { hotObservable.accept(1) hotObservable.accept(2) } XCTAssertEqual(results, [0, 1, 2]) } func testInfallibleAsDriver() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() let xs = hotObservable.asInfallible(onErrorJustReturn: -1).asDriver() let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(xs) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.next(1)) hotObservable.on(.next(2)) hotObservable.on(.error(testError)) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [1, 2, -1]) } func testAsDriver_onErrorJustReturn() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() let xs = hotObservable.asDriver(onErrorJustReturn: -1) let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(xs) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.next(1)) hotObservable.on(.next(2)) hotObservable.on(.error(testError)) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [1, 2, -1]) } func testAsDriver_onErrorDriveWith() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() let xs = hotObservable.asDriver(onErrorDriveWith: Driver.just(-1)) let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(xs) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.next(1)) hotObservable.on(.next(2)) hotObservable.on(.error(testError)) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [1, 2, -1]) } func testAsDriver_onErrorRecover() { let hotObservable = BackgroundThreadPrimitiveHotObservable<Int>() let xs = hotObservable.asDriver { _ in return Driver.empty() } let results = subscribeTwiceOnBackgroundSchedulerAndOnlyOneSubscription(xs) { XCTAssertTrue(hotObservable.subscriptions == [SubscribedToHotObservable]) hotObservable.on(.next(1)) hotObservable.on(.next(2)) hotObservable.on(.error(testError)) XCTAssertTrue(hotObservable.subscriptions == [UnsunscribedFromHotObservable]) } XCTAssertEqual(results, [1, 2]) } } // MARK: correct order of sync subscriptions extension DriverTest { func testDrivingOrderOfSynchronousSubscriptions1() { func prepareSampleDriver(with item: String) -> Driver<String> { return Observable.create { observer in observer.onNext(item) observer.onCompleted() return Disposables.create() } .asDriver(onErrorJustReturn: "") } var disposeBag = DisposeBag() let scheduler = TestScheduler(initialClock: 0) let observer = scheduler.createObserver(String.self) let relay = BehaviorRelay(value: "initial") relay.asDriver() .drive(observer) .disposed(by: disposeBag) prepareSampleDriver(with: "first") .drive(relay) .disposed(by: disposeBag) prepareSampleDriver(with: "second") .drive(relay) .disposed(by: disposeBag) Observable.just("third") .bind(to: relay) .disposed(by: disposeBag) disposeBag = DisposeBag() XCTAssertEqual(observer.events, [ .next(0, "initial"), .next(0, "first"), .next(0, "second"), .next(0, "third") ]) } func testDrivingOrderOfSynchronousSubscriptions2() { var latestValue: Int? let state = BehaviorSubject(value: 1) let subscription = state.asDriver(onErrorJustReturn: 0) .flatMapLatest { x in return Driver.just(x * 2) } .flatMapLatest { y in return Observable.just(y).asDriver(onErrorJustReturn: -1) } .flatMapLatest { y in return Observable.just(y).asDriver(onErrorDriveWith: Driver.empty()) } .flatMapLatest { y in return Observable.just(y).asDriver(onErrorRecover: { _ in Driver.empty() }) } .drive(onNext: { element in latestValue = element }) subscription.dispose() XCTAssertEqual(latestValue, 2) } } // MARK: drive observer extension DriverTest { func testDriveObserver() { var events: [Recorded<Event<Int>>] = [] let observer: AnyObserver<Int> = AnyObserver { event in events.append(Recorded(time: 0, value: event)) } _ = (Driver.just(1) as Driver<Int>).drive(observer) XCTAssertEqual(events.first?.value.element.flatMap { $0 }, 1) } func testDriveObservers() { var events1: [Recorded<Event<Int>>] = [] var events2: [Recorded<Event<Int>>] = [] let observer1: AnyObserver<Int> = AnyObserver { event in events1.append(Recorded(time: 0, value: event)) } let observer2: AnyObserver<Int> = AnyObserver { event in events2.append(Recorded(time: 0, value: event)) } _ = (Driver.just(1) as Driver<Int>).drive(observer1, observer2) XCTAssertEqual(events1, [ .next(1), .completed() ]) XCTAssertEqual(events2, [ .next(1), .completed() ]) } func testDriveOptionalObserver() { var events: [Recorded<Event<Int?>>] = [] let observer: AnyObserver<Int?> = AnyObserver { event in events.append(Recorded(time: 0, value: event)) } _ = (Driver.just(1) as Driver<Int>).drive(observer) XCTAssertEqual(events.first?.value.element.flatMap { $0 }, 1) } func testDriveOptionalObservers() { var events1: [Recorded<Event<Int?>>] = [] var events2: [Recorded<Event<Int?>>] = [] let observer1: AnyObserver<Int?> = AnyObserver { event in events1.append(Recorded(time: 0, value: event)) } let observer2: AnyObserver<Int?> = AnyObserver { event in events2.append(Recorded(time: 0, value: event)) } _ = (Driver.just(1) as Driver<Int>).drive(observer1, observer2) XCTAssertEqual(events1, [ .next(1), .completed() ]) XCTAssertEqual(events2, [ .next(1), .completed() ]) } func testDriveNoAmbiguity() { var events: [Recorded<Event<Int?>>] = [] let observer: AnyObserver<Int?> = AnyObserver { event in events.append(Recorded(time: 0, value: event)) } // shouldn't cause compile time error _ = Driver.just(1).drive(observer) XCTAssertEqual(events.first?.value.element.flatMap { $0 }, 1) } } // MARK: drive optional behavior relay extension DriverTest { func testDriveBehaviorRelay() { let relay = BehaviorRelay<Int>(value: 0) let subscription = (Driver.just(1) as Driver<Int>).drive(relay) XCTAssertEqual(relay.value, 1) subscription.dispose() } func testDriveBehaviorRelays() { let relay1 = BehaviorRelay<Int>(value: 0) let relay2 = BehaviorRelay<Int>(value: 0) _ = Driver.just(1).drive(relay1, relay2) XCTAssertEqual(relay1.value, 1) XCTAssertEqual(relay2.value, 1) } func testDriveOptionalBehaviorRelay1() { let relay = BehaviorRelay<Int?>(value: 0) _ = (Driver.just(1) as Driver<Int>).drive(relay) XCTAssertEqual(relay.value, 1) } func testDriveOptionalBehaviorRelays1() { let relay1 = BehaviorRelay<Int?>(value: 0) let relay2 = BehaviorRelay<Int?>(value: 0) _ = (Driver.just(1) as Driver<Int>).drive(relay1, relay2) XCTAssertEqual(relay1.value, 1) XCTAssertEqual(relay2.value, 1) } func testDriveOptionalBehaviorRelay2() { let relay = BehaviorRelay<Int?>(value: 0) _ = (Driver.just(1) as Driver<Int?>).drive(relay) XCTAssertEqual(relay.value, 1) } func testDriveOptionalBehaviorRelays2() { let relay1 = BehaviorRelay<Int?>(value: 0) let relay2 = BehaviorRelay<Int?>(value: 0) _ = (Driver.just(1) as Driver<Int?>).drive(relay1, relay2) XCTAssertEqual(relay1.value, 1) XCTAssertEqual(relay2.value, 1) } func testDriveBehaviorRelayNoAmbiguity() { let relay = BehaviorRelay<Int?>(value: 0) // shouldn't cause compile time error _ = Driver.just(1).drive(relay) XCTAssertEqual(relay.value, 1) } } // MARK: drive optional behavior relay extension DriverTest { func testDriveReplayRelay() { let relay = ReplayRelay<Int>.create(bufferSize: 1) var latest: Int? _ = relay.subscribe(onNext: { latestElement in latest = latestElement }) _ = (Driver.just(1) as Driver<Int>).drive(relay) XCTAssertEqual(latest, 1) } func testDriveReplayRelays() { let relay1 = ReplayRelay<Int>.create(bufferSize: 1) let relay2 = ReplayRelay<Int>.create(bufferSize: 1) var latest1: Int? var latest2: Int? _ = relay1.subscribe(onNext: { latestElement in latest1 = latestElement }) _ = relay2.subscribe(onNext: { latestElement in latest2 = latestElement }) _ = (Driver.just(1) as Driver<Int>).drive(relay1, relay2) XCTAssertEqual(latest1, 1) XCTAssertEqual(latest2, 1) } func testDriveOptionalReplayRelay1() { let relay = ReplayRelay<Int?>.create(bufferSize: 1) var latest: Int? = nil _ = relay.subscribe(onNext: { latestElement in latest = latestElement }) _ = (Driver.just(1) as Driver<Int>).drive(relay) XCTAssertEqual(latest, 1) } func testDriveOptionalReplayRelays() { let relay1 = ReplayRelay<Int?>.create(bufferSize: 1) let relay2 = ReplayRelay<Int?>.create(bufferSize: 1) var latest1: Int? var latest2: Int? _ = relay1.subscribe(onNext: { latestElement in latest1 = latestElement }) _ = relay2.subscribe(onNext: { latestElement in latest2 = latestElement }) _ = (Driver.just(1) as Driver<Int>).drive(relay1, relay2) XCTAssertEqual(latest1, 1) XCTAssertEqual(latest2, 1) } func testDriveOptionalReplayRelay2() { let relay = ReplayRelay<Int?>.create(bufferSize: 1) var latest: Int? _ = relay.subscribe(onNext: { latestElement in latest = latestElement }) _ = (Driver.just(1) as Driver<Int?>).drive(relay) XCTAssertEqual(latest, 1) } func testDriveReplayRelays2() { let relay1 = ReplayRelay<Int?>.create(bufferSize: 1) let relay2 = ReplayRelay<Int?>.create(bufferSize: 1) var latest1: Int? var latest2: Int? _ = relay1.subscribe(onNext: { latestElement in latest1 = latestElement }) _ = relay2.subscribe(onNext: { latestElement in latest2 = latestElement }) _ = (Driver.just(1) as Driver<Int?>).drive(relay1, relay2) XCTAssertEqual(latest1, 1) XCTAssertEqual(latest2, 1) } func testDriveReplayRelayNoAmbiguity() { let relay = ReplayRelay<Int?>.create(bufferSize: 1) var latest: Int? = nil _ = relay.subscribe(onNext: { latestElement in latest = latestElement }) // shouldn't cause compile time error _ = Driver.just(1).drive(relay) XCTAssertEqual(latest, 1) } } // MARK: - Drive with object extension DriverTest { func testDriveWithNext() { var testObject: TestObject! = TestObject() let scheduler = TestScheduler(initialClock: 0) var values = [String]() var disposed: UUID? let coldObservable = scheduler.createColdObservable([ .next(10, 0), .next(20, 1), .next(30, 2), .next(40, 3), .completed(50) ]) let driver = coldObservable.asDriver(onErrorJustReturn: -1) _ = driver .drive( with: testObject, onNext: { object, value in values.append(object.id.uuidString + "\(value)") }, onDisposed: { disposed = $0.id } ) scheduler.start() let uuid = testObject.id XCTAssertEqual(values, [ uuid.uuidString + "0", uuid.uuidString + "1", uuid.uuidString + "2", uuid.uuidString + "3" ]) XCTAssertEqual(disposed, uuid) XCTAssertNotNil(testObject) testObject = nil XCTAssertNil(testObject) } func testDriveWithError() { var testObject: TestObject! = TestObject() let scheduler = TestScheduler(initialClock: 0) var values = [String]() var disposed: UUID? let coldObservable = scheduler.createColdObservable([ .next(10, 0), .next(20, 1), .next(30, 2), .error(40, testError), .next(50, 3) ]) let driver = coldObservable.asDriver(onErrorJustReturn: -1) _ = driver .drive( with: testObject, onNext: { object, value in values.append(object.id.uuidString + "\(value)") }, onDisposed: { disposed = $0.id } ) scheduler.start() let uuid = testObject.id XCTAssertEqual(values, [ uuid.uuidString + "0", uuid.uuidString + "1", uuid.uuidString + "2", uuid.uuidString + "-1" ]) XCTAssertEqual(disposed, uuid) XCTAssertNotNil(testObject) testObject = nil XCTAssertNil(testObject) } func testDriveWithCompleted() { var testObject: TestObject! = TestObject() let scheduler = TestScheduler(initialClock: 0) var values = [String]() var disposed: UUID? var completed: UUID? let coldObservable = scheduler.createColdObservable([ .next(10, 0), .next(20, 1), .next(30, 2), .completed(40) ]) let driver = coldObservable.asDriver(onErrorJustReturn: -1) _ = driver .drive( with: testObject, onNext: { object, value in values.append(object.id.uuidString + "\(value)") }, onCompleted: { completed = $0.id }, onDisposed: { disposed = $0.id } ) scheduler.start() let uuid = testObject.id XCTAssertEqual(values, [ uuid.uuidString + "0", uuid.uuidString + "1", uuid.uuidString + "2" ]) XCTAssertEqual(disposed, uuid) XCTAssertEqual(completed, uuid) XCTAssertNotNil(testObject) testObject = nil XCTAssertNil(testObject) } } private class TestObject: NSObject { var id = UUID() }
mit
7bb1dc281e1283da37b8ef6e57d57ea6
27.386207
120
0.56346
4.656109
false
true
false
false
lemberg/connfa-ios
Connfa/Classes/Events/Program List/ProgramListFilter/ProgramListFilter.swift
1
5165
// // ProgramListFilter.swift // Connfa // // Created by Volodymyr Hyrka on 11/24/17. // Copyright © 2017 Lemberg Solution. All rights reserved. // import Foundation class ProgramListFilter: Codable { class FilterItem: Codable, Hashable { var title: String var mark = false var hashValue: Int { return title.hashValue } init(title: String) { self.title = title } static func == (lhs: ProgramListFilter.FilterItem, rhs: ProgramListFilter.FilterItem) -> Bool { return lhs.title == rhs.title } } var types: [FilterItem] var levels: [FilterItem] var tracks: [FilterItem] init(types: [String], levels: [String], tracks: [String]) { self.types = types.map { FilterItem(title: $0) } self.levels = levels.map { FilterItem(title: $0) } self.tracks = tracks.map { FilterItem(title: $0) } } convenience init() { self.init(types: [], levels: [], tracks: []) } public var isEmpty: Bool { return !needFilter(conditions: types) && !needFilter(conditions: levels) && !needFilter(conditions: tracks) } public func reset() { types.forEach { $0.mark = false } levels.forEach { $0.mark = false } tracks.forEach { $0.mark = false } } /// Merge new filter with existing one without loosing mark /// /// - Parameter filter: newFilter public func merge(with filter: ProgramListFilter) { let oldTypesSet = Set(self.types) let newTypesSet = Set(filter.types) let oldlevelsSet = Set(self.levels) let newlevelsSet = Set(filter.levels) let oldTracksSet = Set(self.tracks) let newTracksSet = Set(filter.tracks) let typesIntersec = oldTypesSet.intersection(newTypesSet) let levelsIntersec = oldlevelsSet.intersection(newlevelsSet) let tracksIntersec = oldTracksSet.intersection(newTracksSet) let typesSubstract = newTypesSet.subtracting(oldTypesSet) let levelsSubstract = newlevelsSet.subtracting(oldlevelsSet) let tracksSubstract = newTracksSet.subtracting(oldTracksSet) // Intersection var newTypes = self.types.filter{ typesIntersec.contains($0) } var newLevels = self.levels.filter{ levelsIntersec.contains($0) } var newTracks = self.tracks.filter{ tracksIntersec.contains($0) } // Union with substraction newTypes.append(contentsOf: typesSubstract) newLevels.append(contentsOf: levelsSubstract) newTracks.append(contentsOf: tracksSubstract) self.types = newTypes self.levels = newLevels self.tracks = newTracks } public func apply(for events: [EventModel]) -> [EventModel] { var result = events if needFilter(conditions: types) { let typeFilters = map(conditions: types) result = result.filter { if let type = $0.type { return typeFilters.contains(type) } return false } } if needFilter(conditions: levels) { let levelFilters = map(conditions: levels) result = result.filter { let eventHasNoLevel = $0.experienceLevel < 0 if eventHasNoLevel { return true } if let expLevel = ExperienceLevel(rawValue: $0.experienceLevel) { return levelFilters.contains(expLevel.description) } return false } } if needFilter(conditions: tracks) { let trackFilters = map(conditions: tracks) result = result.filter { if let track = $0.track { return trackFilters.contains(track) } return false } } return result } public var filterInfo: String { let adapter = ProgramListFilterAdapter() let infoTypes = map(conditions: types) let infoLevels = map(conditions: levels) let infoTracks = map(conditions: tracks) return adapter.fullString(types: infoTypes, specialTypeMarked: specialTypeMarked, levels: infoLevels, tracks: infoTracks) } /// Currently only events with type 'Session' has experiance levels: Beginner/Intermediate/Advanced. private let specialType = "Session" var specialTypeMarked: Bool { var result = false for item in types { if item.title == self.specialType && item.mark == true { result = true break } } return result } //MARK: - private /// Check if events needed to filter by conditions. There is no need to filter conditions in case all marked or all not marked. Filtering needed if only few marked. /// /// - Parameter conditions: Array of FilterItem for specific parameter type/level/track /// - Returns: true - need to filter / false - no need private func needFilter(conditions: [FilterItem]) -> Bool { let total = conditions.count let marked = conditions.filter { $0.mark }.count return !(marked == 0 || marked == total) } /// Map string values of FilterItems if it's marked /// /// - Parameter conditions: Array of FilterItem for specific parameter type/level/track /// - Returns: values fo filtering private func map(conditions: [FilterItem]) -> [String] { return conditions.compactMap{ $0.mark ? $0.title : nil } } }
apache-2.0
a2ccbb712e3a59dac8fdb701ba70f831
29.556213
166
0.65763
4.072555
false
false
false
false
teklabs/MyTabBarApp
MyTabBarApp/ItemListViewController.swift
1
5383
// // ItemListViewController.swift // MyTabBarApp // // Created by teklabsco on 11/23/15. // Copyright © 2015 Teklabs, LLC. All rights reserved. // import UIKit //import Item var itemObjects:[String] = [String]() var currentItemIndex:Int = 0 var itemListView:ItemListViewController? var itemDetailViewController:ItemDetailViewController? let kItems:String = "items" let BLANK_ITEM_TITLE:String = "(New Item TITLE)" class ItemListViewController: UITableViewController { //@IBOutlet var addItemButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. itemListView = self load() self.navigationItem.leftBarButtonItem = self.editButtonItem() let addItemButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:") self.navigationItem.rightBarButtonItem = addItemButton } override func viewWillAppear(animated: Bool) { //self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed save() super.viewWillAppear(animated) } override func viewDidAppear(animated: Bool) { if itemObjects.count == 0 { insertNewObject(self) } super.viewDidAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(sender: AnyObject) { if detailViewController?.detailDescriptionLabel.editable == false { return } if itemObjects.count == 0 || itemObjects[0] != BLANK_ITEM_TITLE { itemObjects.insert(BLANK_ITEM_TITLE, atIndex: 0) let indexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } currentIndex = 0 self.performSegueWithIdentifier("showItemDetail", sender: self) } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return itemObjects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let itemObject = itemObjects[indexPath.row] cell.textLabel!.text = itemObject return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { itemObjects.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } override func setEditing(editing: Bool, animated: Bool) { super.setEditing(editing, animated:animated) if editing { detailViewController?.detailDescriptionLabel.editable = false detailViewController?.detailDescriptionLabel.text = "" return } save() } override func tableView(tableView: UITableView, didEndEditingRowAtIndexPath indexPath: NSIndexPath) { detailViewController?.detailDescriptionLabel.editable = false detailViewController?.detailDescriptionLabel.text = "" save() } override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { print("Made it to selection.") self.performSegueWithIdentifier("showItemDetail", sender: self) } func save() { NSUserDefaults.standardUserDefaults().setObject(itemObjects, forKey: kItems) NSUserDefaults.standardUserDefaults().synchronize() } func load() { if let loadedData = NSUserDefaults.standardUserDefaults().arrayForKey(kItems) as? [String] { itemObjects = loadedData } } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { detailViewController?.detailDescriptionLabel.editable = true if segue.identifier == "showItemDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { currentIndex = indexPath.row } let itemObject = itemObjects[currentIndex] detailViewController?.detailItem = itemObject //detailItemViewController?.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() detailViewController?.navigationItem.leftItemsSupplementBackButton = true } } }
gpl-3.0
735169b7aa46ae03d6c900d238ec93f0
34.414474
157
0.666852
5.707317
false
false
false
false
whiteshadow-gr/HatForIOS
HAT/Objects/Profile/Info/HATProfileInfoObject.swift
1
5164
/** * Copyright (C) 2018 HAT Data Exchange Ltd * * SPDX-License-Identifier: MPL2 * * This file is part of the Hub of All Things project (HAT). * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ import SwiftyJSON // MARK: Struct public struct HATProfileInfo: HatApiType, HATObject, Comparable { // MARK: - Comparable protocol /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func == (lhs: HATProfileInfo, rhs: HATProfileInfo) -> Bool { return (lhs.recordID == rhs.recordID) } /// Returns a Boolean value indicating whether the value of the first /// argument is less than that of the second argument. /// /// This function is the only requirement of the `Comparable` protocol. The /// remainder of the relational operator functions are implemented by the /// standard library for any type that conforms to `Comparable`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func < (lhs: HATProfileInfo, rhs: HATProfileInfo) -> Bool { return lhs.recordID < rhs.recordID } // MARK: - Coding Keys /** The JSON fields used by the hat The Fields are the following: * `dateOfBirth` in JSON is `dateOfBirth` * `gender` in JSON is `gender` * `incomeGroup` in JSON is `incomeGroup` * `recordID` in JSON is `recordId` */ private enum CodingKeys: String, CodingKey { case dateOfBirth = "dateOfBirth" case gender = "gender" case incomeGroup = "incomeGroup" case recordID = "recordId" } // MARK: - Variables /// User's data of birth public var dateOfBirth: Date = Date() /// User's gender public var gender: String = "" /// User's income group public var incomeGroup: String = "" /// Record ID public var recordID: String = "-1" // MARK: - Initialisers /** The default initialiser. Initialises everything to default values. */ public init() { dateOfBirth = Date() gender = "" incomeGroup = "" recordID = "-1" } /** It initialises everything from the received JSON file from the HAT - dict: The JSON file received from the HAT */ public init(from dict: JSON) { if let data: [String: JSON] = (dict["data"].dictionary) { if let tempGender: String = (data[CodingKeys.gender.rawValue]?.stringValue) { gender = tempGender } if let tempIncomeGroup: String = (data[CodingKeys.incomeGroup.rawValue]?.stringValue) { incomeGroup = tempIncomeGroup } if let tempDateOfBirth: String = (data[CodingKeys.dateOfBirth.rawValue]?.stringValue) { if let tempDate: Date = HATFormatterHelper.formatStringToDate(string: tempDateOfBirth) { dateOfBirth = tempDate } } } recordID = (dict[CodingKeys.recordID.rawValue].stringValue) } /** It initialises everything from the received JSON file from the HAT - dict: The JSON file received from the HAT */ public mutating func initialize(fromCache: Dictionary<String, Any>) { if let tempGender: Any = fromCache[CodingKeys.gender.rawValue] { gender = String(describing: tempGender) } if let tempIncomeGroup: Any = fromCache[CodingKeys.incomeGroup.rawValue] { incomeGroup = String(describing: tempIncomeGroup) } if let tempDateOfBirth: Any = fromCache[CodingKeys.dateOfBirth.rawValue] { let temp: String = String(describing: tempDateOfBirth) if let date: Date = HATFormatterHelper.formatStringToDate(string: temp) { dateOfBirth = date } } } // MARK: - JSON Mapper /** Returns the object as Dictionary, JSON - returns: Dictionary<String, String> */ public func toJSON() -> Dictionary<String, Any> { return [ CodingKeys.dateOfBirth.rawValue: HATFormatterHelper.formatDateToISO(date: self.dateOfBirth), CodingKeys.gender.rawValue: self.gender, CodingKeys.incomeGroup.rawValue: self.incomeGroup, "unixTimeStamp": Int(HATFormatterHelper.formatDateToEpoch(date: Date())!)! ] } }
mpl-2.0
ade9ab53fdb36890ebdb840ba6bf2d9f
29.376471
104
0.572812
4.853383
false
false
false
false
rustedivan/tapmap
tapmap/Rendering/LabelLayout.swift
1
6620
// // LabelLayout.swift // tapmap // // Created by Ivan Milles on 2021-01-16. // Copyright © 2021 Wildbrain. All rights reserved. // import Foundation import CoreGraphics.CGGeometry import UIKit.UIScreen enum LayoutAnchor { case NE case SE case NW case SW case Center var next: LayoutAnchor? { switch self { case .NE: return .SE case .SE: return .NW case .NW: return .SW case .SW: return nil case .Center: return nil } } } struct LabelMarker: Comparable { let name: String let ownerHash: Int let worldPos: Vertex let kind: GeoPlace.Kind let rank: Int init(for poi: GeoPlace) { name = poi.name ownerHash = poi.hashValue worldPos = poi.location kind = poi.kind rank = poi.rank } var displayText: NSString { return ((kind == .Region) ? name.uppercased() : name) as NSString } static func < (lhs: LabelMarker, rhs: LabelMarker) -> Bool { let lhsScore = lhs.rank - (lhs.kind == .Region ? 1 : 0) // Value regions one step higher let rhsScore = rhs.rank - (rhs.kind == .Region ? 1 : 0) return lhsScore < rhsScore } } struct LabelPlacement: Codable, Hashable { enum CodingKeys: CodingKey { case aabb } var markerHash: Int = 0 let aabb: Aabb var anchor: LayoutAnchor = .NE var debugName: String = "Unknown" init(markerHash: Int, aabb: Aabb, anchor: LayoutAnchor, debugName: String) { self.markerHash = markerHash self.aabb = aabb self.anchor = anchor self.debugName = debugName } func hash(into hasher: inout Hasher) { hasher.combine(markerHash) } } typealias MeasureFunction = (LabelMarker) -> (w: Float, h: Float) typealias LabelLayout = [Int : LabelPlacement] class LabelLayoutEngine { let maxLabels: Int let space: Aabb let measure: MeasureFunction var labelMargin: Float = 3.0 var labelDistance: Float = 2.0 var orderedLayout: [LabelPlacement] = [] var labelSizeCache: [Int : (w: Float, h: Float)] = [:] // $ Limit size of this init(maxLabels: Int, space: Aabb, measure: @escaping MeasureFunction) { self.maxLabels = maxLabels self.space = space self.measure = measure } // $ Re-implement zoom culling as a 3D box sweeping through point cloud func layoutLabels(markers: [Int: LabelMarker], projection project: (Vertex) -> CGPoint) -> (layout: LabelLayout, removed: [Int]) { // Collision detection structure for screen-space layout var labelQuadTree = QuadTree<LabelPlacement>(minX: space.minX, minY: space.minY, maxX: space.maxX, maxY: space.maxY, maxDepth: 6) var workingSet = markers var removedFromLayout: [Int] = [] // Move and insert the previously placed labels in their established order for (i, placement) in orderedLayout.enumerated() { guard let marker = workingSet[placement.markerHash] else { removedFromLayout.append(placement.markerHash) continue } let result = layoutLabel(marker: marker, in: labelQuadTree, startAnchor: placement.anchor, projection: project) if let (labelBox, layoutBox, anchor) = result { let reprojectedPlacement = LabelPlacement(markerHash: marker.ownerHash, aabb: labelBox, anchor: anchor, debugName: marker.name) labelQuadTree.insert(value: reprojectedPlacement, region: layoutBox, clipToBounds: true) orderedLayout[i] = LabelPlacement(markerHash: placement.markerHash, aabb: labelBox, anchor: anchor, debugName: marker.name) } else { removedFromLayout.append(placement.markerHash) } workingSet.removeValue(forKey: placement.markerHash) } orderedLayout.removeAll { removedFromLayout.contains($0.markerHash) } // Layout new incoming markers let markersToLayout = Array(workingSet.values).sorted(by: <) for marker in markersToLayout { guard orderedLayout.count < maxLabels else { break } let startAnchor: LayoutAnchor = (marker.kind == .Region ? .Center : .NE) // Choose starting layout anchor let result = layoutLabel(marker: marker, in: labelQuadTree, startAnchor: startAnchor, projection: project) if let (labelBox, layoutBox, anchor) = result { let placement = LabelPlacement(markerHash: marker.ownerHash, aabb: labelBox, anchor: anchor, debugName: marker.name) // Unpadded aabb for layout labelQuadTree.insert(value: placement, region: layoutBox, clipToBounds: true) // Padded aabb for collision orderedLayout.append(placement) } } let layoutEntries = orderedLayout.map { ($0.markerHash, $0) } let layout: LabelLayout = Dictionary(uniqueKeysWithValues: layoutEntries) return (layout: layout, removed: removedFromLayout) } func layoutLabel(marker: LabelMarker, in layout: QuadTree<LabelPlacement>, startAnchor: LayoutAnchor, projection project: (Vertex) -> CGPoint) -> (labelBox: Aabb, layoutBox: Aabb, anchor: LayoutAnchor)? { var anchor: LayoutAnchor? = startAnchor let origin = project(marker.worldPos) let size = labelSize(forMarker: marker) while anchor != nil { let aabb = placeLabel(width: size.w, height: size.h, at: origin, anchor: anchor!, distance: labelDistance) let paddedAabb = padAabb(aabb, margin: labelMargin) let closeLabels = layout.query(search: paddedAabb) let canPlaceLabel = closeLabels.allSatisfy { boxIntersects($0.aabb, paddedAabb) == false } if canPlaceLabel { return (labelBox: aabb, layoutBox: paddedAabb, anchor!) } else { anchor = anchor?.next } } return nil } func labelSize(forMarker marker: LabelMarker) -> (w: Float, h: Float) { if let cachedSize = labelSizeCache[marker.ownerHash] { return cachedSize } else { let m = measure(marker) labelSizeCache[marker.ownerHash] = m return m } } } fileprivate func placeLabel(width: Float, height: Float, at screenPos: CGPoint, anchor: LayoutAnchor, distance d: Float) -> Aabb { let markerPos = Vertex(Float(screenPos.x), Float(screenPos.y)) let lowerLeft: Vertex switch anchor { case .NE: lowerLeft = markerPos + Vertex(+d, -d) + Vertex(0.0, -height) case .SE: lowerLeft = markerPos + Vertex(+d, +d) + Vertex(0.0, 0.0) case .NW: lowerLeft = markerPos + Vertex(-d, -d) + Vertex(-width, -height) case .SW: lowerLeft = markerPos + Vertex(-d, +d) + Vertex(-width, 0.0) case .Center: lowerLeft = markerPos + Vertex(-width / 2.0, -height / 2.0) } return Aabb(loX: floor(lowerLeft.x), loY: floor(lowerLeft.y), hiX: ceil(lowerLeft.x + width), hiY: ceil(lowerLeft.y + height)) } fileprivate func padAabb(_ aabb: Aabb, margin: Float) -> Aabb { return Aabb(loX: aabb.minX - margin, loY: aabb.minY - margin, hiX: aabb.maxX + margin, hiY: aabb.maxY + margin) }
mit
6805e5285c3195ba3441087a3c9cbe03
32.770408
205
0.69648
3.361605
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieGraphics/Font/Decoder/SFNTFontFace/SFNTNAME.swift
1
7402
// // SFNTNAME.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // struct SFNTNAME: ByteDecodable, RandomAccessCollection { public typealias Indices = Range<Int> public typealias Index = Int var format: BEUInt16 var record: [Record] var data: Data struct Record { var platform: SFNTPlatform var language: BEUInt16 var name: BEUInt16 var length: BEUInt16 var offset: BEUInt16 } init(from data: inout Data) throws { let copy = data self.format = try data.decode(BEUInt16.self) let _count = try data.decode(BEUInt16.self) let _stringOffset = try data.decode(BEUInt16.self) self.data = copy.dropFirst(Int(_stringOffset)) self.record = [] self.record.reserveCapacity(Int(_count)) for _ in 0..<Int(_count) { let platform = try data.decode(SFNTPlatform.self) let language = try data.decode(BEUInt16.self) let name = try data.decode(BEUInt16.self) let length = try data.decode(BEUInt16.self) let offset = try data.decode(BEUInt16.self) self.record.append(Record(platform: platform, language: language, name: name, length: length, offset: offset)) } } var startIndex: Int { return 0 } var endIndex: Int { return record.count } subscript(position: Int) -> String? { assert(0..<count ~= position, "Index out of range.") guard let encoding = self.record[position].platform.encoding else { return nil } let offset = Int(self.record[position].offset) let length = Int(self.record[position].length) let strData: Data = self.data.dropFirst(offset).prefix(length) guard strData.count == length else { return nil } return String(data: strData, encoding: encoding) } } extension SFNTNAME.Record { var iso_language: String? { switch platform.platform { case 1: switch language { case 0: return "en" case 1: return "fr" case 2: return "de" case 3: return "it" case 4: return "nl" case 5: return "sv" case 6: return "es" case 7: return "da" case 8: return "pt" case 9: return "nb" case 10: return "he" case 11: return "ja" case 12: return "ar" case 13: return "fi" case 14: return "el" case 15: return "is" case 16: return "mt" case 17: return "tr" case 18: return "hr" case 19: return "zh-Hant" case 20: return "ur" case 21: return "hi" case 22: return "th" case 23: return "ko" case 24: return "lt" case 25: return "pl" case 26: return "hu" case 27: return "et" case 28: return "lv" case 29: return "se" case 30: return "fo" case 31: return "fa" case 32: return "ru" case 33: return "zh-Hans" case 34: return "nl-BE" case 35: return "ga" case 36: return "sq" case 37: return "ro" case 38: return "cs" case 39: return "sk" case 40: return "sl" case 41: return "yi" case 42: return "sr" case 43: return "mk" case 44: return "bg" case 45: return "uk" case 46: return "be" case 47: return "uz" case 48: return "kk" case 49: return "az-Cyrl" case 50: return "az" case 51: return "hy" case 52: return "ka" case 53: return "mo" case 54: return "ky" case 55: return "tg" case 56: return "tk" case 57: return "mn" case 58: return "mn-Cyrl" case 59: return "ps" case 60: return "ku" case 61: return "ks" case 62: return "sd" case 63: return "bo" case 64: return "ne" case 65: return "sa" case 66: return "mr" case 67: return "bn" case 68: return "as" case 69: return "gu" case 70: return "pa" case 71: return "or" case 72: return "ml" case 73: return "kn" case 74: return "ta" case 75: return "te" case 76: return "si" case 77: return "my" case 78: return "km" case 79: return "lo" case 80: return "vi" case 81: return "id" case 82: return "fil" case 83: return "ms" case 84: return "ms-Arab" case 85: return "am" case 86: return "ti" case 88: return "so" case 89: return "sw" case 90: return "rw" case 91: return "rn" case 92: return "ny" case 93: return "mg" case 94: return "eo" case 128: return "cy" case 129: return "eu" case 130: return "ca" case 131: return "la" case 132: return "qu" case 133: return "gn" case 134: return "ay" case 135: return "tt" case 136: return "ug" case 137: return "dz" case 138: return "jv" case 139: return "su" case 140: return "gl" case 141: return "af" case 142: return "br" case 143: return "iu" case 144: return "gd" case 145: return "gv" case 146: return "ga" case 147: return "to" case 148: return "el" case 149: return "kl" case 150: return "az" default: return nil } case 3: return Locale.identifier(fromWindowsLocaleCode: Int(language)) default: return nil } } }
mit
8a693aed9833b6931daf5ba5f7f2e34f
31.897778
122
0.522697
4.249139
false
false
false
false
AboutObjectsTraining/swift-comp-reston-2017-02
examples/SwiftPerson/SwiftPerson/Person.swift
1
1435
// // person.swift // swiftexercise // // Created by Gregory Reimer on 7/14/15. // Copyright (c) 2015 Gregory Reimer. All rights reserved. // import Foundation let SpaceSeperator = " " let CommaSeperator = ", " public enum Gender { case male case female } public struct Person: Nameable { public var firstName: String public var lastName: String public var age: Int public var gender: Gender public var middleName: String? public var fullName: String { let components = nameComponents.filter { !$0.isEmpty } return components.joined(separator: SpaceSeperator) } public var nameComponents: [String] { return [firstName, middleName ?? "", lastName] } public var collationName: String { let firstAndMiddleNames = [firstName, middleName ?? "" ] let filteredFirstAndMiddleNames = firstAndMiddleNames.filter { !$0.isEmpty } let firstAndMiddleName = filteredFirstAndMiddleNames.joined(separator: SpaceSeperator) return [lastName, firstAndMiddleName].joined(separator: CommaSeperator) } public init(firstName: String, middleName: String? = .none, lastName: String, age: Int = 0, gender: Gender = .female) { self.firstName = firstName self.middleName = middleName self.age = age self.gender = gender self.lastName = lastName } }
mit
c8a723b50819fe66bc43f00e73aac35c
25.090909
94
0.649477
4.388379
false
false
false
false
grahamgilbert/Crypt
Crypt/Mechanisms/Enablement.swift
2
2723
/* Crypt Copyright 2016 The Crypt Project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import Security import CoreFoundation import os.log class Enablement: CryptMechanism { fileprivate let bundleid = "com.grahamgilbert.crypt" private static let log = OSLog(subsystem: "com.grahamgilbert.crypt", category: "Enablement") // This is the only public function. It will be called from the // ObjC AuthorizationPlugin class @objc func run() { if self.needsEncryption { os_log("Attempting to enable FileVault", log: Enablement.log, type: .default) guard let username = self.username else { allowLogin(); return } guard let password = self.password else { allowLogin(); return } if getFVEnabled().encrypted && needToRestart() { // This is a catch for if we are on 10.13+ but on HFS. os_log("FileVault is enabled already and `fdesetup status` requests a restart", log: Enablement.log, type: .default) _ = restartMac() } let the_settings = NSDictionary.init(dictionary: ["Username" : username, "Password" : password]) let filepath = CFPreferencesCopyAppValue(Preferences.outputPath as CFString, bundleid as CFString) as? String ?? "/private/var/root/crypt_output.plist" do { _ = try enableFileVault(the_settings, filepath: filepath) _ = restartMac() } catch let error as NSError { os_log("Failed to Enable FileVault %{public}@", log: Enablement.log, type: .error, error.localizedDescription) _ = allowLogin() } } else { // Allow to login. End of mechanism os_log("Hint Value not set Allowing Login...", log: Enablement.log, type: .default) _ = allowLogin() } } // Restart fileprivate func restartMac() -> Bool { // Wait a couple of seconds for everything to finish os_log("called restartMac()...", log: Enablement.log, type: .default) sleep(3) let task = Process(); os_log("Restarting Mac after enabling FileVault...", log: Enablement.log, type: .default) task.launchPath = "/sbin/shutdown" task.arguments = ["-r", "now"] task.launch() return true } }
apache-2.0
9452efd462fd3075c309cbfbfc87a1a4
34.363636
157
0.672787
4.17638
false
false
false
false
spritekitbook/flappybird-swift
Chapter 9/Start/FloppyBird/FloppyBird/Settings.swift
7
1033
// // Settings.swift // FloppyBird // // Created by Jeremy Novak on 9/27/16. // Copyright © 2016 SpriteKit Book. All rights reserved. // import Foundation class Settings { static let sharedInstance = Settings() // MARK: - Private class constants private let defaults = UserDefaults.standard private let keyFirstRun = "First Run" private let keyBestScore = "Best Score" // MARK: - Init init() { if defaults.object(forKey: keyFirstRun) == nil { firstLaunch() } } private func firstLaunch() { defaults.set(0, forKey: keyBestScore) defaults.set(false, forKey: keyFirstRun) defaults.synchronize() } // MARK: - Public saving methods func saveBest(score: Int) { defaults.set(score, forKey: keyBestScore) defaults.synchronize() } // MARK: - Public retrieving methods func getBestScore() -> Int { return defaults.integer(forKey: keyBestScore) } }
apache-2.0
acff42b37a8dee5326815a31815289ee
21.933333
57
0.600775
4.336134
false
false
false
false
Friend-LGA/LGSideMenuController
Demo/_shared_files/SideMenuController/RootViewController/RootTabBarController.swift
1
4504
// // RootTabBarController.swift // LGSideMenuControllerDemo // import Foundation import UIKit class RootTabBarController: UITabBarController { private var type: DemoType? init(type: DemoType) { super.init(nibName: nil, bundle: nil) setup(type: type) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // For Storyboard Demo func setup(type: DemoType) { self.type = type } // MARK: - Lifecycle - override func viewDidLoad() { super.viewDidLoad() struct Counter { static var count = 0 } Counter.count += 1 print("RootNavigationController.viewDidLoad(), counter: \(Counter.count)") // UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: tabBar.bounds.height)], for: .normal) // UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: tabBar.bounds.height)], for: .selected) setColors() } // override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { // super.willTransition(to: newCollection, with: coordinator) // // UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: tabBar.bounds.height)], for: .normal) // UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: tabBar.bounds.height)], for: .selected) // } // // override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { // super.viewWillTransition(to: size, with: coordinator) // // UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: tabBar.bounds.height)], for: .normal) // UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: tabBar.bounds.height)], for: .selected) // } // MARK: - Rotation - override var shouldAutorotate : Bool { return true } // MARK: - Status Bar - override var prefersStatusBarHidden : Bool { return false } override var preferredStatusBarStyle : UIStatusBarStyle { return .default } override var preferredStatusBarUpdateAnimation : UIStatusBarAnimation { return .fade } // MARK: - Theme - override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) setColors() } // MARK: - Other - func setColors() { // navigationBar.barTintColor = UIColor(white: (isLightTheme() ? 1.0 : 0.0), alpha: 0.9) // navigationBar.titleTextAttributes = [.foregroundColor: (isLightTheme() ? UIColor.black : UIColor.white)] } // MARK: - Logging - deinit { struct Counter { static var count = 0 } Counter.count += 1 print("RootNavigationController.deinit(), counter: \(Counter.count)") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) struct Counter { static var count = 0 } Counter.count += 1 print("RootNavigationController.viewWillAppear(\(animated)), counter: \(Counter.count)") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) struct Counter { static var count = 0 } Counter.count += 1 print("RootNavigationController.viewDidAppear(\(animated)), counter: \(Counter.count)") } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) struct Counter { static var count = 0 } Counter.count += 1 print("RootNavigationController.viewWillDisappear(\(animated)), counter: \(Counter.count)") } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) struct Counter { static var count = 0 } Counter.count += 1 print("RootNavigationController.viewDidDisappear(\(animated)), counter: \(Counter.count)") } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() struct Counter { static var count = 0 } Counter.count += 1 print("RootNavigationController.viewWillLayoutSubviews(), counter: \(Counter.count)") } }
mit
fbda440ba413107e3f7eb6e3f225dece
33.121212
154
0.674067
4.971302
false
false
false
false
nathawes/swift
test/SourceKit/CodeComplete/complete_moduleimportdepth.swift
21
4458
import ImportsImportsFoo import FooHelper.FooHelperExplicit func test() { let x = 1 #^A^# } // REQUIRES: objc_interop // RUN: %complete-test -hide-none -group=none -tok=A %s -raw -- -I %S/Inputs -F %S/../Inputs/libIDE-mock-sdk > %t // RUN: %FileCheck %s < %t // Swift == 1 // CHECK-LABEL: key.name: "abs(:)", // CHECK-NEXT: key.sourcetext: "abs(<#T##x: Comparable & SignedNumeric##Comparable & SignedNumeric#>)", // CHECK-NEXT: key.description: "abs(x: Comparable & SignedNumeric)", // CHECK-NEXT: key.typename: "Comparable & SignedNumeric", // CHECK-NEXT: key.doc.brief: "Returns the absolute value of the given number.", // CHECK-NEXT: key.context: source.codecompletion.context.othermodule, // CHECK-NEXT: key.moduleimportdepth: 1, // CHECK-NEXT: key.num_bytes_to_erase: 0, // CHECK-NOT: key.modulename // CHECK: key.modulename: "Swift" // CHECK-NEXT: }, // FooHelper.FooHelperExplicit == 1 // CHECK-LABEL: key.name: "fooHelperExplicitFrameworkFunc1(:)", // CHECK-NEXT: key.sourcetext: "fooHelperExplicitFrameworkFunc1(<#T##a: Int32##Int32#>)", // CHECK-NEXT: key.description: "fooHelperExplicitFrameworkFunc1(a: Int32)", // CHECK-NEXT: key.typename: "Int32", // CHECK-NEXT: key.context: source.codecompletion.context.othermodule, // CHECK-NEXT: key.moduleimportdepth: 1, // CHECK-NEXT: key.num_bytes_to_erase: 0, // CHECK-NOT: key.modulename // CHECK: key.modulename: "FooHelper.FooHelperExplicit" // CHECK-NEXT: }, // ImportsImportsFoo == 1 // CHECK-LABEL: key.name: "importsImportsFoo()", // CHECK-NEXT: key.sourcetext: "importsImportsFoo()", // CHECK-NEXT: key.description: "importsImportsFoo()", // CHECK-NEXT: key.typename: "Void", // CHECK-NEXT: key.context: source.codecompletion.context.othermodule, // CHECK-NEXT: key.moduleimportdepth: 1, // CHECK-NEXT: key.num_bytes_to_erase: 0, // CHECK-NOT: key.modulename // CHECK: key.modulename: "ImportsImportsFoo" // CHECK-NEXT: }, // Bar == 2 // CHECK-LABEL: key.name: "BarForwardDeclaredClass", // CHECK-NEXT: key.sourcetext: "BarForwardDeclaredClass", // CHECK-NEXT: key.description: "BarForwardDeclaredClass", // CHECK-NEXT: key.typename: "BarForwardDeclaredClass", // CHECK-NEXT: key.context: source.codecompletion.context.othermodule, // CHECK-NEXT: key.moduleimportdepth: 2, // CHECK-NEXT: key.num_bytes_to_erase: 0, // CHECK-NOT: key.modulename // CHECK: key.modulename: "Bar" // CHECK-NEXT: }, // ImportsFoo == 2 // CHECK-LABEL: key.name: "importsFoo()", // CHECK-NEXT: key.sourcetext: "importsFoo()", // CHECK-NEXT: key.description: "importsFoo()", // CHECK-NEXT: key.typename: "Void", // CHECK-NEXT: key.context: source.codecompletion.context.othermodule, // CHECK-NEXT: key.moduleimportdepth: 2, // CHECK-NEXT: key.num_bytes_to_erase: 0, // CHECK-NOT: key.modulename // CHECK: key.modulename: "ImportsFoo" // CHECK-NEXT: }, // Foo == FooSub == 3 // CHECK-LABEL: key.name: "FooClassBase", // CHECK-NEXT: key.sourcetext: "FooClassBase", // CHECK-NEXT: key.description: "FooClassBase", // CHECK-NEXT: key.typename: "FooClassBase", // CHECK-NEXT: key.context: source.codecompletion.context.othermodule, // CHECK-NEXT: key.moduleimportdepth: 3, // CHECK-NEXT: key.num_bytes_to_erase: 0, // CHECK-NOT: key.modulename // CHECK: key.modulename: "Foo" // CHECK-NEXT: }, // CHECK-LABEL: key.name: "FooSubEnum1", // CHECK-NEXT: key.sourcetext: "FooSubEnum1", // CHECK-NEXT: key.description: "FooSubEnum1", // CHECK-NEXT: key.typename: "FooSubEnum1", // CHECK-NEXT: key.context: source.codecompletion.context.othermodule, // CHECK-NEXT: key.moduleimportdepth: 3, // CHECK-NEXT: key.num_bytes_to_erase: 0, // CHECK-NOT: key.modulename // CHECK: key.modulename: "Foo.FooSub" // CHECK-NEXT: }, // FooHelper == 4 // FIXME: rdar://problem/20230030 // We're picking up the implicit import of FooHelper used to attach FooHelperExplicit to. // xCHECK-LABEL: key.name: "FooHelperUnnamedEnumeratorA2", // xCHECK-NEXT: key.sourcetext: "FooHelperUnnamedEnumeratorA2", // xCHECK-NEXT: key.description: "FooHelperUnnamedEnumeratorA2", // xCHECK-NEXT: key.typename: "Int", // xCHECK-NEXT: key.context: source.codecompletion.context.othermodule, // xCHECK-NEXT: key.moduleimportdepth: 4, // xCHECK-NEXT: key.num_bytes_to_erase: 0, // xCHECK-NOT: key.modulename // xCHECK: key.modulename: "FooHelper" // xCHECK-NEXT: },
apache-2.0
6e60d3552e7c8d0e2764b3773f27be26
40.277778
113
0.683042
3.152758
false
false
false
false
nathawes/swift
test/IRGen/symbolic_references.swift
22
997
// RUN: %target-swift-frontend -emit-ir %s | %FileCheck %s // RUN: %target-swift-frontend -emit-ir -enable-private-imports %s | %FileCheck %s --check-prefix=PRIVATE protocol P { associatedtype A } // CHECK-DAG: @"symbolic _____ 19symbolic_references3Foo016_{{.*}}V5InnerV9InnermostV" = linkonce_odr hidden constant <{ i8, i32, i8 }> <{ i8 1, // CHECK-DAG: @"symbolic _____ 19symbolic_references3Foo016_{{.*}}V5InnerV" = linkonce_odr hidden constant <{ i8, i32, i8 }> <{ i8 1 // CHECK-DAG: @"symbolic _____ 19symbolic_references3Foo016_{{.*}}V" = linkonce_odr hidden constant <{ i8, i32, i8 }> <{ i8 1 // PRIVATE-DAG: @"symbolic _____ 19symbolic_references3Foo016_{{.*}}V5InnerV" = linkonce_odr hidden constant <{ i8, i32, i8 }> <{ i8 1 // PRIVATE-DAG: @"symbolic _____ 19symbolic_references3Foo016_{{.*}}V" = linkonce_odr hidden constant <{ i8, i32, i8 }> <{ i8 1 fileprivate struct Foo { fileprivate struct Inner: P { fileprivate struct Innermost { } typealias A = Innermost } }
apache-2.0
64c7e1b94c305d2b7cb755e3e36eba19
51.473684
144
0.660983
3.345638
false
false
false
false
practicalswift/swift
test/Interpreter/protocol_initializers_class.swift
16
10985
// RUN: %empty-directory(%t) // RUN: %target-build-swift -swift-version 5 %s -o %t/a.out // RUN: %target-codesign %t/a.out // // RUN: %target-run %t/a.out // REQUIRES: executable_test import StdlibUnittest var ProtocolInitTestSuite = TestSuite("ProtocolInitClass") func mustThrow<T>(_ f: () throws -> T) { do { _ = try f() preconditionFailure("Didn't throw") } catch {} } func mustFail<T>(f: () -> T?) { if f() != nil { preconditionFailure("Didn't fail") } } enum E : Error { case X } // This is the same as the protocol_initializers.swift test, // but class-bound protocol TriviallyConstructible : class { init(x: LifetimeTracked) init(x: LifetimeTracked, throwsDuring: Bool) throws init?(x: LifetimeTracked, failsDuring: Bool) } extension TriviallyConstructible { init(x: LifetimeTracked, throwsBefore: Bool) throws { if throwsBefore { throw E.X } self.init(x: x) } init(x: LifetimeTracked, throwsAfter: Bool) throws { self.init(x: x) if throwsAfter { throw E.X } } init(x: LifetimeTracked, throwsBefore: Bool, throwsDuring: Bool) throws { if throwsBefore { throw E.X } try self.init(x: x, throwsDuring: throwsDuring) } init(x: LifetimeTracked, throwsBefore: Bool, throwsAfter: Bool) throws { if throwsBefore { throw E.X } self.init(x: x) if throwsAfter { throw E.X } } init(x: LifetimeTracked, throwsDuring: Bool, throwsAfter: Bool) throws { try self.init(x: x, throwsDuring: throwsDuring) if throwsAfter { throw E.X } } init(x: LifetimeTracked, throwsBefore: Bool, throwsDuring: Bool, throwsAfter: Bool) throws { if throwsBefore { throw E.X } try self.init(x: x, throwsDuring: throwsDuring) if throwsAfter { throw E.X } } init?(x: LifetimeTracked, failsBefore: Bool) { if failsBefore { return nil } self.init(x: x) } init?(x: LifetimeTracked, failsAfter: Bool) { self.init(x: x) if failsAfter { return nil } } init?(x: LifetimeTracked, failsBefore: Bool, failsDuring: Bool) { if failsBefore { return nil } self.init(x: x, failsDuring: failsDuring) } init?(x: LifetimeTracked, failsBefore: Bool, failsAfter: Bool) { if failsBefore { return nil } self.init(x: x) if failsAfter { return nil } } init?(x: LifetimeTracked, failsDuring: Bool, failsAfter: Bool) { self.init(x: x, failsDuring: failsDuring) if failsAfter { return nil } } init?(x: LifetimeTracked, failsBefore: Bool, failsDuring: Bool, failsAfter: Bool) { if failsBefore { return nil } self.init(x: x, failsDuring: failsDuring) if failsAfter { return nil } } } class TrivialClass : TriviallyConstructible { let tracker: LifetimeTracked // Protocol requirements required init(x: LifetimeTracked) { self.tracker = x } required convenience init(x: LifetimeTracked, throwsDuring: Bool) throws { self.init(x: x) if throwsDuring { throw E.X } } required convenience init?(x: LifetimeTracked, failsDuring: Bool) { self.init(x: x) if failsDuring { return nil } } // Class initializers delegating to protocol initializers convenience init(throwsBefore: Bool) throws { if throwsBefore { throw E.X } self.init(x: LifetimeTracked(0)) } convenience init(throwsAfter: Bool) throws { self.init(x: LifetimeTracked(0)) if throwsAfter { throw E.X } } convenience init(throwsBefore: Bool, throwsDuring: Bool) throws { if throwsBefore { throw E.X } try self.init(x: LifetimeTracked(0), throwsDuring: throwsDuring) } convenience init(throwsBefore: Bool, throwsAfter: Bool) throws { if throwsBefore { throw E.X } self.init(x: LifetimeTracked(0)) if throwsAfter { throw E.X } } convenience init(throwsDuring: Bool, throwsAfter: Bool) throws { try self.init(x: LifetimeTracked(0), throwsDuring: throwsDuring) if throwsAfter { throw E.X } } convenience init(throwsBefore: Bool, throwsDuring: Bool, throwsAfter: Bool) throws { if throwsBefore { throw E.X } try self.init(x: LifetimeTracked(0), throwsDuring: throwsDuring) if throwsAfter { throw E.X } } convenience init?(failsBefore: Bool) { if failsBefore { return nil } self.init(x: LifetimeTracked(0)) } convenience init?(failsAfter: Bool) { self.init(x: LifetimeTracked(0)) if failsAfter { return nil } } convenience init?(failsBefore: Bool, failsDuring: Bool) { if failsBefore { return nil } self.init(x: LifetimeTracked(0), failsDuring: failsDuring) } convenience init?(failsBefore: Bool, failsAfter: Bool) { if failsBefore { return nil } self.init(x: LifetimeTracked(0)) if failsAfter { return nil } } convenience init?(failsDuring: Bool, failsAfter: Bool) { self.init(x: LifetimeTracked(0), failsDuring: failsDuring) if failsAfter { return nil } } convenience init?(failsBefore: Bool, failsDuring: Bool, failsAfter: Bool) { if failsBefore { return nil } self.init(x: LifetimeTracked(0), failsDuring: failsDuring) if failsAfter { return nil } } } ProtocolInitTestSuite.test("ExtensionInit_Success") { _ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false) _ = try! TrivialClass(x: LifetimeTracked(0), throwsAfter: false) _ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: false) _ = try! TrivialClass(x: LifetimeTracked(0), throwsDuring: false, throwsAfter: false) _ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsAfter: false) _ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: false, throwsAfter: false) _ = TrivialClass(x: LifetimeTracked(0), failsBefore: false)! _ = TrivialClass(x: LifetimeTracked(0), failsAfter: false)! _ = TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: false)! _ = TrivialClass(x: LifetimeTracked(0), failsDuring: false, failsAfter: false)! _ = TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsAfter: false)! _ = TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: false, failsAfter: false)! } ProtocolInitTestSuite.test("ClassInit_Success") { _ = try! TrivialClass(throwsBefore: false) _ = try! TrivialClass(throwsAfter: false) _ = try! TrivialClass(throwsBefore: false, throwsDuring: false) _ = try! TrivialClass(throwsDuring: false, throwsAfter: false) _ = try! TrivialClass(throwsBefore: false, throwsAfter: false) _ = try! TrivialClass(throwsBefore: false, throwsDuring: false, throwsAfter: false) _ = TrivialClass(failsBefore: false)! _ = TrivialClass(failsAfter: false)! _ = TrivialClass(failsBefore: false, failsDuring: false)! _ = TrivialClass(failsDuring: false, failsAfter: false)! _ = TrivialClass(failsBefore: false, failsAfter: false)! _ = TrivialClass(failsBefore: false, failsDuring: false, failsAfter: false)! } ProtocolInitTestSuite.test("ExtensionInit_Failure") { mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsAfter: true) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true, throwsDuring: false) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: true) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsDuring: true, throwsAfter: false) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsDuring: false, throwsAfter: true) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true, throwsAfter: false) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsAfter: true) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true, throwsDuring: false, throwsAfter: false) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: true, throwsAfter: false) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: false, throwsAfter: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsAfter: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true, failsDuring: false) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsDuring: true, failsAfter: false) } mustFail { TrivialClass(x: LifetimeTracked(0), failsDuring: false, failsAfter: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true, failsAfter: false) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsAfter: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true, failsDuring: false, failsAfter: false) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: true, failsAfter: false) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: false, failsAfter: true) } } ProtocolInitTestSuite.test("ClassInit_Failure") { mustThrow { try TrivialClass(throwsBefore: true) } mustThrow { try TrivialClass(throwsAfter: true) } mustThrow { try TrivialClass(throwsBefore: true, throwsDuring: false) } mustThrow { try TrivialClass(throwsBefore: false, throwsDuring: true) } mustThrow { try TrivialClass(throwsDuring: true, throwsAfter: false) } mustThrow { try TrivialClass(throwsDuring: false, throwsAfter: true) } mustThrow { try TrivialClass(throwsBefore: true, throwsAfter: false) } mustThrow { try TrivialClass(throwsBefore: false, throwsAfter: true) } mustThrow { try TrivialClass(throwsBefore: true, throwsDuring: false, throwsAfter: false) } mustThrow { try TrivialClass(throwsBefore: false, throwsDuring: true, throwsAfter: false) } mustThrow { try TrivialClass(throwsBefore: false, throwsDuring: false, throwsAfter: true) } mustFail { TrivialClass(failsBefore: true) } mustFail { TrivialClass(failsAfter: true) } mustFail { TrivialClass(failsBefore: true, failsDuring: false) } mustFail { TrivialClass(failsBefore: false, failsDuring: true) } mustFail { TrivialClass(failsDuring: true, failsAfter: false) } mustFail { TrivialClass(failsDuring: false, failsAfter: true) } mustFail { TrivialClass(failsBefore: true, failsAfter: false) } mustFail { TrivialClass(failsBefore: false, failsAfter: true) } mustFail { TrivialClass(failsBefore: true, failsDuring: false, failsAfter: false) } mustFail { TrivialClass(failsBefore: false, failsDuring: true, failsAfter: false) } mustFail { TrivialClass(failsBefore: false, failsDuring: false, failsAfter: true) } } runAllTests()
apache-2.0
d3df9351278c10a56b20ec7158b41b79
31.596439
116
0.695221
4.208812
false
false
false
false
andriitishchenko/vkLibManage
vkLibManage/Player.swift
1
2934
// // Player.swift // vkLibManage // // Created by Andrii Tiischenko on 10/19/16. // Copyright © 2016 Andrii Tiischenko. All rights reserved. // import UIKit import MediaPlayer //@objc(Player) class Player: NSObject, PrivatPlayerDelegate { private var privatePlayer = PrivatPlayer() static let sharedInstance: Player = Player() //private override private override init() { super.init() self.privatePlayer.delegate = self } // deinit { // // } func addToQueue(_ item:TrackItem){ // self.jukebox.append(item: JukeboxItem (URL: URL(string: "http://www.noiseaddicts.com/samples_1w72b820/2228.mp3")!), loadingAssets: false) } func privatPlayerGetNextTrack() -> PrivatPlayerMediaItem? { if let item = DBManager.sharedInstance.getNextPlaylistItem() { var media = PrivatPlayerMediaItem() media.url = item.getFileURL() media.title = item.title media.artist = item.artist return media } return nil } func privatPlayerGetPrevTrack() -> PrivatPlayerMediaItem?{ if let item = DBManager.sharedInstance.getNextPlaylistItem() { var media = PrivatPlayerMediaItem() media.url = item.getFileURL() media.title = item.title media.artist = item.artist return media } return nil } func privatPlayerDidStartedTrack(){ } func privatPlayerDidFinishedTrack(){ } /// PLAYLIST CONTROL func play(){ self.privatePlayer.play() } func stop(){ //self.privatePlayer.stop() } func playNext(){ self.privatePlayer.requestNextAndPlay() } func playPrev(){ self.privatePlayer.requestPrevAndPlay() } // func getActivePlaylist() -> [TrackItem] { // return DBManager.sharedInstance.getActivePlaylist() // } //add tracks from Playlust to the Active playlist func addPlaylistToPlayQueue(_ item:PlaylistItem) { DBManager.sharedInstance.addPlaylistWithID(item.id) self.privatePlayer.play() } //add tracks to the Active playlist func addTracksToPlayQueue(_ list:[TrackItem]) { DBManager.sharedInstance.addPlaylistItems(list, finish: { self.privatePlayer.play() }) } //play tack separately of playlist. Active playlist will not be changed func PlayTrackStandalone(_ item:TrackItem) { var media = PrivatPlayerMediaItem() media.url = item.getFileURL() media.title = item.title media.artist = item.artist self.privatePlayer.play(media) } //will replace whole Active playlist func newPlaylistQueue(_ item:PlaylistItem) { DBManager.sharedInstance.replacePlaylistWithID(item.id) } }
mit
7ba1b673f7f32c71b88fc3e3592baabe
23.647059
147
0.613024
4.338757
false
false
false
false
ngthduy90/Yummy
Source/Models/Business.swift
1
1277
// // Business.swift // Yummy // // Created by Duy Nguyen on 6/25/17. // Copyright © 2017 Duy Nguyen. All rights reserved. // import Foundation import SwiftyJSON class Business { var name: String = "" var distance: Double = 0.0 var reviewCount: Int = 0 var imageURL: URL? var ratingImageURL: URL? var categories: String = "" var location: Location init(fromJSON json: JSON) { let addresses = json["location"]["display_address"].arrayValue.map { $0.stringValue } let coorJSON = json["location"]["coordinate"] let latValue = coorJSON["latitude"].doubleValue let longValue = coorJSON["longitude"].doubleValue self.location = Location(listAddess: addresses, coordinate: Coordinate(latitude: latValue, longitude: longValue)) self.name = json["name"].stringValue self.distance = json["distance"].doubleValue self.reviewCount = json["review_count"].intValue self.imageURL = json["image_url"].url self.ratingImageURL = json["rating_img_url_large"].url } var distanceInMiles: String { get { return String(format: "%.2f mi", Constants.MilesPerMeter * distance) } } }
apache-2.0
8b5a65df198ef683284ba5f1d0a1e884
26.73913
121
0.61442
4.296296
false
false
false
false
dsay/POPDataSource
DataSources/Example/Models/Models.swift
1
3868
import UIKit struct Artist { var name: String var id: Int var albums = [Album]() init(_ name: String, _ id: Int) { self.name = name self.id = id } } struct Genre { var name: String var albums = [Album]() init(_ genre: String) { self.name = genre } } struct Album { var name: String var releaseDate: Date var trackCount: Int var genre: String var artistName: String init(_ name: String, _ artistName: String, _ releaseDate: Date, _ trackCount: Int, _ genre: String) { self.name = name self.artistName = artistName self.releaseDate = releaseDate self.trackCount = trackCount self.genre = genre } } struct Parser { var fileURL: URL func parse() -> ([Album], [Artist])? { let data = try? Data(contentsOf: fileURL) var json: [[String : AnyObject]]? = nil do { json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [[String : AnyObject]] } catch { json = nil } guard let parsed = json else { return nil } var albums = [Album]() var artists = [Artist]() let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" for representation in parsed { let artist = Artist(representation["artistName"] as! String, representation["artistId"] as! Int) artists.append(artist) let date = representation["releaseDate"] as! String let album = Album(representation["collectionName"] as! String, representation["artistName"] as! String, dateFormatter.date(from: date)!, representation["trackCount"] as! Int, representation["primaryGenreName"] as! String) albums.append(album) } return (albums, Array(Set(artists))) } } struct LedZeppelin { fileprivate static let parser: Parser = { let path = Bundle.main.url(forResource: "Albums", withExtension: "json") return Parser(fileURL: path!) }() fileprivate static let data = LedZeppelin.parser.parse() static let genres: [Genre] = { let genreNames = Set(LedZeppelin.data!.0.map { $0.genre }) return genreNames.map { name -> Genre in var genre = Genre(name) genre.albums = LedZeppelin.data!.0.filter { $0.genre == name } return genre } }() static var artists: [Artist] { var artists = [Artist]() for artist in LedZeppelin.data!.1 { var artistWithAlbums = artist artistWithAlbums.albums = LedZeppelin.data!.0.filter { $0.artistName == artist.name } artists.append(artistWithAlbums) } return artists } static let albums: [Album] = { return LedZeppelin.data!.0 }() } func ==(lhs: Album, rhs: Album) -> Bool { return (lhs.name == rhs.name) && (lhs.trackCount == rhs.trackCount) && (lhs.genre == rhs.genre) && (lhs.artistName == rhs.artistName) && (lhs.releaseDate == rhs.releaseDate) } extension Album: Hashable { var hashValue: Int { return self.artistName.hashValue ^ self.genre.hashValue ^ self.name.hashValue ^ self.releaseDate.hashValue ^ self.trackCount.hashValue } } func ==(lhs: Artist, rhs: Artist) -> Bool { return (lhs.name == rhs.name) && (lhs.id == rhs.id) && (lhs.albums == rhs.albums) } extension Artist: Hashable { var hashValue: Int { return self.name.hashValue ^ self.id.hashValue ^ self.albums.count.hashValue } }
mit
c8118dff30aaef889432e8d098781bb3
28.082707
142
0.558428
4.302558
false
false
false
false
michikono/swift-using-typealiases-as-generics
swift-using-typealiases-as-generics-i.playground/Pages/typealias-for-self 2.xcplaygroundpage/Contents.swift
2
1258
//: Typealias for Self - limitations with structs //: ============================================= //: [Previous](@previous) protocol Material {} struct Wood: Material {} struct Glass: Material {} struct Metal: Material {} struct Cotton: Material {} //: Alternate method for creating a factory -- we changed `factory()` to return `Self` instead of `T` protocol Furniture { typealias M: Material typealias M2: Material func mainMaterial() -> M func secondaryMaterial() -> M2 static func factory() -> Self // <===== } //: still works struct Chair: Furniture { func mainMaterial() -> Wood { return Wood() } func secondaryMaterial() -> Cotton { return Cotton() } static func factory() -> Chair { return Chair() } } //: **This next code snippet will not compile -- which is good!** //: Notice here that `Chair` can not be the return type for `factory()`. Change `Chair` => `Lamp` to fix this error struct Lamp: Furniture { func mainMaterial() -> Glass { return Glass() } func secondaryMaterial() -> Metal { return Metal() } static func factory() -> Chair { return Chair() // <== this is not what we intended! } } //: [Next](@next)
mit
53f5373c34a1cbaf69bfa58d19461b01
22.735849
115
0.588235
4.084416
false
false
false
false
IBM-Swift/Kitura
Sources/Kitura/staticFileServer/CacheRelatedHeadersSetter.swift
1
3366
/* * Copyright IBM Corporation 2016 * * 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 KituraNet import Foundation extension StaticFileServer { class CacheRelatedHeadersSetter: ResponseHeadersSetter { /// Uses the file system's last modified value. private let addLastModifiedHeader: Bool /// Value of max-age in Cache-Control header. private let maxAgeCacheControlHeader: Int /// Generate ETag. private var generateETag: Bool init(addLastModifiedHeader: Bool, maxAgeCacheControlHeader: Int, generateETag: Bool) { self.addLastModifiedHeader = addLastModifiedHeader self.maxAgeCacheControlHeader = maxAgeCacheControlHeader self.generateETag = generateETag } func setCustomResponseHeaders(response: RouterResponse, filePath _: String, fileAttributes: [FileAttributeKey : Any]) { addLastModified(response: response, fileAttributes: fileAttributes) addETag(response: response, fileAttributes: fileAttributes) setMaxAge(response: response) } private func addLastModified(response: RouterResponse, fileAttributes: [FileAttributeKey : Any]) { if addLastModifiedHeader { let date = fileAttributes[FileAttributeKey.modificationDate] as? Date if let date = date { response.headers["Last-Modified"] = SPIUtils.httpDate(date) } } } private func addETag(response: RouterResponse, fileAttributes: [FileAttributeKey : Any]) { if generateETag, let etag = CacheRelatedHeadersSetter.calculateETag(from: fileAttributes) { response.headers["Etag"] = etag } } private func setMaxAge(response: RouterResponse) { response.headers["Cache-Control"] = "max-age=\(maxAgeCacheControlHeader)" } static func calculateETag(from fileAttributes: [FileAttributeKey : Any]) -> String? { guard let date = fileAttributes[FileAttributeKey.modificationDate] as? Date, let size = fileAttributes[FileAttributeKey.size] as? NSNumber else { return nil } #if !os(Linux) || swift(>=4.0.2) // https://bugs.swift.org/browse/SR-5850 let sizeHex = String(Int(truncating: size), radix: 16, uppercase: false) #else let sizeHex = String(Int(size), radix: 16, uppercase: false) #endif let timeHex = String(Int(date.timeIntervalSince1970), radix: 16, uppercase: false) let etag = "W/\"\(sizeHex)-\(timeHex)\"" return etag } } }
apache-2.0
69857cc52563e58fcde919c74228adca
38.6
94
0.622995
5.076923
false
false
false
false
kallahir/AlbumTrackr-iOS
AlbumTracker/SearchViewController.swift
1
2529
// // SearchViewController.swift // AlbumTracker // // Created by Itallo Rossi Lucas on 5/5/16. // Copyright © 2016 AlbumTrackr. All rights reserved. // import UIKit class SearchViewController: UITableViewController, UISearchBarDelegate { @IBOutlet weak var searchBar: UISearchBar! var artists:[Artist] = [] var filteredArtists = [Artist]() override func viewDidLoad() { super.viewDidLoad() self.searchBar.delegate = self self.searchBar.placeholder = NSLocalizedString("Search.search_artist", comment: "Search Artist") self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() self.loadData() } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("SearchCell")! as UITableViewCell // if(filteredArtists.count > 0){ // cell.textLabel?.text = filteredArtists[indexPath.row].artistName // } return cell } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filteredArtists.count } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { self.filteredArtists = artists.filter({ artist in return (artist.name?.lowercaseString.containsString(searchText.lowercaseString))! }) self.tableView.reloadData() } func loadData(){ // self.artists.append(Artist(artistName: "David Bowie", artistStyle: "Rock", artistNewestAlbum: "Starman", artistImage: "david_bowie")) // self.artists.append(Artist(artistName: "Green Day", artistStyle: "Punk Rock", artistNewestAlbum: "American Idiot", artistImage: "green_day")) // self.artists.append(Artist(artistName: "Nirvana", artistStyle: "Grungie", artistNewestAlbum: "Nevermind", artistImage: "nirvana")) // self.artists.append(Artist(artistName: "Pink Floyd", artistStyle: "Progressive Rock", artistNewestAlbum: "Dark Side of The Moon", artistImage: "pink_floyd")) // self.artists.append(Artist(artistName: "Rolling Stones", artistStyle: "Rock 'n Roll", artistNewestAlbum: "Satisfaction", artistImage: "rolling_stones")) } }
agpl-3.0
33aa5ee9e29a5baa2150819ab4e7a291
41.133333
167
0.686709
4.664207
false
false
false
false
qiuncheng/posted-articles-in-blog
Demos/rx_laptimer/rx_laptimer/ViewController.swift
1
2237
// // ViewController.swift // rx_laptimer // // Created by Marin Todorov on 2/15/16. // Copyright © 2016 Underplot ltd. All rights reserved. // import UIKit import RxSwift import RxCocoa class ViewController: UIViewController { @IBOutlet weak var lblChrono: UILabel! @IBOutlet weak var btnLap: UIButton! @IBOutlet weak var tableView: UITableView! let tableHeaderView = UILabel() let bag = DisposeBag() var timer: Observable<Int>! override func viewDidLoad() { super.viewDidLoad() tableHeaderView.backgroundColor = UIColor(white: 0.85, alpha: 1.0) //create the timer timer = Observable<Int>.interval(0.1, scheduler: MainScheduler.instance) timer .subscribe(onNext: { msecs -> Void in print("\(msecs)00ms") }) .addDisposableTo(bag) //wire the chrono timer.map(stringFromTimeInterval) .bindTo(lblChrono.rx.text) .addDisposableTo(bag) let lapsSequence = timer.sample(btnLap.rx.tap) .map(stringFromTimeInterval) .scan([String](), accumulator: {lapTimes, newTime in return lapTimes + [newTime] }) .shareReplay(1) lapsSequence .bindTo(tableView.rx.items(cellIdentifier: "Cell", cellType: UITableViewCell.self)) { (row, element, cell) in cell.textLabel?.text = "\(row + 1)) \(element)" } .disposed(by: bag) //set table delegate tableView .rx.setDelegate(self) .addDisposableTo(bag) //update the table header lapsSequence.map({ laps -> String in return "\t\(laps.count) laps" }) .startWith("\tno laps") .bindTo(tableHeaderView.rx.text) .addDisposableTo(bag) } } extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return tableHeaderView } } func stringFromTimeInterval(ms: NSInteger) -> String { return String(format: "%0.2d:%0.2d.%0.1d", arguments: [(ms / 600) % 600, (ms % 600 ) / 10, ms % 10]) }
apache-2.0
6be0fa9a08bccbfedbb10c0855e49b11
27.303797
117
0.592576
4.384314
false
false
false
false
cpuu/OTT
OTT/Beacon/BeaconsViewController.swift
1
3334
// // BeaconsViewController.swift // BlueCap // // Created by Troy Stribling on 9/13/14. // Copyright (c) 2014 Troy Stribling. The MIT License (MIT). // import UIKit import BlueCapKit class BeaconsViewController: UITableViewController { var beaconRegion: FLBeaconRegion? struct MainStoryBoard { static let beaconCell = "BeaconCell" } required init?(coder aDecoder:NSCoder) { super.init(coder:aDecoder) } override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let beaconRegion = self.beaconRegion { self.navigationItem.title = beaconRegion.identifier NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(BeaconsViewController.updateBeacons), name: BlueCapNotification.didUpdateBeacon, object: beaconRegion) } else { self.navigationItem.title = "Beacons" } NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(BeaconsViewController.didEnterBackground), name: UIApplicationDidEnterBackgroundNotification, object: nil) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.navigationItem.title = "" NSNotificationCenter.defaultCenter().removeObserver(self) } override func prepareForSegue(segue:UIStoryboardSegue, sender: AnyObject!) { } func updateBeacons() { BCLogger.debug() self.tableView.reloadData() } func sortBeacons(beacons: [FLBeacon]) -> [FLBeacon] { return beacons.sort(){(b1: FLBeacon, b2: FLBeacon) -> Bool in if b1.major > b2.major { return true } else if b1.major == b2.major && b1.minor > b2.minor { return true } else { return false } } } func didEnterBackground() { BCLogger.debug() self.navigationController?.popToRootViewControllerAnimated(false) } // UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let beaconRegion = self.beaconRegion { return beaconRegion.beacons.count } else { return 0 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(MainStoryBoard.beaconCell, forIndexPath: indexPath) as! BeaconCell if let beaconRegion = self.beaconRegion { let beacon = self.sortBeacons(beaconRegion.beacons)[indexPath.row] cell.proximityUUIDLabel.text = beacon.proximityUUID.UUIDString cell.majorLabel.text = "\(beacon.major)" cell.minorLabel.text = "\(beacon.minor)" cell.proximityLabel.text = beacon.proximity.stringValue cell.rssiLabel.text = "\(beacon.rssi)" let accuracy = NSString(format:"%.4f", beacon.accuracy) cell.accuracyLabel.text = "\(accuracy)m" } return cell } }
mit
db92d1ea6a7f9ee648437374b77fcb02
32.676768
189
0.64847
5.097859
false
false
false
false
ObjSer/objser-swift
ObjSer/util/PairSequence.swift
1
2135
// // PairSequence.swift // ObjSer // // The MIT License (MIT) // // Copyright (c) 2015 Greg Omelaenko // // 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. // struct PairSequenceGenerator<T>: GeneratorType { typealias Element = (T, T) private var generator: AnyGenerator<T> mutating func next() -> (T, T)? { guard let a = generator.next(), let b = generator.next() else { return nil } return (a, b) } } struct PairSequence<Element>: SequenceType { private let sequence: AnySequence<Element> init<S : SequenceType where S.Generator.Element == Element, S.SubSequence : SequenceType, S.SubSequence.Generator.Element == Element, S.SubSequence.SubSequence == S.SubSequence>(_ seq: S) { sequence = AnySequence(seq) } typealias Generator = PairSequenceGenerator<Element> func generate() -> PairSequenceGenerator<Element> { return PairSequenceGenerator(generator: sequence.generate()) } func underestimateCount() -> Int { return sequence.underestimateCount() / 2 } }
mit
1f57b0cecb92014a1d684ae77f133e2a
35.810345
193
0.700703
4.357143
false
false
false
false
koogawa/iSensorSwift
iSensorSwift/Controller/HeadingViewController.swift
1
2038
// // HeadingViewController.swift // iSensorSwift // // Created by Kosuke Ogawa on 2016/03/30. // Copyright © 2016 koogawa. All rights reserved. // import UIKit import CoreLocation class HeadingViewController: UIViewController, CLLocationManagerDelegate { @IBOutlet weak var textField: UITextField! var locationManager: CLLocationManager! override func viewDidLoad() { super.viewDidLoad() if CLLocationManager.locationServicesEnabled() { locationManager = CLLocationManager() locationManager.delegate = self // Specifies the minimum amount of change in degrees needed for a heading service update (default: 1 degree) locationManager.headingFilter = kCLHeadingFilterNone // Specifies a physical device orientation from which heading calculation should be referenced locationManager.headingOrientation = .portrait locationManager.startUpdatingHeading() } } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if CLLocationManager.locationServicesEnabled() { locationManager.stopUpdatingHeading() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - CLLocationManager delegate func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { switch status { case .notDetermined: locationManager.requestWhenInUseAuthorization() case .restricted, .denied: break case .authorizedAlways, .authorizedWhenInUse: break } } func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) { self.textField.text = "".appendingFormat("%.2f", newHeading.magneticHeading) } }
mit
f82a79d92ce5ac62ea862775613ae2ac
30.828125
120
0.661757
6.117117
false
false
false
false
JonyFang/AnimatedDropdownMenu
Examples/Examples/MenuTypes/LeftTypeFourViewController.swift
1
3229
// // LeftTypeFourViewController.swift // AnimatedDropdownMenu // // Created by JonyFang on 17/3/3. // Copyright © 2017年 JonyFang. All rights reserved. // import UIKit import AnimatedDropdownMenu class LeftTypeFourViewController: UIViewController { // MARK: - Properties fileprivate let dropdownItems: [AnimatedDropdownMenu.Item] = [ AnimatedDropdownMenu.Item.init("From | Photography", nil, nil), AnimatedDropdownMenu.Item.init("From | Artwork", nil, nil), AnimatedDropdownMenu.Item.init("Others", nil, nil) ] fileprivate var selectedStageIndex: Int = 0 fileprivate var lastStageIndex: Int = 0 fileprivate var dropdownMenu: AnimatedDropdownMenu! // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() setupAnimatedDropdownMenu() view.backgroundColor = .white } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) resetNavigationBarColor() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) dropdownMenu.show() } // MARK: - Private Methods fileprivate func setupAnimatedDropdownMenu() { let dropdownMenu = AnimatedDropdownMenu(navigationController: navigationController, containerView: view, selectedIndex: selectedStageIndex, items: dropdownItems) dropdownMenu.cellBackgroundColor = UIColor.menuGreenColor() dropdownMenu.menuTitleColor = UIColor.menuLightTextColor() dropdownMenu.menuArrowTintColor = UIColor.menuLightTextColor() dropdownMenu.cellTextColor = UIColor.init(white: 1.0, alpha: 0.3) dropdownMenu.cellTextSelectedColor = UIColor.menuLightTextColor() dropdownMenu.cellTextAlignment = .left dropdownMenu.cellSeparatorColor = .clear dropdownMenu.didSelectItemAtIndexHandler = { [weak self] selectedIndex in guard let strongSelf = self else { return } strongSelf.lastStageIndex = strongSelf.selectedStageIndex strongSelf.selectedStageIndex = selectedIndex guard strongSelf.selectedStageIndex != strongSelf.lastStageIndex else { return } //Configure Selected Action strongSelf.selectedAction() } self.dropdownMenu = dropdownMenu navigationItem.titleView = dropdownMenu } private func selectedAction() { print("\(dropdownItems[selectedStageIndex].title)") } fileprivate func resetNavigationBarColor() { navigationController?.navigationBar.barStyle = .black navigationController?.navigationBar.barTintColor = UIColor.menuGreenColor() let textAttributes: [String: Any] = [ NSForegroundColorAttributeName: UIColor.menuLightTextColor(), NSFontAttributeName: UIFont.navigationBarTitleFont() ] navigationController?.navigationBar.titleTextAttributes = textAttributes } }
mit
2a5cbc94b4f84e1fb49241e5f4ef4226
31.26
169
0.646311
6.16826
false
false
false
false
meetkei/KeiSwiftFramework
KeiSwiftFramework/ViewController/KViewController+Responder.swift
1
2592
// // KViewController+Responder.swift // // Copyright (c) 2016 Keun young Kim <[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. // public extension KViewController { public func findFirstResponder(_ v: UIView? = nil) -> UIView? { if let targetView = v { for item in targetView.subviews { if item.isFirstResponder { return item } if let v = findFirstResponder(item) { return v } } } else { for item in view.subviews { if item.isFirstResponder { return item } if let v = findFirstResponder(item) { return v } } } return nil } public func findFirstResponderAndResign(_ v: UIView? = nil) { if let targetView = v { for item in targetView.subviews { if item.isFirstResponder { item.resignFirstResponder() return } findFirstResponderAndResign(item) } } else { for item in view.subviews { if item.isFirstResponder { item.resignFirstResponder() return } findFirstResponderAndResign(item) } } } }
mit
82f735869b00409f518f3ed3c741c3b4
33.56
81
0.563272
5.268293
false
false
false
false
xiaoxionglaoshi/DNSwiftProject
DNSwiftProject/DNSwiftProject/Classes/Main/DNAddress/Controller/DNAddressViewController.swift
1
3147
// // DNAddressViewController.swift // DNSwiftProject // // Created by mainone on 16/11/25. // Copyright © 2016年 wjn. All rights reserved. // import UIKit class DNAddressViewController: DNBaseViewController { lazy var tableView = UITableView() lazy var modelArr = [DNCycleModel]() var cycleView: DNCycleView? override func viewDidLoad() { super.viewDidLoad() tableView.frame = view.bounds tableView.delegate = self tableView.dataSource = self view.addSubview(tableView) tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellID") cycleView = DNCycleView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 250)) cycleView?.delegate = self tableView.tableHeaderView = cycleView requestData() } func requestData() { let tempArr = [["title":"中国奥运军团三金回顾","imageString":"http://pic33.nipic.com/20130916/3420027_192919547000_2.jpg"], ["title":"《封神传奇》进世界电影特效榜单?山寨的!","imageString":"https://github.com/codestergit/SweetAlert-iOS/blob/master/SweetAlertiOS.gif?raw=true"], ["title":"奥运男子4x100自由泳接力 菲尔普斯,奥运男子4x100自由泳接力 菲尔普斯,奥运男子4x100自由泳接力 菲尔普斯,奥运男子4x100自由泳接力 菲尔普斯","imageString":"http://i1.hexunimg.cn/2014-08-15/167580248.jpg"], ["title":"顶住丢金压力 孙杨晋级200自决赛","imageString":"http://pic6.huitu.com/res/20130116/84481_20130116142820494200_1.jpg"]]; for dict in tempArr { let model = DNCycleModel(fromDict: dict) modelArr.append(model) } cycleView?.dataArr = modelArr } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension DNAddressViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath) cell.textLabel?.text = "我排在第\(indexPath.row)" return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 55 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) for item in 0...4 { if item != 2 { self.tabBarController?.viewControllers?[item].tabBarItem.badgeValue = String(indexPath.row) } } } } extension DNAddressViewController: DNCycleViewDelegate { func cycleViewDidSelected(cycleView: DNCycleView, selectedIndex: NSInteger) { print("打印了\(selectedIndex)") } }
apache-2.0
636402783314199b4c8c9f544b09c67a
34.445783
178
0.653297
3.917443
false
false
false
false
Norod/Filterpedia
Filterpedia/components/FilterInputItemRenderer.swift
1
10493
// // FilterInputItemRenderer.swift // Filterpedia // // Created by Simon Gladman on 30/12/2015. // Copyright © 2015 Simon Gladman. All rights reserved. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> import UIKit class FilterInputItemRenderer: UITableViewCell { let textEditButton = UIButton() let slider = LabelledSlider() let vectorSlider = VectorSlider() let imagesSegmentedControl = UISegmentedControl(items: assetLabels) let titleLabel = UILabel() let shapeLayer: CAShapeLayer = { let layer = CAShapeLayer() layer.strokeColor = UIColor.lightGray.cgColor layer.fillColor = nil layer.lineWidth = 0.5 return layer }() let descriptionLabel: UILabel = { let label = UILabel() label.numberOfLines = 2 label.font = UIFont.italicSystemFont(ofSize: 12) return label }() let stackView: UIStackView = { let stackView = UIStackView() stackView.axis = UILayoutConstraintAxis.vertical return stackView }() weak var delegate: FilterInputItemRendererDelegate? private(set) var inputKey: String = "" var detail: (inputKey: String, attribute: [String : Any], filterParameterValues: [String: AnyObject]) = ("", [String: AnyObject](), [String: AnyObject]()) { didSet { filterParameterValues = detail.filterParameterValues inputKey = detail.inputKey attribute = detail.attribute } } private var title: String = "" private var filterParameterValues = [String: AnyObject]() private(set) var attribute = [String : Any]() { didSet { let displayName = attribute[kCIAttributeDisplayName] as? String ?? "" let className = attribute[kCIAttributeClass] as? String ?? "" title = "\(displayName) (\(inputKey): \(className))" titleLabel.text = "\(displayName) (\(inputKey): \(className))" descriptionLabel.text = attribute[kCIAttributeDescription] as? String ?? "[No description]" updateForAttribute() } } private(set) var value: AnyObject? { didSet { delegate?.filterInputItemRenderer(self, didChangeValue: value, forKey: inputKey) if let value = value { titleLabel.text = title + " = \(value)" } } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.layer.addSublayer(shapeLayer) contentView.addSubview(stackView) textEditButton.layer.cornerRadius = 5 textEditButton.layer.backgroundColor = UIColor(white: 0.8, alpha: 1.0).cgColor textEditButton.setTitleColor(UIColor.blue, for: UIControlState()) stackView.addArrangedSubview(titleLabel) stackView.addArrangedSubview(descriptionLabel) stackView.addArrangedSubview(slider) stackView.addArrangedSubview(imagesSegmentedControl) stackView.addArrangedSubview(vectorSlider) stackView.addArrangedSubview(textEditButton) slider.addTarget(self, action: #selector(FilterInputItemRenderer.sliderChangeHandler), for: UIControlEvents.valueChanged) vectorSlider.addTarget(self, action: #selector(FilterInputItemRenderer.vectorSliderChangeHandler), for: UIControlEvents.valueChanged) imagesSegmentedControl.addTarget(self, action: #selector(FilterInputItemRenderer.imagesSegmentedControlChangeHandler), for: UIControlEvents.valueChanged) textEditButton.addTarget(self, action: #selector(FilterInputItemRenderer.textEditClicked), for: .touchDown) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Change handlers func sliderChangeHandler() { value = slider.value as AnyObject? } func vectorSliderChangeHandler() { guard let attributeType = attribute[kCIAttributeClass] as? String, let vector = vectorSlider.vector else { return } if attributeType == "CIColor" { value = CIColor(red: vector.x, green: vector.y, blue: vector.z, alpha: vector.w) } else { value = vector } } func imagesSegmentedControlChangeHandler() { value = assets[imagesSegmentedControl.selectedSegmentIndex].ciImage } func textEditClicked() { guard let rootController = UIApplication.shared.keyWindow!.rootViewController else { return } let editTextController = UIAlertController(title: "Filterpedia", message: nil, preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (_: UIAlertAction) in if let updatedText = editTextController.textFields?.first?.text { self.value = updatedText as AnyObject? self.textEditButton.setTitle(updatedText, for: UIControlState()) } } let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil) editTextController.addTextField { (textField: UITextField) in textField.text = self.value as? String } editTextController.addAction(okAction) editTextController.addAction(cancelAction) rootController.present(editTextController, animated: false, completion: nil) } // MARK: Update user interface for attributes func updateForAttribute() { guard let attributeType = attribute[kCIAttributeClass] as? String else { return } switch attributeType { case "NSNumber": slider.isHidden = false imagesSegmentedControl.isHidden = true vectorSlider.isHidden = true textEditButton.isHidden = true slider.min = attribute[kCIAttributeSliderMin] as? Float ?? 0 slider.max = attribute[kCIAttributeSliderMax] as? Float ?? 1 slider.value = filterParameterValues[inputKey] as? Float ?? attribute[kCIAttributeDefault] as? Float ?? attribute[kCIAttributeSliderMin] as? Float ?? 0 sliderChangeHandler() case "CIImage": slider.isHidden = true imagesSegmentedControl.isHidden = false vectorSlider.isHidden = true textEditButton.isHidden = true imagesSegmentedControl.selectedSegmentIndex = assets.index(where: { $0.ciImage == filterParameterValues[inputKey] as? CIImage}) ?? 0 imagesSegmentedControlChangeHandler() case "CIVector": slider.isHidden = true imagesSegmentedControl.isHidden = true vectorSlider.isHidden = false textEditButton.isHidden = true let max: CGFloat? = (attribute[kCIAttributeType] as? String == kCIAttributeTypePosition) ? 640 : nil let vector = filterParameterValues[inputKey] as? CIVector ?? attribute[kCIAttributeDefault] as? CIVector vectorSlider.vectorWithMaximumValue = (vector, max) vectorSliderChangeHandler() case "CIColor": slider.isHidden = true imagesSegmentedControl.isHidden = true vectorSlider.isHidden = false textEditButton.isHidden = true if let color = filterParameterValues[inputKey] as? CIColor ?? attribute[kCIAttributeDefault] as? CIColor { let colorVector = CIVector(x: color.red, y: color.green, z: color.blue, w: color.alpha) vectorSlider.vectorWithMaximumValue = (colorVector, nil) } vectorSliderChangeHandler() case "NSString": slider.isHidden = true imagesSegmentedControl.isHidden = true vectorSlider.isHidden = true textEditButton.isHidden = false let text = filterParameterValues[inputKey] as? NSString ?? attribute[kCIAttributeDefault] as? NSString ?? "" value = text textEditButton.setTitle(String(text), for: UIControlState()) default: slider.isHidden = true imagesSegmentedControl.isHidden = true vectorSlider.isHidden = true textEditButton.isHidden = true } } override func layoutSubviews() { stackView.frame = contentView.bounds.insetBy(dx: 5, dy: 5) let path = UIBezierPath() path.move(to: CGPoint(x: 5, y: contentView.bounds.height)) path.addLine(to: CGPoint(x: contentView.bounds.width, y: contentView.bounds.height)) shapeLayer.path = path.cgPath } } // MARK: FilterInputItemRendererDelegate protocol FilterInputItemRendererDelegate: class { func filterInputItemRenderer(_ filterInputItemRenderer: FilterInputItemRenderer, didChangeValue: AnyObject?, forKey: String?) }
gpl-3.0
4ee76af9b3a9b92e69857c86d4b7c2e0
31.890282
158
0.600457
5.408247
false
false
false
false
apple/swift
test/Parse/optional_lvalues.swift
66
3110
// RUN: %target-typecheck-verify-swift struct S { var x: Int = 0 let y: Int = 0 // expected-note 4 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} {{3-6=var}} {{3-6=var}} init() {} } struct T { var mutS: S? = nil let immS: S? = nil // expected-note 10 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} {{3-6=var}} {{3-6=var}} {{3-6=var}} {{3-6=var}} {{3-6=var}} {{3-6=var}} {{3-6=var}} {{3-6=var}} init() {} } var mutT: T? let immT: T? = nil // expected-note 4 {{change 'let' to 'var' to make it mutable}} {{1-4=var}} {{1-4=var}} {{1-4=var}} {{1-4=var}} let mutTPayload = mutT! mutT! = T() mutT!.mutS = S() mutT!.mutS! = S() mutT!.mutS!.x = 0 mutT!.mutS!.y = 0 // expected-error{{cannot assign to property: 'y' is a 'let' constant}} mutT!.immS = S() // expected-error{{cannot assign to property: 'immS' is a 'let' constant}} mutT!.immS! = S() // expected-error{{cannot assign through '!': 'immS' is a 'let' constant}} mutT!.immS!.x = 0 // expected-error{{cannot assign to property: 'immS' is a 'let' constant}} mutT!.immS!.y = 0 // expected-error{{cannot assign to property: 'y' is a 'let' constant}} immT! = T() // expected-error{{cannot assign through '!': 'immT' is a 'let' constant}} immT!.mutS = S() // expected-error{{cannot assign to property: 'immT' is a 'let' constant}} immT!.mutS! = S() // expected-error{{cannot assign through '!': 'immT' is a 'let' constant}} immT!.mutS!.x = 0 // expected-error{{cannot assign to property: 'immT' is a 'let' constant}} immT!.mutS!.y = 0 // expected-error{{cannot assign to property: 'y' is a 'let' constant}} immT!.immS = S() // expected-error{{cannot assign to property: 'immS' is a 'let' constant}} immT!.immS! = S() // expected-error{{cannot assign through '!': 'immS' is a 'let' constant}} immT!.immS!.x = 0 // expected-error{{cannot assign to property: 'immS' is a 'let' constant}} immT!.immS!.y = 0 // expected-error{{cannot assign to property: 'y' is a 'let' constant}} var mutIUO: T! = nil let immIUO: T! = nil // expected-note 2 {{change 'let' to 'var' to make it mutable}} {{1-4=var}} {{1-4=var}} mutIUO!.mutS = S() mutIUO!.immS = S() // expected-error{{cannot assign to property: 'immS' is a 'let' constant}} immIUO!.mutS = S() // expected-error{{cannot assign to property: 'immIUO' is a 'let' constant}} immIUO!.immS = S() // expected-error{{cannot assign to property: 'immS' is a 'let' constant}} mutIUO.mutS = S() mutIUO.immS = S() // expected-error{{cannot assign to property: 'immS' is a 'let' constant}} immIUO.mutS = S() // expected-error{{cannot assign to property: 'immIUO' is a 'let' constant}} immIUO.immS = S() // expected-error{{cannot assign to property: 'immS' is a 'let' constant}} func foo(x: Int) {} var nonOptional: S = S() _ = nonOptional! // expected-error{{cannot force unwrap value of non-optional type 'S'}} {{16-17=}} _ = nonOptional!.x // expected-error{{cannot force unwrap value of non-optional type 'S'}} {{16-17=}} class C {} class D: C {} let c = C() let d = (c as! D)! // expected-error{{cannot force unwrap value of non-optional type 'D'}} {{18-19=}}
apache-2.0
0ab3bd3ebc5577557eace0934d74daa8
46.846154
205
0.629582
2.791741
false
false
false
false
kimseongrim/KimSampleCode
UIStepper/UIStepper/ViewController.swift
1
1460
// // ViewController.swift // UIStepper // // Created by 金成林 on 15/1/24. // Copyright (c) 2015年 Kim. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var mUIStepper: UIStepper! @IBOutlet weak var mUILabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //设定stepper的范围与起始值 mUIStepper.minimumValue = 0 mUIStepper.maximumValue = 10 mUIStepper.stepValue = 1 //设定stepper是否循环(到最大值时再增加数值最从最小值开始) mUIStepper.wraps = true //默认true,true时表示当用户按住时会持续发送ValueChange事件,false则是只有等用户交互结束时才发送ValueChange事件 mUIStepper.continuous = true //默认true,true时表示按住加号或减号不松手,数字会持续变化 mUIStepper.autorepeat = true mUIStepper.addTarget(self, action: "stepperValueIschanged", forControlEvents: UIControlEvents.ValueChanged) } func stepperValueIschanged() { // Double 转 String mUILabel.text = "\(mUIStepper.value)" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-2.0
a5f676d8af2ff0f5223f8663a18d9884
25.25
115
0.656349
4.064516
false
false
false
false
QuarkWorks/RealmModelGenerator
RealmModelGenerator/VersionVC.swift
1
2137
// // VersionVC.swift // RealmModelGenerator // // Created by Zhaolong Zhong on 4/20/16. // Copyright © 2016 QuarkWorks. All rights reserved. // import Cocoa protocol VersionVCDelegate: AnyObject { func versionVC(versionVC:VersionVC, selectedModelDidChange currentModel:Model?) } class VersionVC: NSViewController { static let TAG = NSStringFromClass(VersionVC.self) @IBOutlet weak var versionPopUpButton: NSPopUpButton! var schema = Schema() { didSet { schema.models.forEach({(e) in modelVersions.append(e.version) }) } } private var currentModel: Model { return self.schema.currentModel } private var modelVersions:[String] = ["New version"] weak var delegate:VersionVCDelegate? override func viewDidLoad() { super.viewDidLoad() versionPopUpButton.removeAllItems() versionPopUpButton.addItems(withTitles: modelVersions) versionPopUpButton.selectItem(withTitle: currentModel.version) } @IBAction func cancelButtonOnClick(sender: Any) { self.dismiss(self) } @IBAction func okButtonOnClick(sender: Any) { self.dismiss(self) if versionPopUpButton.indexOfSelectedItem == modelVersions.index(of: self.currentModel.version) { return } else if versionPopUpButton.indexOfSelectedItem == 0 { do { try schema.increaseVersion() } catch { Tools.popupAlert(messageText: "Error", buttonTitle: "OK", informativeText: "Cannot increase version") } } else { if versionPopUpButton.indexOfSelectedItem != modelVersions.index(of: self.currentModel.version) { self.currentModel.isModifiable = false self.schema.models.filter({$0.version == versionPopUpButton.titleOfSelectedItem}).first!.isModifiable = true } } self.schema.observable.notifyObservers() self.delegate?.versionVC(versionVC: self, selectedModelDidChange: currentModel) } }
mit
7c205b26571c38d8283eaf9dc0305f9e
30.880597
124
0.639513
4.876712
false
false
false
false
brentdax/swift
test/ClangImporter/sdk-bridging-header.swift
16
1374
// RUN: %target-typecheck-verify-swift -import-objc-header %S/Inputs/sdk-bridging-header.h // RUN: not %target-swift-frontend -typecheck %s -import-objc-header %S/Inputs/bad-bridging-header.h 2>&1 | %FileCheck -check-prefix=CHECK-FATAL %s // RUN: %target-typecheck-verify-swift -Xcc -include -Xcc %S/Inputs/sdk-bridging-header.h -import-objc-header %S/../Inputs/empty.swift // RUN: not %target-swift-frontend -typecheck %s -Xcc -include -Xcc %S/Inputs/bad-bridging-header.h 2>&1 | %FileCheck -check-prefix=CHECK-INCLUDE %s // RUN: not %target-swift-frontend -typecheck %s -Xcc -include -Xcc %S/Inputs/bad-bridging-header.h -import-objc-header %S/../Inputs/empty.swift 2>&1 | %FileCheck -check-prefix=CHECK-INCLUDE %s // RUN: not %target-swift-frontend -typecheck %s -Xcc -include -Xcc %S/Inputs/bad-bridging-header.h -import-objc-header %S/Inputs/sdk-bridging-header.h 2>&1 | %FileCheck -check-prefix=CHECK-INCLUDE %s // CHECK-FATAL: failed to import bridging header // CHECK-INCLUDE: error: 'this-header-does-not-exist.h' file not found // CHECK-INCLUDE: error: use of unresolved identifier 'MyPredicate' // REQUIRES: objc_interop import Foundation let `true` = MyPredicate.`true`() let not = MyPredicate.not() let and = MyPredicate.and([]) let or = MyPredicate.or([not, and]) _ = MyPredicate.foobar() // expected-error{{type 'MyPredicate' has no member 'foobar'}}
apache-2.0
99980605781a9eaf1c06da5b6a821826
56.25
200
0.729985
3.108597
false
false
false
false
ansinlee/meteorology
meteorology/AppDelegate.swift
1
2432
// // AppDelegate.swift // meteorology // // Created by LeeAnsin on 15/3/16. // Copyright (c) 2015年 LeeAnsin. All rights reserved. // import UIKit // 主题颜色 let NavBarBackgroudColor = UIColor(red:74/255, green:171/255, blue:247/255, alpha:1.00) let MainBackgroudColor = UIColor(red:0.90, green:0.90, blue:0.95, alpha:1.00) let MainCornerRadius = CGFloat(16) let MainBorderWidth = CGFloat(1) let BottomNavBarHeight = CGFloat(40) @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
b9c0992b7c18e85dd2b5d462ff788d88
44.698113
285
0.754335
4.942857
false
false
false
false
coderwjq/swiftweibo
SwiftWeibo/SwiftWeibo/Classes/Main/View/Status.swift
1
1259
// // Status.swift // SwiftWeibo // // Created by mzzdxt on 2016/11/3. // Copyright © 2016年 wjq. All rights reserved. // import UIKit class Status: NSObject { // MARK:- 属性 var created_at: String? // 微博的创建时间 var source: String? // 微博来源 var text: String? // 微博的正文 var mid: Int = 0 // 微博的id var user: User? // 微博的作者 var pic_urls: [[String : String]]? // 微博的配图 var retweeted_status: Status? // 微博对应的转发微博 // MARK:- 自定义构造函数 init(dict: [String : AnyObject]) { super.init() setValuesForKeys(dict) // 将用户字典转成用户模型对象 if let userDict = dict["user"] as? [String : AnyObject] { user = User(dict: userDict) } // 将转发微博字典转成转发微博模型对象 if let retweetedStatusDict = dict["retweeted_status"] as? [String : AnyObject] { retweeted_status = Status(dict: retweetedStatusDict) } } override func setValue(_ value: Any?, forUndefinedKey key: String) { } }
apache-2.0
97ef17ca83ebf38066ba68e68f64ecab
25.878049
88
0.521779
4.03663
false
false
false
false
kylef/JSONSchema.swift
Sources/Core/ref.swift
1
920
enum ReferenceError: Error { case notFound } func ref(context: Context, reference: Any, instance: Any, schema: [String: Any]) throws -> AnySequence<ValidationError> { guard let reference = reference as? String else { return AnySequence(EmptyCollection()) } guard let document = context.resolve(ref: reference) else { throw ReferenceError.notFound } let id: String? if let document = document as? [String: Any], let idValue = document[context.resolver.idField] as? String { id = urlNormalise(idValue) } else { id = nil } if let id = id { context.resolver.stack.append(id) } defer { if let id = id { assert(context.resolver.stack.removeLast() == id, "popping id mismatch - if this assertion is triggered, there's probably a bug in JSON Schema context library") } } return try context.descend(instance: instance, subschema: document) }
bsd-3-clause
7ae4ef51f5865edc799b0415c3032f59
26.058824
123
0.676087
3.982684
false
false
false
false
stephentyrone/swift
test/stmt/statements.swift
5
22488
// RUN: %target-typecheck-verify-swift /* block comments */ /* /* nested too */ */ func markUsed<T>(_ t: T) {} func f1(_ a: Int, _ y: Int) {} func f2() {} func f3() -> Int {} func invalid_semi() { ; // expected-error {{';' statements are not allowed}} {{3-5=}} } func nested1(_ x: Int) { var y : Int // expected-warning@-1 {{variable 'y' was never mutated; consider changing to 'let' constant}} func nested2(_ z: Int) -> Int { return x+y+z } _ = nested2(1) } func funcdecl5(_ a: Int, y: Int) { var x : Int // a few statements if (x != 0) { if (x != 0 || f3() != 0) { // while with and without a space after it. while(true) { 4; 2; 1 } // expected-warning 3 {{integer literal is unused}} while (true) { 4; 2; 1 } // expected-warning 3 {{integer literal is unused}} } } // Assignment statement. x = y (x) = y 1 = x // expected-error {{cannot assign to value: literals are not mutable}} (1) = x // expected-error {{cannot assign to value: literals are not mutable}} "string" = "other" // expected-error {{cannot assign to value: literals are not mutable}} [1, 1, 1, 1] = [1, 1] // expected-error {{cannot assign to immutable expression of type '[Int]}} 1.0 = x // expected-error {{cannot assign to value: literals are not mutable}} nil = 1 // expected-error {{cannot assign to value: literals are not mutable}} (x:1).x = 1 // expected-error {{cannot assign to immutable expression of type 'Int'}} var tup : (x:Int, y:Int) tup.x = 1 _ = tup let B : Bool // if/then/else. if (B) { } else if (y == 2) { } // This diagnostic is terrible - rdar://12939553 if x {} // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}} if true { if (B) { } else { } } if (B) { f1(1,2) } else { f2() } if (B) { if (B) { f1(1,2) } else { f2() } } else { f2() } // while statement. while (B) { } // It's okay to leave out the spaces in these. while(B) {} if(B) {} } struct infloopbool { var boolValue: infloopbool { return self } } func infloopbooltest() { if (infloopbool()) {} // expected-error {{cannot convert value of type 'infloopbool' to expected condition type 'Bool'}} } // test "builder" API style extension Int { static func builder() -> Int { } var builderProp: Int { return 0 } func builder2() {} } Int .builder() .builderProp .builder2() struct SomeGeneric<T> { static func builder() -> SomeGeneric<T> { } var builderProp: SomeGeneric<T> { return .builder() } func builder2() {} } SomeGeneric<Int> .builder() .builderProp .builder2() break // expected-error {{'break' is only allowed inside a loop, if, do, or switch}} continue // expected-error {{'continue' is only allowed inside a loop}} while true { func f() { break // expected-error {{'break' is only allowed inside a loop}} continue // expected-error {{'continue' is only allowed inside a loop}} } // Labeled if MyIf: if 1 != 2 { break MyIf continue MyIf // expected-error {{'continue' cannot be used with if statements}} break // break the while continue // continue the while. } } // Labeled if MyOtherIf: if 1 != 2 { break MyOtherIf continue MyOtherIf // expected-error {{'continue' cannot be used with if statements}} break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if}} continue // expected-error {{'continue' is only allowed inside a loop}} } do { break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}} } func tuple_assign() { var a,b,c,d : Int (a,b) = (1,2) func f() -> (Int,Int) { return (1,2) } ((a,b), (c,d)) = (f(), f()) _ = (a,b,c,d) } func missing_semicolons() { var w = 321 func g() {} g() w += 1 // expected-error{{consecutive statements}} {{6-6=;}} var z = w"hello" // expected-error{{consecutive statements}} {{12-12=;}} expected-warning {{string literal is unused}} // expected-warning@-1 {{initialization of variable 'z' was never used; consider replacing with assignment to '_' or removing it}} class C {}class C2 {} // expected-error{{consecutive statements}} {{14-14=;}} struct S {}struct S2 {} // expected-error{{consecutive statements}} {{14-14=;}} func j() {}func k() {} // expected-error{{consecutive statements}} {{14-14=;}} } //===--- Return statement. return 42 // expected-error {{return invalid outside of a func}} return // expected-error {{return invalid outside of a func}} func NonVoidReturn1() -> Int { _ = 0 return // expected-error {{non-void function should return a value}} } func NonVoidReturn2() -> Int { return + // expected-error {{unary operator cannot be separated from its operand}} {{11-1=}} expected-error {{expected expression in 'return' statement}} } func VoidReturn1() { if true { return } // Semicolon should be accepted -- rdar://11344875 return; // no-error } func VoidReturn2() { return () // no-error } func VoidReturn3() { return VoidReturn2() // no-error } //===--- If statement. func IfStmt1() { if 1 > 0 // expected-error {{expected '{' after 'if' condition}} _ = 42 } func IfStmt2() { if 1 > 0 { } else // expected-error {{expected '{' or 'if' after 'else'}} _ = 42 } func IfStmt3() { if 1 > 0 { } else 1 < 0 { // expected-error {{expected '{' or 'if' after 'else'; did you mean to write 'if'?}} {{9-9= if}} _ = 42 } else { } } //===--- While statement. func WhileStmt1() { while 1 > 0 // expected-error {{expected '{' after 'while' condition}} _ = 42 } //===-- Do statement. func DoStmt() { // This is just a 'do' statement now. do { } } func DoWhileStmt1() { do { // expected-error {{'do-while' statement is not allowed}} // expected-note@-1 {{did you mean 'repeat-while' statement?}} {{3-5=repeat}} // expected-note@-2 {{did you mean separate 'do' and 'while' statements?}} {{5-5=\n}} } while true } func DoWhileStmt2() { do { } while true { } } func LabeledDoStmt() { LABEL: { // expected-error {{labeled block needs 'do'}} {{10-10=do }} } } //===--- Repeat-while statement. func RepeatWhileStmt1() { repeat {} while true repeat {} while false repeat { break } while true repeat { continue } while true } func RepeatWhileStmt2() { repeat // expected-error {{expected '{' after 'repeat'}} expected-error {{expected 'while' after body of 'repeat' statement}} } func RepeatWhileStmt4() { repeat { } while + // expected-error {{unary operator cannot be separated from its operand}} {{12-1=}} expected-error {{expected expression in 'repeat-while' condition}} } func brokenSwitch(_ x: Int) -> Int { switch x { case .Blah(var rep): // expected-error{{pattern cannot match values of type 'Int'}} return rep } } func switchWithVarsNotMatchingTypes(_ x: Int, y: Int, z: String) -> Int { switch (x,y,z) { case (let a, 0, _), (0, let a, _): // OK return a case (let a, _, _), (_, _, let a): // expected-error {{pattern variable bound to type 'String', expected type 'Int'}} // expected-warning@-1 {{case is already handled by previous patterns; consider removing it}} return a } } func breakContinue(_ x : Int) -> Int { Outer: for _ in 0...1000 { Switch: // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}} switch x { case 42: break Outer case 97: continue Outer case 102: break Switch case 13: continue case 139: break // <rdar://problem/16563853> 'break' should be able to break out of switch statements } } // <rdar://problem/16692437> shadowing loop labels should be an error Loop: // expected-note {{previously declared here}} for _ in 0...2 { Loop: // expected-error {{label 'Loop' cannot be reused on an inner statement}} for _ in 0...2 { } } // <rdar://problem/16798323> Following a 'break' statement by another statement on a new line result in an error/fit-it switch 5 { case 5: markUsed("before the break") break markUsed("after the break") // 'markUsed' is not a label for the break. default: markUsed("") } let x : Int? = 42 // <rdar://problem/16879701> Should be able to pattern match 'nil' against optionals switch x { // expected-error {{switch must be exhaustive}} // expected-note@-1 {{missing case: '.some(_)'}} case .some(42): break case nil: break } } enum MyEnumWithCaseLabels { case Case(one: String, two: Int) } func testMyEnumWithCaseLabels(_ a : MyEnumWithCaseLabels) { // <rdar://problem/20135489> Enum case labels are ignored in "case let" statements switch a { case let .Case(one: _, two: x): break // ok case let .Case(xxx: _, two: x): break // expected-error {{tuple pattern element label 'xxx' must be 'one'}} // TODO: In principle, reordering like this could be supported. case let .Case(two: _, one: x): break // expected-error {{tuple pattern element label}} } } // "defer" func test_defer(_ a : Int) { defer { VoidReturn1() } defer { breakContinue(1)+42 } // expected-warning {{result of operator '+' is unused}} // Ok: defer { while false { break } } // Not ok. while false { defer { break } } // expected-error {{'break' cannot transfer control out of a defer statement}} // expected-warning@-1 {{'defer' statement at end of scope always executes immediately}}{{17-22=do}} defer { return } // expected-error {{'return' cannot transfer control out of a defer statement}} // expected-warning@-1 {{'defer' statement at end of scope always executes immediately}}{{3-8=do}} } class SomeTestClass { var x = 42 func method() { defer { x = 97 } // self. not required here! // expected-warning@-1 {{'defer' statement at end of scope always executes immediately}}{{5-10=do}} } } enum DeferThrowError: Error { case someError } func throwInDefer() { defer { throw DeferThrowError.someError } // expected-error {{errors cannot be thrown out of a defer body}} print("Foo") } func throwInDeferOK1() { defer { do { throw DeferThrowError.someError } catch {} } print("Bar") } func throwInDeferOK2() throws { defer { do { throw DeferThrowError.someError } catch {} } print("Bar") } func throwingFuncInDefer1() throws { defer { try throwingFunctionCalledInDefer() } // expected-error {{errors cannot be thrown out of a defer body}} print("Bar") } func throwingFuncInDefer1a() throws { defer { do { try throwingFunctionCalledInDefer() } catch {} } print("Bar") } func throwingFuncInDefer2() throws { defer { throwingFunctionCalledInDefer() } // expected-error {{errors cannot be thrown out of a defer body}} print("Bar") } func throwingFuncInDefer2a() throws { defer { do { throwingFunctionCalledInDefer() // expected-error@-1 {{call can throw but is not marked with 'try'}} // expected-note@-2 {{did you mean to use 'try'?}} // expected-note@-3 {{did you mean to handle error as optional value?}} // expected-note@-4 {{did you mean to disable error propagation?}} } catch {} } print("Bar") } func throwingFuncInDefer3() { defer { try throwingFunctionCalledInDefer() } // expected-error {{errors cannot be thrown out of a defer body}} print("Bar") } func throwingFuncInDefer3a() { defer { do { try throwingFunctionCalledInDefer() } catch {} } print("Bar") } func throwingFuncInDefer4() { defer { throwingFunctionCalledInDefer() } // expected-error {{errors cannot be thrown out of a defer body}} print("Bar") } func throwingFuncInDefer4a() { defer { do { throwingFunctionCalledInDefer() // expected-error@-1 {{call can throw but is not marked with 'try'}} // expected-note@-2 {{did you mean to use 'try'?}} // expected-note@-3 {{did you mean to handle error as optional value?}} // expected-note@-4 {{did you mean to disable error propagation?}} } catch {} } print("Bar") } func throwingFunctionCalledInDefer() throws { throw DeferThrowError.someError } class SomeDerivedClass: SomeTestClass { override init() { defer { super.init() // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}} } } } func test_guard(_ x : Int, y : Int??, cond : Bool) { // These are all ok. guard let a = y else {} markUsed(a) guard let b = y, cond else {} guard case let c = x, cond else {} guard case let Optional.some(d) = y else {} guard x != 4, case _ = x else { } guard let e, cond else {} // expected-error {{variable binding in a condition requires an initializer}} guard case let f? : Int?, cond else {} // expected-error {{variable binding in a condition requires an initializer}} guard let g = y else { markUsed(g) // expected-error {{variable declared in 'guard' condition is not usable in its body}} } guard let h = y, cond {} // expected-error {{expected 'else' after 'guard' condition}} {{25-25=else }} guard case _ = x else {} // expected-warning {{'guard' condition is always true, body is unreachable}} // SR-7567 guard let outer = y else { guard true else { print(outer) // expected-error {{variable declared in 'guard' condition is not usable in its body}} } } } func test_is_as_patterns() { switch 4 { case is Int: break // expected-warning {{'is' test is always true}} case _ as Int: break // expected-warning {{'as' test is always true}} // expected-warning@-1 {{case is already handled by previous patterns; consider removing it}} case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}} } } // <rdar://problem/21387308> Fuzzing SourceKit: crash in Parser::parseStmtForEach(...) func matching_pattern_recursion() { switch 42 { case { // expected-error {{expression pattern of type '() -> ()' cannot match values of type 'Int'}} for i in zs { } }: break } } // <rdar://problem/18776073> Swift's break operator in switch should be indicated in errors func r18776073(_ a : Int?) { switch a { case nil: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{14-14= break}} case _?: break } } // <rdar://problem/22491782> unhelpful error message from "throw nil" func testThrowNil() throws { throw nil // expected-error {{cannot infer concrete Error for thrown 'nil' value}} } // rdar://problem/23684220 // Even if the condition fails to typecheck, save it in the AST anyway; the old // condition may have contained a SequenceExpr. func r23684220(_ b: Any) { if let _ = b ?? b {} // expected-warning {{left side of nil coalescing operator '??' has non-optional type 'Any', so the right side is never used}} // expected-error@-1 {{initializer for conditional binding must have Optional type, not 'Any'}} } // <rdar://problem/21080671> QoI: try/catch (instead of do/catch) creates silly diagnostics func f21080671() { try { // expected-error {{the 'do' keyword is used to specify a 'catch' region}} {{3-6=do}} } catch { } try { // expected-error {{the 'do' keyword is used to specify a 'catch' region}} {{3-6=do}} f21080671() } catch let x as Int { } catch { } } // <rdar://problem/24467411> QoI: Using "&& #available" should fixit to comma // https://twitter.com/radexp/status/694561060230184960 func f(_ x : Int, y : Int) { if x == y && #available(iOS 52, *) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-15=,}} if #available(iOS 52, *) && x == y {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{27-30=,}} // https://twitter.com/radexp/status/694790631881883648 if x == y && let _ = Optional(y) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-15=,}} if x == y&&let _ = Optional(y) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-14=,}} } // <rdar://problem/25178926> QoI: Warn about cases where switch statement "ignores" where clause enum Type { case Foo case Bar } func r25178926(_ a : Type) { switch a { // expected-error {{switch must be exhaustive}} // expected-note@-1 {{missing case: '.Bar'}} case .Foo, .Bar where 1 != 100: // expected-warning @-1 {{'where' only applies to the second pattern match in this case}} // expected-note @-2 {{disambiguate by adding a line break between them if this is desired}} {{14-14=\n }} // expected-note @-3 {{duplicate the 'where' on both patterns to check both patterns}} {{12-12= where 1 != 100}} break } switch a { // expected-error {{switch must be exhaustive}} // expected-note@-1 {{missing case: '.Bar'}} case .Foo: break case .Bar where 1 != 100: break } switch a { // expected-error {{switch must be exhaustive}} // expected-note@-1 {{missing case: '.Bar'}} case .Foo, // no warn .Bar where 1 != 100: break } switch a { // expected-error {{switch must be exhaustive}} // expected-note@-1 {{missing case: '.Foo'}} // expected-note@-2 {{missing case: '.Bar'}} case .Foo where 1 != 100, .Bar where 1 != 100: break } } do { guard 1 == 2 else { break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}} } } func fn(a: Int) { guard a < 1 else { break // expected-error {{'break' is only allowed inside a loop, if, do, or switch}} } } func fn(x: Int) { if x >= 0 { guard x < 1 else { guard x < 2 else { break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}} } return } } } func bad_if() { if 1 {} // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}} if (x: false) {} // expected-error {{cannot convert value of type '(x: Bool)' to expected condition type 'Bool'}} if (x: 1) {} // expected-error {{cannot convert value of type '(x: Int)' to expected condition type 'Bool'}} if nil {} // expected-error {{'nil' is not compatible with expected condition type 'Bool'}} } // Typo correction for loop labels for _ in [1] { break outerloop // expected-error {{cannot find label 'outerloop' in scope}} continue outerloop // expected-error {{cannot find label 'outerloop' in scope}} } while true { break outerloop // expected-error {{cannot find label 'outerloop' in scope}} continue outerloop // expected-error {{cannot find label 'outerloop' in scope}} } repeat { break outerloop // expected-error {{cannot find label 'outerloop' in scope}} continue outerloop // expected-error {{cannot find label 'outerloop' in scope}} } while true outerLoop: for _ in [1] { // expected-note {{'outerLoop' declared here}} break outerloop // expected-error {{cannot find label 'outerloop' in scope; did you mean 'outerLoop'?}} {{9-18=outerLoop}} } outerLoop: for _ in [1] { // expected-note {{'outerLoop' declared here}} continue outerloop // expected-error {{cannot find label 'outerloop' in scope; did you mean 'outerLoop'?}} {{12-21=outerLoop}} } outerLoop: while true { // expected-note {{'outerLoop' declared here}} break outerloop // expected-error {{cannot find label 'outerloop' in scope; did you mean 'outerLoop'?}} {{9-18=outerLoop}} } outerLoop: while true { // expected-note {{'outerLoop' declared here}} continue outerloop // expected-error {{cannot find label 'outerloop' in scope; did you mean 'outerLoop'?}} {{12-21=outerLoop}} } outerLoop: repeat { // expected-note {{'outerLoop' declared here}} break outerloop // expected-error {{cannot find label 'outerloop' in scope; did you mean 'outerLoop'?}} {{9-18=outerLoop}} } while true outerLoop: repeat { // expected-note {{'outerLoop' declared here}} continue outerloop // expected-error {{cannot find label 'outerloop' in scope; did you mean 'outerLoop'?}} {{12-21=outerLoop}} } while true outerLoop1: for _ in [1] { // expected-note {{did you mean 'outerLoop1'?}} {{11-20=outerLoop1}} outerLoop2: for _ in [1] { // expected-note {{did you mean 'outerLoop2'?}} {{11-20=outerLoop2}} break outerloop // expected-error {{cannot find label 'outerloop' in scope}} } } outerLoop1: for _ in [1] { // expected-note {{did you mean 'outerLoop1'?}} {{14-23=outerLoop1}} outerLoop2: for _ in [1] { // expected-note {{did you mean 'outerLoop2'?}} {{14-23=outerLoop2}} continue outerloop // expected-error {{cannot find label 'outerloop' in scope}} } } outerLoop1: while true { // expected-note {{did you mean 'outerLoop1'?}} {{11-20=outerLoop1}} outerLoop2: while true { // expected-note {{did you mean 'outerLoop2'?}} {{11-20=outerLoop2}} break outerloop // expected-error {{cannot find label 'outerloop' in scope}} } } outerLoop1: while true { // expected-note {{did you mean 'outerLoop1'?}} {{14-23=outerLoop1}} outerLoop2: while true { // expected-note {{did you mean 'outerLoop2'?}} {{14-23=outerLoop2}} continue outerloop // expected-error {{cannot find label 'outerloop' in scope}} } } outerLoop1: repeat { // expected-note {{did you mean 'outerLoop1'?}} {{11-20=outerLoop1}} outerLoop2: repeat { // expected-note {{did you mean 'outerLoop2'?}} {{11-20=outerLoop2}} break outerloop // expected-error {{cannot find label 'outerloop' in scope}} } while true } while true outerLoop1: repeat { // expected-note {{did you mean 'outerLoop1'?}} {{14-23=outerLoop1}} outerLoop2: repeat { // expected-note {{did you mean 'outerLoop2'?}} {{14-23=outerLoop2}} continue outerloop // expected-error {{cannot find label 'outerloop' in scope}} } while true } while true // Errors in case syntax class case, // expected-error {{expected identifier in enum 'case' declaration}} expected-error {{expected identifier after comma in enum 'case' declaration}} expected-error {{enum 'case' is not allowed outside of an enum}} case // expected-error {{expected identifier in enum 'case' declaration}} expected-error {{enum 'case' is not allowed outside of an enum}} // NOTE: EOF is important here to properly test a code path that used to crash the parser
apache-2.0
ba0eabb19a810b4a080eea4708bfc667
30.103734
217
0.641364
3.661348
false
false
false
false
felipecarreramo/BSImagePicker
Pod/Classes/Model/AssetCollectionDataSource.swift
1
3092
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllström // // 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 Photos final class AssetCollectionDataSource : NSObject, SelectableDataSource { fileprivate var assetCollection: PHAssetCollection var selections: [PHObject] = [] var delegate: SelectableDataDelegate? var allowsMultipleSelection: Bool = false var maxNumberOfSelections: Int = 1 var selectedIndexPaths: [IndexPath] { get { if selections.count > 0 { return [IndexPath(item: 0, section: 0)] } else { return [] } } } required init(assetCollection: PHAssetCollection) { self.assetCollection = assetCollection super.init() } // MARK: SelectableDataSource var sections: Int { get { return 1 } } func numberOfObjectsInSection(_ section: Int) -> Int { return 1 } func objectAtIndexPath(_ indexPath: IndexPath) -> PHObject { assert((indexPath as NSIndexPath).section < 1 && (indexPath as NSIndexPath).row < 1, "AssetCollectionDataSource can only contain 1 section and row") return assetCollection } func selectObjectAtIndexPath(_ indexPath: IndexPath) { assert((indexPath as NSIndexPath).section < 1 && (indexPath as NSIndexPath).row < 1, "AssetCollectionDataSource can only contain 1 section and row") selections = [assetCollection] } func deselectObjectAtIndexPath(_ indexPath: IndexPath) { assert((indexPath as NSIndexPath).section < 1 && (indexPath as NSIndexPath).row < 1, "AssetCollectionDataSource can only contain 1 section and row") selections = [] } func isObjectAtIndexPathSelected(_ indexPath: IndexPath) -> Bool { assert((indexPath as NSIndexPath).section < 1 && (indexPath as NSIndexPath).row < 1, "AssetCollectionDataSource can only contain 1 section and row") return selections.count > 0 } }
mit
9f68f58c2362f8ad250b43a707980eee
38.126582
156
0.682951
5.067213
false
false
false
false
indragiek/MarkdownTextView
MarkdownTextView/MarkdownListHighlighter.swift
1
1949
// // MarkdownListHighlighter.swift // MarkdownTextView // // Created by Indragie on 4/29/15. // Copyright (c) 2015 Indragie Karunaratne. All rights reserved. // import UIKit /** * Highlights Markdown lists using specifiable marker patterns. */ public final class MarkdownListHighlighter: HighlighterType { private let regularExpression: NSRegularExpression private let attributes: TextAttributes? private let itemAttributes: TextAttributes? /** Creates a new instance of the receiver. :param: markerPattern Regular expression pattern to use for matching list markers. :param: attributes Attributes to apply to the entire list. :param: itemAttributes Attributes to apply to list items (excluding list markers) :returns: An initialized instance of the receiver. */ public init(markerPattern: String, attributes: TextAttributes?, itemAttributes: TextAttributes?) { self.regularExpression = listItemRegexWithMarkerPattern(markerPattern) self.attributes = attributes self.itemAttributes = itemAttributes } // MARK: HighlighterType public func highlightAttributedString(attributedString: NSMutableAttributedString) { if (attributes == nil && itemAttributes == nil) { return } enumerateMatches(regularExpression, string: attributedString.string) { if let attributes = self.attributes { attributedString.addAttributes(attributes, range: $0.range) } if let itemAttributes = self.itemAttributes { attributedString.addAttributes(itemAttributes, range: $0.rangeAtIndex(1)) } } } } private func listItemRegexWithMarkerPattern(pattern: String) -> NSRegularExpression { // From markdown.pl v1.0.1 <http://daringfireball.net/projects/markdown/> return regexFromPattern("^(?:[ ]{0,3}(?:\(pattern))[ \t]+)(.+)\n") }
mit
c70df6e6040977d5b4d12fd776a86589
34.454545
102
0.689584
4.934177
false
false
false
false
SwiftyJSON/SwiftyJSON
Source/SwiftyJSON/SwiftyJSON.swift
1
40389
// SwiftyJSON.swift // // Copyright (c) 2014 - 2017 Ruoyu Fu, Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: - Error // swiftlint:disable line_length public enum SwiftyJSONError: Int, Swift.Error { case unsupportedType = 999 case indexOutOfBounds = 900 case elementTooDeep = 902 case wrongType = 901 case notExist = 500 case invalidJSON = 490 } extension SwiftyJSONError: CustomNSError { /// return the error domain of SwiftyJSONError public static var errorDomain: String { return "com.swiftyjson.SwiftyJSON" } /// return the error code of SwiftyJSONError public var errorCode: Int { return self.rawValue } /// return the userInfo of SwiftyJSONError public var errorUserInfo: [String: Any] { switch self { case .unsupportedType: return [NSLocalizedDescriptionKey: "It is an unsupported type."] case .indexOutOfBounds: return [NSLocalizedDescriptionKey: "Array Index is out of bounds."] case .wrongType: return [NSLocalizedDescriptionKey: "Couldn't merge, because the JSONs differ in type on top level."] case .notExist: return [NSLocalizedDescriptionKey: "Dictionary key does not exist."] case .invalidJSON: return [NSLocalizedDescriptionKey: "JSON is invalid."] case .elementTooDeep: return [NSLocalizedDescriptionKey: "Element too deep. Increase maxObjectDepth and make sure there is no reference loop."] } } } // MARK: - JSON Type /** JSON's type definitions. See http://www.json.org */ public enum Type: Int { case number case string case bool case array case dictionary case null case unknown } // MARK: - JSON Base public struct JSON { /** Creates a JSON using the data. - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - parameter opt: The JSON serialization reading options. `[]` by default. - returns: The created JSON */ public init(data: Data, options opt: JSONSerialization.ReadingOptions = []) throws { let object: Any = try JSONSerialization.jsonObject(with: data, options: opt) self.init(jsonObject: object) } /** Creates a JSON object - note: this does not parse a `String` into JSON, instead use `init(parseJSON: String)` - parameter object: the object - returns: the created JSON object */ public init(_ object: Any) { switch object { case let object as Data: do { try self.init(data: object) } catch { self.init(jsonObject: NSNull()) } default: self.init(jsonObject: object) } } /** Parses the JSON string into a JSON object - parameter json: the JSON string - returns: the created JSON object */ public init(parseJSON jsonString: String) { if let data = jsonString.data(using: .utf8) { self.init(data) } else { self.init(NSNull()) } } /** Creates a JSON using the object. - parameter jsonObject: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. - returns: The created JSON */ fileprivate init(jsonObject: Any) { object = jsonObject } /** Merges another JSON into this JSON, whereas primitive values which are not present in this JSON are getting added, present values getting overwritten, array values getting appended and nested JSONs getting merged the same way. - parameter other: The JSON which gets merged into this JSON - throws `ErrorWrongType` if the other JSONs differs in type on the top level. */ public mutating func merge(with other: JSON) throws { try self.merge(with: other, typecheck: true) } /** Merges another JSON into this JSON and returns a new JSON, whereas primitive values which are not present in this JSON are getting added, present values getting overwritten, array values getting appended and nested JSONS getting merged the same way. - parameter other: The JSON which gets merged into this JSON - throws `ErrorWrongType` if the other JSONs differs in type on the top level. - returns: New merged JSON */ public func merged(with other: JSON) throws -> JSON { var merged = self try merged.merge(with: other, typecheck: true) return merged } /** Private woker function which does the actual merging Typecheck is set to true for the first recursion level to prevent total override of the source JSON */ fileprivate mutating func merge(with other: JSON, typecheck: Bool) throws { if type == other.type { switch type { case .dictionary: for (key, _) in other { try self[key].merge(with: other[key], typecheck: false) } case .array: self = JSON(arrayValue + other.arrayValue) default: self = other } } else { if typecheck { throw SwiftyJSONError.wrongType } else { self = other } } } /// Private object fileprivate var rawArray: [Any] = [] fileprivate var rawDictionary: [String: Any] = [:] fileprivate var rawString: String = "" fileprivate var rawNumber: NSNumber = 0 fileprivate var rawNull: NSNull = NSNull() fileprivate var rawBool: Bool = false /// JSON type, fileprivate setter public fileprivate(set) var type: Type = .null /// Error in JSON, fileprivate setter public fileprivate(set) var error: SwiftyJSONError? /// Object in JSON public var object: Any { get { switch type { case .array: return rawArray case .dictionary: return rawDictionary case .string: return rawString case .number: return rawNumber case .bool: return rawBool default: return rawNull } } set { error = nil switch unwrap(newValue) { case let number as NSNumber: if number.isBool { type = .bool rawBool = number.boolValue } else { type = .number rawNumber = number } case let string as String: type = .string rawString = string case _ as NSNull: type = .null case Optional<Any>.none: type = .null case let array as [Any]: type = .array rawArray = array case let dictionary as [String: Any]: type = .dictionary rawDictionary = dictionary default: type = .unknown error = SwiftyJSONError.unsupportedType } } } /// The static null JSON @available(*, unavailable, renamed:"null") public static var nullJSON: JSON { return null } public static var null: JSON { return JSON(NSNull()) } } /// Private method to unwarp an object recursively private func unwrap(_ object: Any) -> Any { switch object { case let json as JSON: return unwrap(json.object) case let array as [Any]: return array.map(unwrap) case let dictionary as [String: Any]: var d = dictionary dictionary.forEach { pair in d[pair.key] = unwrap(pair.value) } return d default: return object } } public enum Index<T: Any>: Comparable { case array(Int) case dictionary(DictionaryIndex<String, T>) case null static public func == (lhs: Index, rhs: Index) -> Bool { switch (lhs, rhs) { case (.array(let left), .array(let right)): return left == right case (.dictionary(let left), .dictionary(let right)): return left == right case (.null, .null): return true default: return false } } static public func < (lhs: Index, rhs: Index) -> Bool { switch (lhs, rhs) { case (.array(let left), .array(let right)): return left < right case (.dictionary(let left), .dictionary(let right)): return left < right default: return false } } } public typealias JSONIndex = Index<JSON> public typealias JSONRawIndex = Index<Any> extension JSON: Swift.Collection { public typealias Index = JSONRawIndex public var startIndex: Index { switch type { case .array: return .array(rawArray.startIndex) case .dictionary: return .dictionary(rawDictionary.startIndex) default: return .null } } public var endIndex: Index { switch type { case .array: return .array(rawArray.endIndex) case .dictionary: return .dictionary(rawDictionary.endIndex) default: return .null } } public func index(after i: Index) -> Index { switch i { case .array(let idx): return .array(rawArray.index(after: idx)) case .dictionary(let idx): return .dictionary(rawDictionary.index(after: idx)) default: return .null } } public subscript (position: Index) -> (String, JSON) { switch position { case .array(let idx): return (String(idx), JSON(rawArray[idx])) case .dictionary(let idx): return (rawDictionary[idx].key, JSON(rawDictionary[idx].value)) default: return ("", JSON.null) } } } // MARK: - Subscript /** * To mark both String and Int can be used in subscript. */ public enum JSONKey { case index(Int) case key(String) } public protocol JSONSubscriptType { var jsonKey: JSONKey { get } } extension Int: JSONSubscriptType { public var jsonKey: JSONKey { return JSONKey.index(self) } } extension String: JSONSubscriptType { public var jsonKey: JSONKey { return JSONKey.key(self) } } extension JSON { /// If `type` is `.array`, return json whose object is `array[index]`, otherwise return null json with error. fileprivate subscript(index index: Int) -> JSON { get { if type != .array { var r = JSON.null r.error = self.error ?? SwiftyJSONError.wrongType return r } else if rawArray.indices.contains(index) { return JSON(rawArray[index]) } else { var r = JSON.null r.error = SwiftyJSONError.indexOutOfBounds return r } } set { if type == .array && rawArray.indices.contains(index) && newValue.error == nil { rawArray[index] = newValue.object } } } /// If `type` is `.dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error. fileprivate subscript(key key: String) -> JSON { get { var r = JSON.null if type == .dictionary { if let o = rawDictionary[key] { r = JSON(o) } else { r.error = SwiftyJSONError.notExist } } else { r.error = self.error ?? SwiftyJSONError.wrongType } return r } set { if type == .dictionary && newValue.error == nil { rawDictionary[key] = newValue.object } } } /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. fileprivate subscript(sub sub: JSONSubscriptType) -> JSON { get { switch sub.jsonKey { case .index(let index): return self[index: index] case .key(let key): return self[key: key] } } set { switch sub.jsonKey { case .index(let index): self[index: index] = newValue case .key(let key): self[key: key] = newValue } } } /** Find a json in the complex data structures by using array of Int and/or String as path. Example: ``` let json = JSON[data] let path = [9,"list","person","name"] let name = json[path] ``` The same as: let name = json[9]["list"]["person"]["name"] - parameter path: The target json's path. - returns: Return a json found by the path or a null json with error */ public subscript(path: [JSONSubscriptType]) -> JSON { get { return path.reduce(self) { $0[sub: $1] } } set { switch path.count { case 0: return case 1: self[sub:path[0]].object = newValue.object default: var aPath = path aPath.remove(at: 0) var nextJSON = self[sub: path[0]] nextJSON[aPath] = newValue self[sub: path[0]] = nextJSON } } } /** Find a json in the complex data structures by using array of Int and/or String as path. - parameter path: The target json's path. Example: let name = json[9,"list","person","name"] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: JSONSubscriptType...) -> JSON { get { return self[path] } set { self[path] = newValue } } } // MARK: - LiteralConvertible extension JSON: Swift.ExpressibleByStringLiteral { public init(stringLiteral value: StringLiteralType) { self.init(value) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value) } } extension JSON: Swift.ExpressibleByIntegerLiteral { public init(integerLiteral value: IntegerLiteralType) { self.init(value) } } extension JSON: Swift.ExpressibleByBooleanLiteral { public init(booleanLiteral value: BooleanLiteralType) { self.init(value) } } extension JSON: Swift.ExpressibleByFloatLiteral { public init(floatLiteral value: FloatLiteralType) { self.init(value) } } extension JSON: Swift.ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (String, Any)...) { let dictionary = elements.reduce(into: [String: Any](), { $0[$1.0] = $1.1}) self.init(dictionary) } } extension JSON: Swift.ExpressibleByArrayLiteral { public init(arrayLiteral elements: Any...) { self.init(elements) } } // MARK: - Raw extension JSON: Swift.RawRepresentable { public init?(rawValue: Any) { if JSON(rawValue).type == .unknown { return nil } else { self.init(rawValue) } } public var rawValue: Any { return object } public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data { guard JSONSerialization.isValidJSONObject(object) else { throw SwiftyJSONError.invalidJSON } return try JSONSerialization.data(withJSONObject: object, options: opt) } public func rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { do { return try _rawString(encoding, options: [.jsonSerialization: opt]) } catch { print("Could not serialize object to JSON because:", error.localizedDescription) return nil } } public func rawString(_ options: [writingOptionsKeys: Any]) -> String? { let encoding = options[.encoding] as? String.Encoding ?? String.Encoding.utf8 let maxObjectDepth = options[.maxObjextDepth] as? Int ?? 10 do { return try _rawString(encoding, options: options, maxObjectDepth: maxObjectDepth) } catch { print("Could not serialize object to JSON because:", error.localizedDescription) return nil } } fileprivate func _rawString(_ encoding: String.Encoding = .utf8, options: [writingOptionsKeys: Any], maxObjectDepth: Int = 10) throws -> String? { guard maxObjectDepth > 0 else { throw SwiftyJSONError.invalidJSON } switch type { case .dictionary: do { if !(options[.castNilToNSNull] as? Bool ?? false) { let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted let data = try rawData(options: jsonOption) return String(data: data, encoding: encoding) } guard let dict = object as? [String: Any?] else { return nil } let body = try dict.keys.map { key throws -> String in guard let value = dict[key] else { return "\"\(key)\": null" } guard let unwrappedValue = value else { return "\"\(key)\": null" } let nestedValue = JSON(unwrappedValue) guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { throw SwiftyJSONError.elementTooDeep } if nestedValue.type == .string { return "\"\(key)\": \"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" } else { return "\"\(key)\": \(nestedString)" } } return "{\(body.joined(separator: ","))}" } catch _ { return nil } case .array: do { if !(options[.castNilToNSNull] as? Bool ?? false) { let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted let data = try rawData(options: jsonOption) return String(data: data, encoding: encoding) } guard let array = object as? [Any?] else { return nil } let body = try array.map { value throws -> String in guard let unwrappedValue = value else { return "null" } let nestedValue = JSON(unwrappedValue) guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { throw SwiftyJSONError.invalidJSON } if nestedValue.type == .string { return "\"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" } else { return nestedString } } return "[\(body.joined(separator: ","))]" } catch _ { return nil } case .string: return rawString case .number: return rawNumber.stringValue case .bool: return rawBool.description case .null: return "null" default: return nil } } } // MARK: - Printable, DebugPrintable extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible { public var description: String { return rawString(options: .prettyPrinted) ?? "unknown" } public var debugDescription: String { return description } } // MARK: - Array extension JSON { //Optional [JSON] public var array: [JSON]? { return type == .array ? rawArray.map { JSON($0) } : nil } //Non-optional [JSON] public var arrayValue: [JSON] { return self.array ?? [] } //Optional [Any] public var arrayObject: [Any]? { get { switch type { case .array: return rawArray default: return nil } } set { self.object = newValue ?? NSNull() } } } // MARK: - Dictionary extension JSON { //Optional [String : JSON] public var dictionary: [String: JSON]? { if type == .dictionary { var d = [String: JSON](minimumCapacity: rawDictionary.count) rawDictionary.forEach { pair in d[pair.key] = JSON(pair.value) } return d } else { return nil } } //Non-optional [String : JSON] public var dictionaryValue: [String: JSON] { return dictionary ?? [:] } //Optional [String : Any] public var dictionaryObject: [String: Any]? { get { switch type { case .dictionary: return rawDictionary default: return nil } } set { object = newValue ?? NSNull() } } } // MARK: - Bool extension JSON { // : Swift.Bool //Optional bool public var bool: Bool? { get { switch type { case .bool: return rawBool default: return nil } } set { object = newValue ?? NSNull() } } //Non-optional bool public var boolValue: Bool { get { switch type { case .bool: return rawBool case .number: return rawNumber.boolValue case .string: return ["true", "y", "t", "yes", "1"].contains { rawString.caseInsensitiveCompare($0) == .orderedSame } default: return false } } set { object = newValue } } } // MARK: - String extension JSON { //Optional string public var string: String? { get { switch type { case .string: return object as? String default: return nil } } set { object = newValue ?? NSNull() } } //Non-optional string public var stringValue: String { get { switch type { case .string: return object as? String ?? "" case .number: return rawNumber.stringValue case .bool: return (object as? Bool).map { String($0) } ?? "" default: return "" } } set { object = newValue } } } // MARK: - Number extension JSON { //Optional number public var number: NSNumber? { get { switch type { case .number: return rawNumber case .bool: return NSNumber(value: rawBool ? 1 : 0) default: return nil } } set { object = newValue ?? NSNull() } } //Non-optional number public var numberValue: NSNumber { get { switch type { case .string: let decimal = NSDecimalNumber(string: object as? String) return decimal == .notANumber ? .zero : decimal case .number: return object as? NSNumber ?? NSNumber(value: 0) case .bool: return NSNumber(value: rawBool ? 1 : 0) default: return NSNumber(value: 0.0) } } set { object = newValue } } } // MARK: - Null extension JSON { public var null: NSNull? { set { object = NSNull() } get { switch type { case .null: return rawNull default: return nil } } } public func exists() -> Bool { if let errorValue = error, (400...1000).contains(errorValue.errorCode) { return false } return true } } // MARK: - URL extension JSON { //Optional URL public var url: URL? { get { switch type { case .string: // Check for existing percent escapes first to prevent double-escaping of % character if rawString.range(of: "%[0-9A-Fa-f]{2}", options: .regularExpression, range: nil, locale: nil) != nil { return Foundation.URL(string: rawString) } else if let encodedString_ = rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) { // We have to use `Foundation.URL` otherwise it conflicts with the variable name. return Foundation.URL(string: encodedString_) } else { return nil } default: return nil } } set { object = newValue?.absoluteString ?? NSNull() } } } // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 extension JSON { public var double: Double? { get { return number?.doubleValue } set { if let newValue = newValue { object = NSNumber(value: newValue) } else { object = NSNull() } } } public var doubleValue: Double { get { return numberValue.doubleValue } set { object = NSNumber(value: newValue) } } public var float: Float? { get { return number?.floatValue } set { if let newValue = newValue { object = NSNumber(value: newValue) } else { object = NSNull() } } } public var floatValue: Float { get { return numberValue.floatValue } set { object = NSNumber(value: newValue) } } public var int: Int? { get { return number?.intValue } set { if let newValue = newValue { object = NSNumber(value: newValue) } else { object = NSNull() } } } public var intValue: Int { get { return numberValue.intValue } set { object = NSNumber(value: newValue) } } public var uInt: UInt? { get { return number?.uintValue } set { if let newValue = newValue { object = NSNumber(value: newValue) } else { object = NSNull() } } } public var uIntValue: UInt { get { return numberValue.uintValue } set { object = NSNumber(value: newValue) } } public var int8: Int8? { get { return number?.int8Value } set { if let newValue = newValue { object = NSNumber(value: Int(newValue)) } else { object = NSNull() } } } public var int8Value: Int8 { get { return numberValue.int8Value } set { object = NSNumber(value: Int(newValue)) } } public var uInt8: UInt8? { get { return number?.uint8Value } set { if let newValue = newValue { object = NSNumber(value: newValue) } else { object = NSNull() } } } public var uInt8Value: UInt8 { get { return numberValue.uint8Value } set { object = NSNumber(value: newValue) } } public var int16: Int16? { get { return number?.int16Value } set { if let newValue = newValue { object = NSNumber(value: newValue) } else { object = NSNull() } } } public var int16Value: Int16 { get { return numberValue.int16Value } set { object = NSNumber(value: newValue) } } public var uInt16: UInt16? { get { return number?.uint16Value } set { if let newValue = newValue { object = NSNumber(value: newValue) } else { object = NSNull() } } } public var uInt16Value: UInt16 { get { return numberValue.uint16Value } set { object = NSNumber(value: newValue) } } public var int32: Int32? { get { return number?.int32Value } set { if let newValue = newValue { object = NSNumber(value: newValue) } else { object = NSNull() } } } public var int32Value: Int32 { get { return numberValue.int32Value } set { object = NSNumber(value: newValue) } } public var uInt32: UInt32? { get { return number?.uint32Value } set { if let newValue = newValue { object = NSNumber(value: newValue) } else { object = NSNull() } } } public var uInt32Value: UInt32 { get { return numberValue.uint32Value } set { object = NSNumber(value: newValue) } } public var int64: Int64? { get { return number?.int64Value } set { if let newValue = newValue { object = NSNumber(value: newValue) } else { object = NSNull() } } } public var int64Value: Int64 { get { return numberValue.int64Value } set { object = NSNumber(value: newValue) } } public var uInt64: UInt64? { get { return number?.uint64Value } set { if let newValue = newValue { object = NSNumber(value: newValue) } else { object = NSNull() } } } public var uInt64Value: UInt64 { get { return numberValue.uint64Value } set { object = NSNumber(value: newValue) } } } // MARK: - Comparable extension JSON: Swift.Comparable {} public func == (lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber == rhs.rawNumber case (.string, .string): return lhs.rawString == rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.null, .null): return true default: return false } } public func <= (lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber <= rhs.rawNumber case (.string, .string): return lhs.rawString <= rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.null, .null): return true default: return false } } public func >= (lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber >= rhs.rawNumber case (.string, .string): return lhs.rawString >= rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.null, .null): return true default: return false } } public func > (lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber > rhs.rawNumber case (.string, .string): return lhs.rawString > rhs.rawString default: return false } } public func < (lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber < rhs.rawNumber case (.string, .string): return lhs.rawString < rhs.rawString default: return false } } private let trueNumber = NSNumber(value: true) private let falseNumber = NSNumber(value: false) private let trueObjCType = String(cString: trueNumber.objCType) private let falseObjCType = String(cString: falseNumber.objCType) // MARK: - NSNumber: Comparable extension NSNumber { fileprivate var isBool: Bool { let objCType = String(cString: self.objCType) if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType) { return true } else { return false } } } func == (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == .orderedSame } } func != (lhs: NSNumber, rhs: NSNumber) -> Bool { return !(lhs == rhs) } func < (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == .orderedAscending } } func > (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == ComparisonResult.orderedDescending } } func <= (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != .orderedDescending } } func >= (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != .orderedAscending } } public enum writingOptionsKeys { case jsonSerialization case castNilToNSNull case maxObjextDepth case encoding } // MARK: - JSON: Codable extension JSON: Codable { private static var codableTypes: [Codable.Type] { return [ Bool.self, Int.self, Int8.self, Int16.self, Int32.self, Int64.self, UInt.self, UInt8.self, UInt16.self, UInt32.self, UInt64.self, Double.self, String.self, [JSON].self, [String: JSON].self ] } public init(from decoder: Decoder) throws { var object: Any? if let container = try? decoder.singleValueContainer(), !container.decodeNil() { for type in JSON.codableTypes { if object != nil { break } // try to decode value switch type { case let boolType as Bool.Type: object = try? container.decode(boolType) case let intType as Int.Type: object = try? container.decode(intType) case let int8Type as Int8.Type: object = try? container.decode(int8Type) case let int32Type as Int32.Type: object = try? container.decode(int32Type) case let int64Type as Int64.Type: object = try? container.decode(int64Type) case let uintType as UInt.Type: object = try? container.decode(uintType) case let uint8Type as UInt8.Type: object = try? container.decode(uint8Type) case let uint16Type as UInt16.Type: object = try? container.decode(uint16Type) case let uint32Type as UInt32.Type: object = try? container.decode(uint32Type) case let uint64Type as UInt64.Type: object = try? container.decode(uint64Type) case let doubleType as Double.Type: object = try? container.decode(doubleType) case let stringType as String.Type: object = try? container.decode(stringType) case let jsonValueArrayType as [JSON].Type: object = try? container.decode(jsonValueArrayType) case let jsonValueDictType as [String: JSON].Type: object = try? container.decode(jsonValueDictType) default: break } } } self.init(object ?? NSNull()) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() if object is NSNull { try container.encodeNil() return } switch object { case let intValue as Int: try container.encode(intValue) case let int8Value as Int8: try container.encode(int8Value) case let int32Value as Int32: try container.encode(int32Value) case let int64Value as Int64: try container.encode(int64Value) case let uintValue as UInt: try container.encode(uintValue) case let uint8Value as UInt8: try container.encode(uint8Value) case let uint16Value as UInt16: try container.encode(uint16Value) case let uint32Value as UInt32: try container.encode(uint32Value) case let uint64Value as UInt64: try container.encode(uint64Value) case let doubleValue as Double: try container.encode(doubleValue) case let boolValue as Bool: try container.encode(boolValue) case let stringValue as String: try container.encode(stringValue) case is [Any]: let jsonValueArray = array ?? [] try container.encode(jsonValueArray) case is [String: Any]: let jsonValueDictValue = dictionary ?? [:] try container.encode(jsonValueDictValue) default: break } } }
mit
b21e2965363c309152da3ab40256dc1c
27.828694
266
0.554483
4.652575
false
false
false
false
czerenkow/LublinWeather
App/Settings List/SettingsListRouter.swift
1
2054
// // SettingsListRouter.swift // LublinWeather // // Created by Damian Rzeszot on 30/04/2018. // Copyright © 2018 Damian Rzeszot. All rights reserved. // import UIKit final class SettingsListRouter: Router { struct Builders { var info: InfoBuilder? var languages: SettingsLanguageBuilder? var version: SettingsVersionBuilder? } var builders = Builders() // MARK: - private var xxx: NavigationDelegate! override func load() { super.load() xxx = NavigationDelegate(router: self) nav?.delegate = xxx } // MARK: - func info() { push(builders.info!.build()) } func languages() { push(builders.languages!.build()) } func version() { push(builders.version!.build()) } func close() { controller!.dismiss(animated: true) { self.parent!.deattach(child: self) } } // MARK: - private func push(_ child: Router) { attach(child: child) nav?.pushViewController(child.controller!, animated: true) } private var nav: UINavigationController? { return controller?.navigationController } } final class NavigationDelegate: NSObject, UINavigationControllerDelegate { unowned let router: Router init(router: Router) { self.router = router } func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { let vcs = navigationController.viewControllers let routers = collect(router) for (index, router) in routers.enumerated() { if vcs[safe: index] == nil { self.router.deattach(child: router) } } } private func collect(_ router: Router) -> [Router] { var result: [Router] = [] var ptr: Router? = router while ptr != nil { result.append(ptr!) ptr = ptr?.children.first } return result } }
mit
f539bdc3d2bfd14d641e02b32626f7c2
19.127451
137
0.594252
4.542035
false
false
false
false
benlangmuir/swift
test/Generics/rdar95075552.swift
5
1297
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures 2>&1 | %FileCheck %s // CHECK-LABEL: .Tree@ // CHECK-NEXT: Requirement signature: <Self where Self.[Tree]Distance : FloatingPoint, Self.[Tree]Distance : SIMDScalar, Self.[Tree]Distance == Self.[Tree]Point.[SIMDStorage]Scalar, Self.[Tree]Point : SIMD> protocol Tree { associatedtype Distance: FloatingPoint & SIMDScalar associatedtype Point: SIMD where Point.Scalar == Distance } // CHECK-LABEL: .QuadTree@ // CHECK-NEXT: Requirement signature: <Self where Self : Tree, Self.[Tree]Point == SIMD2<Self.[Tree]Distance>> protocol QuadTree : Tree where Point == SIMD2<Distance> {} // CHECK-LABEL: .OctTree@ // CHECK-NEXT: Requirement signature: <Self where Self : Tree, Self.[Tree]Point == SIMD3<Self.[Tree]Distance>> protocol OctTree : Tree where Point == SIMD3<Distance> {} func sameType<T>(_: T.Type, _: T.Type) {} extension QuadTree { func foo() { sameType(Point.MaskStorage.self, SIMD2<Distance.SIMDMaskScalar>.self) sameType(Point.MaskStorage.MaskStorage.self, SIMD2<Distance.SIMDMaskScalar>.self) } } extension OctTree { func foo() { sameType(Point.MaskStorage.self, SIMD3<Distance.SIMDMaskScalar>.self) sameType(Point.MaskStorage.MaskStorage.self, SIMD3<Distance.SIMDMaskScalar>.self) } }
apache-2.0
3297c1b290e99203c3decdc229347fc8
39.53125
206
0.730918
3.582873
false
false
false
false
astralbodies/CleanRooms
CleanRooms/Services/RoomServiceRemote.swift
1
2461
/* * Copyright (c) 2015 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import Foundation public class RoomServiceRemote { private var urlSession: NSURLSession! public init() { urlSession = NSURLSession.sharedSession() } public init(urlSession: NSURLSession) { self.urlSession = urlSession } public func fetchAllRooms(completion: ([RemoteRoom]) -> Void) { let url = NSURL(string: "http://localhost:5984/rooms/_all_docs?include_docs=true")! let urlRequest = NSMutableURLRequest(URL: url, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10.0 * 1000) urlRequest.HTTPMethod = "GET" urlRequest.addValue("application/json", forHTTPHeaderField: "Accept") let task = urlSession.dataTaskWithRequest(urlRequest) { data, response, error in guard error == nil else { print("Error while fetching remote rooms: \(error)") completion([RemoteRoom]()) return } var json = try? NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String: AnyObject] guard json != nil else { print("Nil data received from fetchAllRooms") completion([RemoteRoom]()) return } let rows = json!["rows"] as! [[String: AnyObject]] var rooms = [RemoteRoom]() for roomDict in rows { rooms.append(RemoteRoom(jsonData: roomDict)) } completion(rooms) } task.resume() } }
mit
1389bb039f86ef7fd7bdd6068eeaf680
34.666667
133
0.712718
4.591418
false
false
false
false
slavapestov/swift
test/Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift
1
1981
@_exported import ObjectiveC // Clang module // The iOS/arm64 target uses _Bool for Objective C's BOOL. We include // x86_64 here as well because the iOS simulator also uses _Bool. #if ((os(iOS) || os(tvOS)) && (arch(arm64) || arch(x86_64))) || os(watchOS) public struct ObjCBool : BooleanType { private var value : Bool public init(_ value: Bool) { self.value = value } /// \brief Allow use in a Boolean context. public var boolValue: Bool { return value } } #else public struct ObjCBool : BooleanType { private var value : UInt8 public init(_ value: Bool) { self.value = value ? 1 : 0 } public init(_ value: UInt8) { self.value = value } /// \brief Allow use in a Boolean context. public var boolValue: Bool { if value == 0 { return false } return true } } #endif extension ObjCBool : BooleanLiteralConvertible { public init(booleanLiteral: Bool) { self.init(booleanLiteral) } } public struct Selector : StringLiteralConvertible { private var ptr : COpaquePointer public init(_ value: String) { self.init(stringLiteral: value) } public init(unicodeScalarLiteral value: String) { self.init(stringLiteral: value) } public init(extendedGraphemeClusterLiteral value: String) { self.init(stringLiteral: value) } public init (stringLiteral value: String) { self = sel_registerName(value) } } public struct NSZone: NilLiteralConvertible { public var pointer : COpaquePointer @_transparent public init(nilLiteral: ()) { pointer = COpaquePointer() } } internal func _convertBoolToObjCBool(x: Bool) -> ObjCBool { return ObjCBool(x) } internal func _convertObjCBoolToBool(x: ObjCBool) -> Bool { return Bool(x) } public func ~=(x: NSObject, y: NSObject) -> Bool { return true } extension NSObject : Equatable, Hashable { public var hashValue: Int { return hash } } public func == (lhs: NSObject, rhs: NSObject) -> Bool { return lhs.isEqual(rhs) }
apache-2.0
ac5f6a09c0d6053f024f3e176b8a21d5
19.852632
75
0.67895
3.899606
false
false
false
false
xwu/swift
test/IDE/complete_value_literals.swift
5
7265
// RUN: %empty-directory(%t) // RUN: %target-swift-ide-test -batch-code-completion -source-filename %s -filecheck %raw-FileCheck -completion-output-dir %t func testAll0() { // Not type context. let x = #^NO_CONTEXT_0^# // NO_CONTEXT_0-DAG: Begin completions // NO_CONTEXT_0-DAG: Literal[Integer]/None: 0[#Int#]; // NO_CONTEXT_0-DAG: Literal[Boolean]/None: true[#Bool#]; // NO_CONTEXT_0-DAG: Literal[Boolean]/None: false[#Bool#]; // NO_CONTEXT_0-DAG: Literal[Nil]/None: nil; // NO_CONTEXT_0-DAG: Literal[String]/None: "{#(abc)#}"[#String#]; // NO_CONTEXT_0-DAG: Literal[Array]/None: [{#(values)#}][#Array#]; // NO_CONTEXT_0-DAG: Literal[Dictionary]/None: [{#(key)#}: {#(value)#}][#Dictionary#]; // NO_CONTEXT_0-DAG: Literal[_Color]/None: #colorLiteral({#red: Float#}, {#green: Float#}, {#blue: Float#}, {#alpha: Float#}); // NO_CONTEXT_0-DAG: Literal[_Image]/None: #imageLiteral({#resourceName: String#}); // NO_CONTEXT_0: End completions } struct MyNil1: ExpressibleByNilLiteral { init(nilLiteral: ()) {} } struct MyBool1: ExpressibleByBooleanLiteral { init(booleanLiteral value: Bool) {} } struct MyInt1: ExpressibleByIntegerLiteral { init(integerLiteral value: Int) {} } struct MyDouble1: ExpressibleByFloatLiteral { init(floatLiteral value: Double) {} } struct MyString1: ExpressibleByStringLiteral { init(unicodeScalarLiteral value: Character) {} init(extendedGraphemeClusterLiteral value: String) {} init(stringLiteral value: String) {} } struct MyUnicodeScalar1: ExpressibleByUnicodeScalarLiteral { init(unicodeScalarLiteral value: Character) {} } struct MyCharacter1: ExpressibleByExtendedGraphemeClusterLiteral { init(unicodeScalarLiteral value: Character) {} init(extendedGraphemeClusterLiteral value: String) {} } struct MyArray1<Element>: ExpressibleByArrayLiteral { init(arrayLiteral value: Element...) {} } struct MyDict1<Key, Value>: ExpressibleByDictionaryLiteral { init(dictionaryLiteral elements: (Key, Value)...) {} } extension MyInt1: Equatable, Hashable { var hashValue: Int { return 1 } } func ==(_: MyInt1, _: MyInt1) -> Bool { return true } func testNil0() { let x: Int = #^NIL_0^# } // NIL_0: Literal[Nil]/None: nil; func testNil1() { let x: MyNil1 = #^NIL_1^# } // NIL_1: Literal[Nil]/None/TypeRelation[Identical]: nil[#MyNil1#]; func testNil2() { let x: Int? = #^NIL_2^# } // NIL_2: Literal[Nil]/None/TypeRelation[Identical]: nil[#Int?#]; func testBool0() { let x: Int = #^BOOL_0^# } // BOOL_0: Literal[Boolean]/None: true[#Bool#]; // BOOL_0: Literal[Boolean]/None: false[#Bool#]; func testBool1() { let x: MyBool1 = #^BOOL_1^# } // BOOL_1: Literal[Boolean]/None/TypeRelation[Identical]: true[#MyBool1#]; // BOOL_1: Literal[Boolean]/None/TypeRelation[Identical]: false[#MyBool1#]; func testBool2() { let x: Bool = #^BOOL_2^# } // BOOL_2: Literal[Boolean]/None/TypeRelation[Identical]: true[#Bool#]; // BOOL_2: Literal[Boolean]/None/TypeRelation[Identical]: false[#Bool#]; func testBool3() { let x: Bool? = #^BOOL_3^# } // BOOL_3: Literal[Boolean]/None/TypeRelation[Convertible]: true[#Bool#]; // BOOL_3: Literal[Boolean]/None/TypeRelation[Convertible]: false[#Bool#]; func testBool4() { let x: Bool! = #^BOOL_4^# } // BOOL_4: Literal[Boolean]/None/TypeRelation[Convertible]: true[#Bool#]; // BOOL_4: Literal[Boolean]/None/TypeRelation[Convertible]: false[#Bool#]; func testInt0() { let x: Bool = #^INT_0^# } // INT_0: Literal[Integer]/None: 0[#Int#]; func testInt1() { let x: MyInt1 = #^INT_1^# } // INT_1: Literal[Integer]/None/TypeRelation[Identical]: 0[#MyInt1#]; func testInt2() { let x: Int = #^INT_2^# } // INT_2: Literal[Integer]/None/TypeRelation[Identical]: 0[#Int#]; func testDouble0() { let x: Double = #^DOUBLE_0^# } // DOUBLE_0: Literal[Integer]/None/TypeRelation[Identical]: 0[#Double#]; func testString0() { let x: Int = #^STRING_0^# } // STRING_0: Literal[String]/None: "{#(abc)#}"[#String#]; func testString1() { let x: MyString1 = #^STRING_1^# } // STRING_1: Literal[String]/None/TypeRelation[Identical]: "{#(abc)#}"[#MyString1#]; func testString2() { let x: String = #^STRING_2^# } // STRING_2: Literal[String]/None/TypeRelation[Identical]: "{#(abc)#}"[#String#]; func testString3() { let x: MyUnicodeScalar1 = #^STRING_3^# } // STRING_3: Literal[String]/None/TypeRelation[Identical]: "{#(abc)#}"[#MyUnicodeScalar1#]; func testString4() { let x: MyCharacter1 = #^STRING_4^# } // STRING_4: Literal[String]/None/TypeRelation[Identical]: "{#(abc)#}"[#MyCharacter1#]; func testString5() { let x: Character = #^STRING_5^# } // STRING_5: Literal[String]/None/TypeRelation[Identical]: "{#(abc)#}"[#Character#]; func testArray0() { let x: Int = #^ARRAY_0^# } // ARRAY_0: Literal[Array]/None: [{#(values)#}][#Array#]; func testArray1() { let x: MyArray1<MyInt1> = #^ARRAY_1^# } // ARRAY_1: Literal[Array]/None/TypeRelation[Identical]: [{#(values)#}][#MyArray1<MyInt1>#]; func testArray2() { let x: [MyInt1] = #^ARRAY_2^# } // ARRAY_2: Literal[Array]/None/TypeRelation[Identical]: [{#(values)#}][#[MyInt1]#]; func testDict0() { let x: Int = #^DICT_0^# } // DICT_0: Literal[Dictionary]/None: [{#(key)#}: {#(value)#}][#Dictionary#]; func testDict1() { let x: MyDict1<MyInt1, MyString1> = #^DICT_1^# } // DICT_1: Literal[Dictionary]/None/TypeRelation[Identical]: [{#(key)#}: {#(value)#}][#MyDict1<MyInt1, MyString1>#]; func testDict2() { let x: [MyInt1: MyString1] = #^DICT_2^# } // DICT_2: Literal[Dictionary]/None/TypeRelation[Identical]: [{#(key)#}: {#(value)#}][#[MyInt1 : MyString1]#]; func testTuple0() { let x: Int = #^TUPLE_0^# } // TUPLE_0: Literal[Tuple]/None: ({#(values)#}); func testTuple1() { let x: (MyInt1, MyString1) = #^TUPLE_1^# } // TUPLE_1: Literal[Tuple]/None/TypeRelation[Identical]: ({#(values)#})[#(MyInt1, MyString1)#]; func testTuple2() { let x: (MyInt1, MyString1, MyDouble1) = #^TUPLE_2^# } // FIXME: should we extend the tuple to have the right number of elements? // TUPLE_2: Literal[Tuple]/None/TypeRelation[Identical]: ({#(values)#})[#(MyInt1, MyString1, MyDouble1)#]; struct MyColor1: _ExpressibleByColorLiteral { init(_colorLiteralRed: Float, green: Float, blue: Float, alpha: Float) {} } func testColor0() { let x: Int = #^COLOR_0^# } // COLOR_0: Literal[_Color]/None: #colorLiteral({#red: Float#}, {#green: Float#}, {#blue: Float#}, {#alpha: Float#}); func testColor1() { let x: MyColor1 = #^COLOR_1^# } // COLOR_1: Literal[_Color]/None/TypeRelation[Identical]: #colorLiteral({#red: Float#}, {#green: Float#}, {#blue: Float#}, {#alpha: Float#})[#MyColor1#]; func testColor2() { let x: MyColor1? = #^COLOR_2^# } // COLOR_2: Literal[_Color]/None/TypeRelation[Convertible]: #colorLiteral({#red: Float#}, {#green: Float#}, {#blue: Float#}, {#alpha: Float#})[#MyColor1#]; struct MyImage1: _ExpressibleByImageLiteral { init(imageLiteralResourceName: String) {} } func testImage0() { let x: Int = #^IMAGE_0^# } // IMAGE_0: Literal[_Image]/None: #imageLiteral({#resourceName: String#}); func testImage1() { let x: MyImage1 = #^IMAGE_1^# } // IMAGE_1: Literal[_Image]/None/TypeRelation[Identical]: #imageLiteral({#resourceName: String#})[#MyImage1#];
apache-2.0
4ab87527de417ae690fcac2f4ae52ec6
31.433036
155
0.651617
3.291799
false
true
false
false
lzpfmh/actor-platform
actor-apps/app-ios/ActorApp/Controllers/Dialogs/DialogsViewController.swift
1
3635
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import UIKit class DialogsViewController: RecentContentViewController, RecentContentViewControllerDelegate { override init() { super.init() // Enabling dialogs page tracking content = ACAllEvents_Main.RECENT() // Setting delegate self.delegate = self } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() // Setting UITabBarItem tabBarItem = UITabBarItem( title: localized("TabMessages"), image: UIImage(named: "TabIconChats")?.styled("tab.icon"), selectedImage: UIImage(named: "TabIconChatsHighlighted")?.styled("tab.icon.selected")) binder.bind(Actor.getAppState().globalCounter, closure: { (value: JavaLangInteger?) -> () in if value != nil { if value!.integerValue > 0 { self.tabBarItem.badgeValue = "\(value!.integerValue)" } else { self.tabBarItem.badgeValue = nil } } else { self.tabBarItem.badgeValue = nil } }) // Setting navigation item navigationItem.title = localized("TabMessages") navigationItem.leftBarButtonItem = editButtonItem() navigationItem.leftBarButtonItem!.title = localized("NavigationEdit") navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: self, action: "compose") } // Implemention of editing override func setEditing(editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) tableView.setEditing(editing, animated: animated) if (editing) { self.navigationItem.leftBarButtonItem!.title = localized("NavigationDone") self.navigationItem.leftBarButtonItem!.style = UIBarButtonItemStyle.Done navigationItem.rightBarButtonItem = nil } else { self.navigationItem.leftBarButtonItem!.title = localized("NavigationEdit") self.navigationItem.leftBarButtonItem!.style = UIBarButtonItemStyle.Plain navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: self, action: "compose") } if editing == true { navigationItem.rightBarButtonItem = nil } else { navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: self, action: "compose") } } func compose() { navigateNext(ComposeController()) } // Tracking app state override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) Actor.onDialogsOpen() } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) Actor.onDialogsClosed() } // Handling selections func recentsDidTap(controller: RecentContentViewController, dialog: ACDialog) -> Bool { navigateDetail(ConversationViewController(peer: dialog.peer)) return false } func searchDidTap(controller: RecentContentViewController, entity: ACSearchEntity) { navigateDetail(ConversationViewController(peer: entity.peer)) } }
mit
4355516a3d8f1737954f42f472b495ba
32.657407
148
0.620908
5.816
false
false
false
false
kstaring/swift
test/IRGen/select_enum_optimized.swift
4
2623
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -O -disable-llvm-optzns -emit-ir | %FileCheck %s enum NoPayload { case E0 case E1 case E2 case E3 } // Check if the code of a select_num is a simple int cast and not a switch. // CHECK-LABEL: define {{.*}}selectDirect // CHECK: %1 = zext i8 %0 to i32 // CHECK: ret i32 %1 @inline(never) func selectDirect(e: NoPayload) -> Int32 { switch e { case .E0: return 0 case .E1: return 1 case .E2: return 2 case .E3: return 3 } } // CHECK-LABEL: define {{.*}}selectNegOffset // CHECK: %1 = zext i8 %0 to i32 // CHECK: %2 = add i32 %1, -6 // CHECK: ret i32 %2 @inline(never) func selectNegOffset(e: NoPayload) -> Int32 { switch e { case .E0: return -6 case .E1: return -5 case .E2: return -4 case .E3: return -3 } } // CHECK-LABEL: define {{.*}}selectPosOffset // CHECK: %1 = zext i8 %0 to i32 // CHECK: %2 = add i32 %1, 3 // CHECK: ret i32 %2 @inline(never) func selectPosOffset(e: NoPayload) -> Int32 { switch e { case .E0: return 3 case .E1: return 4 case .E2: return 5 case .E3: return 6 } } // Following functions contain select_enums, which cannot be generated as a // simple conversion. // CHECK-LABEL: define {{.*}}selectWithDefault // CHECK: switch i8 // CHECK: ret @inline(never) func selectWithDefault(e: NoPayload) -> Int32 { switch e { case .E0: return 0 case .E1: return 1 default: return 2 } } // CHECK-LABEL: define {{.*}}selectNonContiguous // CHECK: switch i8 // CHECK: ret @inline(never) func selectNonContiguous(e: NoPayload) -> Int32 { switch e { case .E0: return 0 case .E1: return 1 case .E2: return 3 case .E3: return 4 } } var gg : Int32 = 10 // CHECK-LABEL: define {{.*}}selectNonConstant // CHECK: switch i8 // CHECK: ret @inline(never) func selectNonConstant(e: NoPayload) -> Int32 { switch e { case .E0: return 0 case .E1: return 1 case .E2: return gg case .E3: return 4 } } // CHECK-LABEL: define {{.*}}selectTuple // CHECK: switch i8 // CHECK: ret @inline(never) func selectTuple(e: NoPayload) -> (Int32, Int32) { switch e { case .E0: return (0, 1) case .E1: return (1, 2) case .E2: return (2, 3) case .E3: return (3, 4) } } // CHECK-LABEL: define {{.*}}selectNonInt // CHECK: switch i8 // CHECK: ret @inline(never) func selectNonInt(e: NoPayload) -> String { switch e { case .E0: return "a" case .E1: return "ab" case .E2: return "abc" case .E3: return "abcd" } }
apache-2.0
150e0390b7cf761c3f75ece4f156e192
15.39375
138
0.605795
2.857298
false
false
false
false
jeanetienne/Bee
Bee/Modules/Spelling/SpellingController.swift
1
4381
// // Bee // Copyright © 2017 Jean-Étienne. All rights reserved. // import UIKit import Speller class SpellingController { struct SpellingAlphabetDescription { var name: String var alphabet: SpellingAlphabet } weak var view: SpellingView! var router: SpellingRouter lazy var spellingTableViewManager: SpellingTableViewManager = { return SpellingTableViewManager(controller: self) }() let alphabets: [SpellingAlphabetDescription] = [ SpellingAlphabetDescription(name: "International Radiotelephony", alphabet: .InternationalRadiotelephony), SpellingAlphabetDescription(name: "US Financial", alphabet: .USFinancial), SpellingAlphabetDescription(name: "LAPD", alphabet: .LAPD), SpellingAlphabetDescription(name: "Czech", alphabet: .Czech), SpellingAlphabetDescription(name: "Danish", alphabet: .Danish), SpellingAlphabetDescription(name: "Dutch", alphabet: .Dutch), SpellingAlphabetDescription(name: "Finnish", alphabet: .Finnish), SpellingAlphabetDescription(name: "French", alphabet: .French), SpellingAlphabetDescription(name: "German", alphabet: .German), SpellingAlphabetDescription(name: "Italian", alphabet: .Italian), SpellingAlphabetDescription(name: "Norwegian", alphabet: .Norwegian), SpellingAlphabetDescription(name: "Portuguese", alphabet: .Portuguese), SpellingAlphabetDescription(name: "Brazilian Portuguese", alphabet: .PortugueseBrazilian), SpellingAlphabetDescription(name: "Slovene", alphabet: .Slovene), SpellingAlphabetDescription(name: "Spanish", alphabet: .Spanish), SpellingAlphabetDescription(name: "Swedish", alphabet: .Swedish), SpellingAlphabetDescription(name: "Turkish", alphabet: .Turkish), SpellingAlphabetDescription(name: "PGP Word List", alphabet: .PGPWordList) ] var selectedAlphabet = SpellingAlphabet.InternationalRadiotelephony var currentSpelling: [SpelledCharacter] = [] init(view aView: SpellingView, router aRouter: SpellingRouter, completionHandler aCompletionHandler: ModuleCompletionHandler? = nil) { view = aView router = aRouter } // MARK: - User input func didLoadView() { view.setSpellingTableViewManager(manager: spellingTableViewManager) view.updateAlphabets(alphabets.map { spellingAlphabetDescription -> String in return spellingAlphabetDescription.name }) } func didPresentView() { view.deselectSpellingTableView() } func didSelectAlphabet(withName name: String, phrase: String?) { selectedAlphabet = alphabets.first(where: { spellingAlphabetDescription -> Bool in spellingAlphabetDescription.name == name })?.alphabet ?? .InternationalRadiotelephony if let phrase = phrase { spell(phrase: phrase, withSpellingAlphabet: selectedAlphabet) } } func didSelectSpell(phrase: String?) { if let phrase = phrase { spell(phrase: phrase, withSpellingAlphabet: selectedAlphabet) } } func didSelectClear() { spellingTableViewManager.viewModel = SpellingViewModel(withSpelling: []) view.updateSpelling(withNumberOfCharacters: 0) } // MARK: - Private helpers func spell(phrase: String, withSpellingAlphabet alphabet: SpellingAlphabet) { currentSpelling = Speller.spell(phrase: phrase, withSpellingAlphabet: alphabet) let spellingViewModel = SpellingViewModel(withSpelling: currentSpelling) spellingTableViewManager.viewModel = spellingViewModel view.updateSpelling(withNumberOfCharacters: spellingViewModel.numberOfSpelledCharacters) } } extension SpelledCharacter { var letter: String { switch self { case .Match(let character, _): return character case .Description(let character, _): return character case .Unknown(let character): return character } } var description: String? { switch self { case .Match(_, let codeWordCollection): return codeWordCollection.mainCodeWord case .Description(_, let description): return description case .Unknown(_): return nil } } }
mit
97c7d5dea698a03097154c58ee2b15b9
34.601626
138
0.684403
4.708602
false
false
false
false
Jubilant-Appstudio/Scuba
Pods/SkyFloatingLabelTextField/Sources/SkyFloatingLabelTextField.swift
1
19983
// Copyright 2016-2017 Skyscanner Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License // for the specific language governing permissions and limitations under the License. import UIKit /** A beautiful and flexible textfield implementation with support for title label, error message and placeholder. */ @IBDesignable open class SkyFloatingLabelTextField: UITextField { // swiftlint:disable:this type_body_length /** A Boolean value that determines if the language displayed is LTR. Default value set automatically from the application language settings. */ open var isLTRLanguage: Bool = UIApplication.shared.userInterfaceLayoutDirection == .leftToRight { didSet { updateTextAligment() } } fileprivate func updateTextAligment() { if isLTRLanguage { textAlignment = .left titleLabel.textAlignment = .left } else { textAlignment = .right titleLabel.textAlignment = .right } } // MARK: Animation timing /// The value of the title appearing duration @objc dynamic open var titleFadeInDuration: TimeInterval = 0.2 /// The value of the title disappearing duration @objc dynamic open var titleFadeOutDuration: TimeInterval = 0.3 // MARK: Colors fileprivate var cachedTextColor: UIColor? /// A UIColor value that determines the text color of the editable text @IBInspectable override dynamic open var textColor: UIColor? { set { cachedTextColor = newValue updateControl(false) } get { return cachedTextColor } } /// A UIColor value that determines text color of the placeholder label @IBInspectable dynamic open var placeholderColor: UIColor = UIColor.lightGray { didSet { updatePlaceholder() } } /// A UIFont value that determines text color of the placeholder label @objc dynamic open var placeholderFont: UIFont? { didSet { updatePlaceholder() } } fileprivate func updatePlaceholder() { if let placeholder = placeholder, let font = placeholderFont ?? font { #if swift(>=4.0) attributedPlaceholder = NSAttributedString( string: placeholder, attributes: [ NSAttributedStringKey.foregroundColor: placeholderColor, NSAttributedStringKey.font: font ] ) #else attributedPlaceholder = NSAttributedString( string: placeholder, attributes: [NSForegroundColorAttributeName: placeholderColor, NSFontAttributeName: font] ) #endif } } /// A UIFont value that determines the text font of the title label @objc dynamic open var titleFont: UIFont = .systemFont(ofSize: 13) { didSet { updateTitleLabel() } } /// A UIColor value that determines the text color of the title label when in the normal state @IBInspectable dynamic open var titleColor: UIColor = .gray { didSet { updateTitleColor() } } /// A UIColor value that determines the color of the bottom line when in the normal state @IBInspectable dynamic open var lineColor: UIColor = .lightGray { didSet { updateLineView() } } /// A UIColor value that determines the color used for the title label and line when the error message is not `nil` @IBInspectable dynamic open var errorColor: UIColor = .red { didSet { updateColors() } } /// A UIColor value that determines the text color of the title label when editing @IBInspectable dynamic open var selectedTitleColor: UIColor = .blue { didSet { updateTitleColor() } } /// A UIColor value that determines the color of the line in a selected state @IBInspectable dynamic open var selectedLineColor: UIColor = .black { didSet { updateLineView() } } // MARK: Line height /// A CGFloat value that determines the height for the bottom line when the control is in the normal state @IBInspectable dynamic open var lineHeight: CGFloat = 0.5 { didSet { updateLineView() setNeedsDisplay() } } /// A CGFloat value that determines the height for the bottom line when the control is in a selected state @IBInspectable dynamic open var selectedLineHeight: CGFloat = 1.0 { didSet { updateLineView() setNeedsDisplay() } } // MARK: View components /// The internal `UIView` to display the line below the text input. open var lineView: UIView! /// The internal `UILabel` that displays the selected, deselected title or error message based on the current state. open var titleLabel: UILabel! // MARK: Properties /** The formatter used before displaying content in the title label. This can be the `title`, `selectedTitle` or the `errorMessage`. The default implementation converts the text to uppercase. */ open var titleFormatter: ((String) -> String) = { (text: String) -> String in return text.uppercased() } /** Identifies whether the text object should hide the text being entered. */ override open var isSecureTextEntry: Bool { set { super.isSecureTextEntry = newValue fixCaretPosition() } get { return super.isSecureTextEntry } } /// A String value for the error message to display. open var errorMessage: String? { didSet { updateControl(true) } } /// The backing property for the highlighted property fileprivate var _highlighted: Bool = false /** A Boolean value that determines whether the receiver is highlighted. When changing this value, highlighting will be done with animation */ override open var isHighlighted: Bool { get { return _highlighted } set { _highlighted = newValue updateTitleColor() updateLineView() } } /// A Boolean value that determines whether the textfield is being edited or is selected. open var editingOrSelected: Bool { return super.isEditing || isSelected } /// A Boolean value that determines whether the receiver has an error message. open var hasErrorMessage: Bool { return errorMessage != nil && errorMessage != "" } fileprivate var _renderingInInterfaceBuilder: Bool = false /// The text content of the textfield @IBInspectable override open var text: String? { didSet { updateControl(false) } } /** The String to display when the input field is empty. The placeholder can also appear in the title label when both `title` `selectedTitle` and are `nil`. */ @IBInspectable override open var placeholder: String? { didSet { setNeedsDisplay() updatePlaceholder() updateTitleLabel() } } /// The String to display when the textfield is editing and the input is not empty. @IBInspectable open var selectedTitle: String? { didSet { updateControl() } } /// The String to display when the textfield is not editing and the input is not empty. @IBInspectable open var title: String? { didSet { updateControl() } } // Determines whether the field is selected. When selected, the title floats above the textbox. open override var isSelected: Bool { didSet { updateControl(true) } } // MARK: - Initializers /** Initializes the control - parameter frame the frame of the control */ override public init(frame: CGRect) { super.init(frame: frame) init_SkyFloatingLabelTextField() } /** Intialzies the control by deserializing it - parameter coder the object to deserialize the control from */ required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) init_SkyFloatingLabelTextField() } fileprivate final func init_SkyFloatingLabelTextField() { borderStyle = .none createTitleLabel() createLineView() updateColors() addEditingChangedObserver() updateTextAligment() } fileprivate func addEditingChangedObserver() { self.addTarget(self, action: #selector(SkyFloatingLabelTextField.editingChanged), for: .editingChanged) } /** Invoked when the editing state of the textfield changes. Override to respond to this change. */ @objc open func editingChanged() { updateControl(true) updateTitleLabel(true) } // MARK: create components fileprivate func createTitleLabel() { let titleLabel = UILabel() titleLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight] titleLabel.font = titleFont titleLabel.alpha = 0.0 titleLabel.textColor = titleColor addSubview(titleLabel) self.titleLabel = titleLabel } fileprivate func createLineView() { if lineView == nil { let lineView = UIView() lineView.isUserInteractionEnabled = false self.lineView = lineView configureDefaultLineHeight() } lineView.autoresizingMask = [.flexibleWidth, .flexibleTopMargin] addSubview(lineView) } fileprivate func configureDefaultLineHeight() { let onePixel: CGFloat = 1.0 / UIScreen.main.scale lineHeight = 2.0 * onePixel selectedLineHeight = 2.0 * self.lineHeight } // MARK: Responder handling /** Attempt the control to become the first responder - returns: True when successfull becoming the first responder */ @discardableResult override open func becomeFirstResponder() -> Bool { let result = super.becomeFirstResponder() updateControl(true) return result } /** Attempt the control to resign being the first responder - returns: True when successfull resigning being the first responder */ @discardableResult override open func resignFirstResponder() -> Bool { let result = super.resignFirstResponder() updateControl(true) return result } // MARK: - View updates fileprivate func updateControl(_ animated: Bool = false) { updateColors() updateLineView() updateTitleLabel(animated) } fileprivate func updateLineView() { if let lineView = lineView { lineView.frame = lineViewRectForBounds(bounds, editing: editingOrSelected) } updateLineColor() } // MARK: - Color updates /// Update the colors for the control. Override to customize colors. open func updateColors() { updateLineColor() updateTitleColor() updateTextColor() } fileprivate func updateLineColor() { if hasErrorMessage { lineView.backgroundColor = errorColor } else { lineView.backgroundColor = editingOrSelected ? selectedLineColor : lineColor } } fileprivate func updateTitleColor() { if hasErrorMessage { titleLabel.textColor = errorColor } else { if editingOrSelected || isHighlighted { titleLabel.textColor = selectedTitleColor } else { titleLabel.textColor = titleColor } } } fileprivate func updateTextColor() { if hasErrorMessage { super.textColor = errorColor } else { super.textColor = cachedTextColor } } // MARK: - Title handling fileprivate func updateTitleLabel(_ animated: Bool = false) { var titleText: String? = nil if hasErrorMessage { titleText = titleFormatter(errorMessage!) } else { if editingOrSelected { titleText = selectedTitleOrTitlePlaceholder() if titleText == nil { titleText = titleOrPlaceholder() } } else { titleText = titleOrPlaceholder() } } titleLabel.text = titleText titleLabel.font = titleFont updateTitleVisibility(animated) } fileprivate var _titleVisible: Bool = false /* * Set this value to make the title visible */ open func setTitleVisible( _ titleVisible: Bool, animated: Bool = false, animationCompletion: ((_ completed: Bool) -> Void)? = nil ) { if _titleVisible == titleVisible { return } _titleVisible = titleVisible updateTitleColor() updateTitleVisibility(animated, completion: animationCompletion) } /** Returns whether the title is being displayed on the control. - returns: True if the title is displayed on the control, false otherwise. */ open func isTitleVisible() -> Bool { return hasText || hasErrorMessage || _titleVisible } fileprivate func updateTitleVisibility(_ animated: Bool = false, completion: ((_ completed: Bool) -> Void)? = nil) { let alpha: CGFloat = isTitleVisible() ? 1.0 : 0.0 let frame: CGRect = titleLabelRectForBounds(bounds, editing: isTitleVisible()) let updateBlock = { () -> Void in self.titleLabel.alpha = alpha self.titleLabel.frame = frame } if animated { let animationOptions: UIViewAnimationOptions = .curveEaseOut let duration = isTitleVisible() ? titleFadeInDuration : titleFadeOutDuration UIView.animate(withDuration: duration, delay: 0, options: animationOptions, animations: { () -> Void in updateBlock() }, completion: completion) } else { updateBlock() completion?(true) } } // MARK: - UITextField text/placeholder positioning overrides /** Calculate the rectangle for the textfield when it is not being edited - parameter bounds: The current bounds of the field - returns: The rectangle that the textfield should render in */ override open func textRect(forBounds bounds: CGRect) -> CGRect { let superRect = super.textRect(forBounds: bounds) let titleHeight = self.titleHeight() let rect = CGRect( x: superRect.origin.x, y: titleHeight, width: superRect.size.width, height: superRect.size.height - titleHeight - selectedLineHeight ) return rect } /** Calculate the rectangle for the textfield when it is being edited - parameter bounds: The current bounds of the field - returns: The rectangle that the textfield should render in */ override open func editingRect(forBounds bounds: CGRect) -> CGRect { let superRect = super.editingRect(forBounds: bounds) let titleHeight = self.titleHeight() let rect = CGRect( x: superRect.origin.x, y: titleHeight, width: superRect.size.width, height: superRect.size.height - titleHeight - selectedLineHeight ) return rect } /** Calculate the rectangle for the placeholder - parameter bounds: The current bounds of the placeholder - returns: The rectangle that the placeholder should render in */ override open func placeholderRect(forBounds bounds: CGRect) -> CGRect { let rect = CGRect( x: 0, y: titleHeight(), width: bounds.size.width, height: bounds.size.height - titleHeight() - selectedLineHeight ) return rect } // MARK: - Positioning Overrides /** Calculate the bounds for the title label. Override to create a custom size title field. - parameter bounds: The current bounds of the title - parameter editing: True if the control is selected or highlighted - returns: The rectangle that the title label should render in */ open func titleLabelRectForBounds(_ bounds: CGRect, editing: Bool) -> CGRect { if editing { return CGRect(x: 0, y: 0, width: bounds.size.width, height: titleHeight()) } return CGRect(x: 0, y: titleHeight(), width: bounds.size.width, height: titleHeight()) } /** Calculate the bounds for the bottom line of the control. Override to create a custom size bottom line in the textbox. - parameter bounds: The current bounds of the line - parameter editing: True if the control is selected or highlighted - returns: The rectangle that the line bar should render in */ open func lineViewRectForBounds(_ bounds: CGRect, editing: Bool) -> CGRect { let height = editing ? selectedLineHeight : lineHeight return CGRect(x: 0, y: bounds.size.height - height, width: bounds.size.width, height: height) } /** Calculate the height of the title label. -returns: the calculated height of the title label. Override to size the title with a different height */ open func titleHeight() -> CGFloat { if let titleLabel = titleLabel, let font = titleLabel.font { return font.lineHeight } return 15.0 } /** Calcualte the height of the textfield. -returns: the calculated height of the textfield. Override to size the textfield with a different height */ open func textHeight() -> CGFloat { return self.font!.lineHeight + 7.0 } // MARK: - Layout /// Invoked when the interface builder renders the control override open func prepareForInterfaceBuilder() { if #available(iOS 8.0, *) { super.prepareForInterfaceBuilder() } borderStyle = .none isSelected = true _renderingInInterfaceBuilder = true updateControl(false) invalidateIntrinsicContentSize() } /// Invoked by layoutIfNeeded automatically override open func layoutSubviews() { super.layoutSubviews() titleLabel.frame = titleLabelRectForBounds(bounds, editing: isTitleVisible() || _renderingInInterfaceBuilder) lineView.frame = lineViewRectForBounds(bounds, editing: editingOrSelected || _renderingInInterfaceBuilder) } /** Calculate the content size for auto layout - returns: the content size to be used for auto layout */ override open var intrinsicContentSize: CGSize { return CGSize(width: bounds.size.width, height: titleHeight() + textHeight()) } // MARK: - Helpers fileprivate func titleOrPlaceholder() -> String? { guard let title = title ?? placeholder else { return nil } return titleFormatter(title) } fileprivate func selectedTitleOrTitlePlaceholder() -> String? { guard let title = selectedTitle ?? title ?? placeholder else { return nil } return titleFormatter(title) } } // swiftlint:disable:this file_length
mit
7e95ef3ef05b1a5e87601af345b972ef
30.719048
120
0.625882
5.444959
false
false
false
false
timkettering/SwiftTicTacToe
TicTacToe/GameState.swift
1
3205
// // GameBoard.swift // TicTacToe // // Created by Tim Kettering on 6/24/15. // // import Foundation // for application design simplicity, we'll hardcode defaults // for the tic-tac-toe game instance let DEFAULT_GAMEBOARD_SIZE: Int = 3 let DEFAULT_GAMEBOARD_SQUARES: Int = DEFAULT_GAMEBOARD_SIZE * DEFAULT_GAMEBOARD_SIZE let LEGAL_WINNING_LINES = (DEFAULT_GAMEBOARD_SIZE * 2) + 2 enum Player: CustomStringConvertible { case X case O func getOpponent() -> Player { return (self == Player.X) ? Player.O : Player.X } var description: String { return (self == Player.X) ? "X" : "O" } } struct GameSquarePos { var row: Int var col: Int static func getArrayPosForGameSquarePos(_ pos: GameSquarePos) -> Int { return (pos.row * DEFAULT_GAMEBOARD_SIZE) + pos.col } static func getGameSquareForArrayPos(_ pos: Int) -> GameSquarePos { let row = pos / DEFAULT_GAMEBOARD_SIZE let col = pos % DEFAULT_GAMEBOARD_SIZE return GameSquarePos(row: row, col: col) } } struct GameState: CustomStringConvertible { let squares: [Player?] var unplayedPositions = [GameSquarePos]() var xPositions = [GameSquarePos]() var oPositions = [GameSquarePos]() var totalMoves = 0 init() { squares = [Player?](repeating: nil, count: DEFAULT_GAMEBOARD_SQUARES) unplayedPositions = getUnplayedPositions() xPositions = getPlayerPositions(Player.X) oPositions = getPlayerPositions(Player.O) totalMoves = xPositions.count + oPositions.count } init(squares sq: [Player?]) { squares = sq unplayedPositions = getUnplayedPositions() xPositions = getPlayerPositions(Player.X) oPositions = getPlayerPositions(Player.O) totalMoves = xPositions.count + oPositions.count } fileprivate func getUnplayedPositions() -> [GameSquarePos] { var unplayedPositions = [GameSquarePos]() for i in 0 ..< DEFAULT_GAMEBOARD_SQUARES where squares[i] == nil { unplayedPositions.append(GameSquarePos.getGameSquareForArrayPos(i)) } return unplayedPositions } func getPlayerForPosition(_ gameSquarePos: GameSquarePos) -> Player? { return squares[GameSquarePos.getArrayPosForGameSquarePos(gameSquarePos)] } fileprivate func getPlayerPositions(_ player: Player) -> [GameSquarePos] { var playerPositions = [GameSquarePos]() for i in 0 ..< DEFAULT_GAMEBOARD_SQUARES where squares[i] == player { playerPositions.append(GameSquarePos.getGameSquareForArrayPos(i)) } return playerPositions } var description: String { var desc = "\n" for i in 0 ..< DEFAULT_GAMEBOARD_SIZE { desc += "|" for j in 0 ..< DEFAULT_GAMEBOARD_SIZE { if j > 0 { desc += "," } if let player = getPlayerForPosition(GameSquarePos(row: i, col: j)) { desc += player.description } else { desc += "_" } } desc += "|\n" } return desc } }
mit
c0cd0a76381f1e41fc4e07423f4cb6c3
29.817308
85
0.612168
4.036524
false
false
false
false
BBRick/wp
wp/Scenes/User/MyPushController.swift
1
6497
// // MyPushController.swift // wp // // Created by macbook air on 16/12/23. // Copyright © 2016年 com.yundian. All rights reserved. // import UIKit private let originalCellId = "MyPushCell" class MyPushController: BasePageListTableViewController { let pushNumber = UILabel() let pushToday = UILabel() let pushWeek = UILabel() let pushMonthly = UILabel() override func viewDidLoad() { super.viewDidLoad() tableView.tableHeaderView = setupHeaderView() } func backDidClick() { _ = navigationController?.popToRootViewController(animated: true) } func setupHeaderView()->(UIView) { let bigSumView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 60)) let sumView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50)) sumView.backgroundColor = UIColor(rgbHex:0xFFFFFF) let imageView = UIImageView(image: UIImage(named: "icon-13.png")) let grayView = UIView() sumView.addSubview(pushNumber) sumView.addSubview(pushToday) sumView.addSubview(pushWeek) sumView.addSubview(pushMonthly) sumView.addSubview(imageView) bigSumView.addSubview(sumView) bigSumView.addSubview(grayView) imageView.snp.makeConstraints { (make) in make.left.equalTo(sumView).offset(18) make.top.equalTo(sumView).offset(17) make.width.equalTo(17) make.height.equalTo(17) } pushNumber.snp.makeConstraints { (make) in make.left.equalTo(imageView.snp.right).offset(8) make.top.equalTo(sumView).offset(18) make.height.equalTo(15) } pushNumber.text = "推单总数: 20" pushNumber.sizeToFit() pushNumber.font = UIFont.systemFont(ofSize: 16 * (UIScreen.main.bounds.width / 375)) pushNumber.textColor = UIColor(rgbHex:0x333333) //本月 pushMonthly.snp.makeConstraints { (make) in make.right.equalTo(sumView).offset(-15) make.top.equalTo(sumView).offset(18) make.height.equalTo(15) } pushMonthly.text = "本月8" pushMonthly.sizeToFit() pushMonthly.font = UIFont.systemFont(ofSize: 16 * (UIScreen.main.bounds.width / 375)) pushMonthly.textColor = UIColor(rgbHex:0x333333) //本周 pushWeek.snp.makeConstraints { (make) in make.right.equalTo(pushMonthly.snp.left).offset(-20) make.top.equalTo(pushMonthly) make.height.equalTo(15) } pushWeek.text = "本周3" pushWeek.sizeToFit() pushWeek.font = UIFont.systemFont(ofSize: 16 * (UIScreen.main.bounds.width / 375)) pushWeek.textColor = UIColor(rgbHex:0x333333) //今日 pushToday.snp.makeConstraints { (make) in make.right.equalTo(pushWeek.snp.left).offset(-20) make.top.equalTo(pushMonthly) make.height.equalTo(15) } pushToday.text = "今日3" pushToday.sizeToFit() pushToday.font = UIFont.systemFont(ofSize: 16 * (UIScreen.main.bounds.width / 375)) pushToday.textColor = UIColor(rgbHex:0x333333) //灰色的线 grayView.snp.makeConstraints { (make) in make.top.equalTo(sumView.snp.bottom) make.left.equalTo(bigSumView) make.right.equalTo(bigSumView) make.bottom.equalTo(bigSumView) } grayView.backgroundColor = UIColor(rgbHex:0xF6F7FB) return bigSumView } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) showTabBarWithAnimationDuration() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) hideTabBarWithAnimationDuration() translucent(clear: false) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table view data source // override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // let cell = tableView.dequeueReusableCell(withIdentifier: originalCellId, for: indexPath) as! MyPushCell // // return cell // } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 107 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath.item == 0 { print("0") } } override func didRequest(_ pageIndex : Int){ didRequestComplete(["",""] as AnyObject) } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
853d978cf29bc82c7a3bd5a2305de4ad
34.657459
136
0.63604
4.460263
false
false
false
false
skyefreeman/OnTap
OnTap/Classes/UIControl+OnTap.swift
1
2666
// // UIControl+OnTap.swift // OnTap // // Created by Skye Freeman on 1/27/17. // Copyright © 2017 Skye Freeman. All rights reserved. // import UIKit public extension UIControl { @discardableResult func on(_ event: UIControlEvents, completion: @escaping OTStandardClosure) -> Self { if event == .touchDown { touchHandler.onTouchDown = completion } else if event == .touchDownRepeat { touchHandler.onTouchDownRepeat = completion } else if event == .touchDragInside { touchHandler.onTouchDragInside = completion } else if event == .touchDragOutside { touchHandler.onTouchDragOutside = completion } else if event == .touchDragEnter { touchHandler.onTouchDragEnter = completion } else if event == .touchDragExit { touchHandler.onTouchDragExit = completion } else if event == .touchUpInside { touchHandler.onTouchUpInside = completion } else if event == .touchUpOutside { touchHandler.onTouchUpOutside = completion } else if event == .touchCancel { touchHandler.onTouchCancel = completion } else if event == .valueChanged { touchHandler.onValueChanged = completion } else if event == .editingDidBegin { touchHandler.onEditingDidBegin = completion } else if event == .editingChanged { touchHandler.onEditingChanged = completion } else if event == .editingDidEnd { touchHandler.onEditingDidEnd = completion } else if event == .editingDidEndOnExit { touchHandler.onEditingDidEndOnExit = completion } else if event == .allTouchEvents { touchHandler.onAllTouchEvents = completion } else if event == .allEditingEvents { touchHandler.onAllEditingEvents = completion } else if event == .applicationReserved { touchHandler.onApplicationReserved = completion } else if event == .systemReserved { touchHandler.onSystemReserved = completion } else if event == .allEvents { touchHandler.onAllEvents = completion } return self } // MARK: Private private struct AssociatedKeys { static var touchHandlerKey = "OTControlTouchHandlerKey" } private var touchHandler: UIControlTouchHandler { get { if let handler = objc_getAssociatedObject(self, &AssociatedKeys.touchHandlerKey) as? UIControlTouchHandler { return handler } else { self.touchHandler = UIControlTouchHandler(control: self) return self.touchHandler } } set { objc_setAssociatedObject(self, &AssociatedKeys.touchHandlerKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } }
mit
8475393c157bae84fdf03f263c2b3a34
47.454545
121
0.681801
5.134875
false
false
false
false
steelwheels/KiwiScript
KiwiLibrary/Source/Setup/KLCompiler.swift
1
37615
/** * @file KLCompiler.swift * @brief Define KLCompiler class * @par Copyright * Copyright (C) 2018 Steel Wheels Project */ import KiwiEngine import CoconutData import CoconutDatabase import JavaScriptCore #if os(OSX) import AppKit #else import UIKit #endif import Foundation open class KLLibraryCompiler: KECompiler { open func compile(context ctxt: KEContext, resource res: KEResource, processManager procmgr: CNProcessManager, terminalInfo terminfo: CNTerminalInfo, environment env: CNEnvironment, console cons: CNFileConsole, config conf: KEConfig) -> Bool { guard compileBase(context: ctxt, terminalInfo: terminfo, environment: env, console: cons, config: conf) else { CNLog(logLevel: .error, message: "[Error] Failed to compile: base", atFunction: #function, inFile: #file) return false } guard compileGeneralFunctions(context: ctxt, resource: res, processManager: procmgr, terminalInfo: terminfo, environment: env, console: cons, config: conf) else { CNLog(logLevel: .error, message: "[Error] Failed to compile: general functions", atFunction: #function, inFile: #file) return false } guard compileThreadFunctions(context: ctxt, resource: res, processManager: procmgr, terminalInfo: terminfo, environment: env, console: cons, config: conf) else { CNLog(logLevel: .error, message: "[Error] Failed to compile: thread functions", atFunction: #function, inFile: #file) return false } guard compileBuiltinScripts(context: ctxt, terminalInfo: terminfo, environment: env, console: cons, config: conf) else { CNLog(logLevel: .error, message: "[Error] Failed to compile: built-in scripts", atFunction: #function, inFile: #file) return false } guard compileUserScripts(context: ctxt, resource: res, processManager: procmgr, environment: env, console: cons, config: conf) else { CNLog(logLevel: .error, message: "[Error] Failed to compile: user scripts", atFunction: #function, inFile: #file) return false } return true } private func compileGeneralFunctions(context ctxt: KEContext, resource res: KEResource, processManager procmgr: CNProcessManager, terminalInfo terminfo: CNTerminalInfo, environment env: CNEnvironment, console cons: CNFileConsole, config conf: KEConfig) -> Bool { defineConstants(context: ctxt) defineFunctions(context: ctxt, console: cons, config: conf) definePrimitiveObjects(context: ctxt, console: cons, config: conf) defineClassObjects(context: ctxt, terminalInfo: terminfo, environment: env, console: cons, config: conf) defineGlobalObjects(context: ctxt, console: cons, config: conf) defineConstructors(context: ctxt, resource: res, console: cons, config: conf) defineDatabase(context: ctxt, console: cons, config: conf) return true } private func compileThreadFunctions(context ctxt: KEContext, resource res: KEResource, processManager procmgr: CNProcessManager, terminalInfo terminfo: CNTerminalInfo, environment env: CNEnvironment, console cons: CNConsole, config conf: KEConfig) -> Bool { if defineThreadFunction(context: ctxt, resource: res, processManager: procmgr, terminalInfo: terminfo, environment: env, console: cons, config: conf) { return (ctxt.errorCount == 0) } else { return false } } private func compileBuiltinScripts(context ctxt: KEContext, terminalInfo terminfo: CNTerminalInfo, environment env: CNEnvironment, console cons: CNFileConsole, config conf: KEConfig) -> Bool { importBuiltinLibrary(context: ctxt, console: cons, config: conf) return (ctxt.errorCount == 0) } private func compileUserScripts(context ctxt: KEContext, resource res: KEResource, processManager procmgr: CNProcessManager, environment env: CNEnvironment, console cons: CNConsole, config conf: KEConfig) -> Bool { if compileLibraryFiles(context: ctxt, resource: res, processManager: procmgr, environment: env, console: cons, config: conf) { return (ctxt.errorCount == 0) } else { return false } } private func compileLibraryFiles(context ctxt: KEContext, resource res: KEResource, processManager procmgr: CNProcessManager, environment env: CNEnvironment, console cons: CNConsole, config conf: KEConfig) -> Bool { /* Compile library */ var result = true if let libnum = res.countOfLibraries() { for i in 0..<libnum { if let scr = res.loadLibrary(index: i) { let srcfile = res.URLOfLibrary(index: i) let _ = self.compileStatement(context: ctxt, statement: scr, sourceFile: srcfile, console: cons, config: conf) } else { if let fname = res.URLOfLibrary(index: i) { cons.error(string: "Failed to load library: \(fname.absoluteString)\n") result = false } else { cons.error(string: "Failed to load file in library section\n") result = false } } } } return result && (ctxt.errorCount == 0) } private func defineConstants(context ctxt: KEContext) { /* PI */ if let pival = JSValue(double: Double.pi, in: ctxt){ ctxt.set(name: "PI", value: pival) } } private func defineFunctions(context ctxt: KEContext, console cons: CNConsole, config conf: KEConfig) { /* isUndefined */ let isUndefinedFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in let result: Bool = value.isUndefined return JSValue(bool: result, in: ctxt) } ctxt.set(name: "isUndefined", function: isUndefinedFunc) /* isNull */ let isNullFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in let result: Bool = value.isNull return JSValue(bool: result, in: ctxt) } ctxt.set(name: "isNull", function: isNullFunc) /* isBoolean */ let isBooleanFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in let result: Bool = value.isBoolean return JSValue(bool: result, in: ctxt) } ctxt.set(name: "isBoolean", function: isBooleanFunc) /* toBoolean */ let toBooleanFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in if value.isBoolean { return value } else if value.isNumber { if let num = value.toNumber() { return JSValue(bool: num.intValue != 0, in: ctxt) } else { return JSValue(nullIn: ctxt) } } else { return JSValue(nullIn: ctxt) } } ctxt.set(name: "toBoolean", function: toBooleanFunc) /* isNumber */ let isNumberFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in let result: Bool = value.isNumber return JSValue(bool: result, in: ctxt) } ctxt.set(name: "isNumber", function: isNumberFunc) /* toNumber */ let toNumberFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in if value.isNumber { return value } else { return JSValue(nullIn: ctxt) } } ctxt.set(name: "toNumber", function: toNumberFunc) /* isString */ let isStringFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in let result: Bool = value.isString return JSValue(bool: result, in: ctxt) } ctxt.set(name: "isString", function: isStringFunc) /* toString */ let toStringFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in if value.isString { return value } else { return JSValue(nullIn: ctxt) } } ctxt.set(name: "toString", function: toStringFunc) /* isObject */ let isObjectFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in let result: Bool = value.isObject return JSValue(bool: result, in: ctxt) } ctxt.set(name: "isObject", function: isObjectFunc) /* toObject */ let toObjectFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in if value.isObject { return value } else { return JSValue(nullIn: ctxt) } } ctxt.set(name: "toObject", function: toObjectFunc) /* isArray */ let isArrayFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in let result: Bool = value.isArray return JSValue(bool: result, in: ctxt) } ctxt.set(name: "isArray", function: isArrayFunc) /* toArray */ let toArrayFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in if value.isArray { return value } else { return JSValue(nullIn: ctxt) } } ctxt.set(name: "toArray", function: toArrayFunc) /* isDictionary */ let isDictFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in var result: Bool = false if value.isObject { if let _ = value.toObject() as? Dictionary<String, Any> { result = true } } return JSValue(bool: result, in: ctxt) } ctxt.set(name: "isDictionary", function: isDictFunc) /* toDictionary */ let toDictFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in if value.isObject { if let _ = value.toObject() as? Dictionary<String, Any> { return value } } return JSValue(nullIn: ctxt) } ctxt.set(name: "toDictionary", function: toDictFunc) /* isRecord */ let isRecordFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in return JSValue(bool: value.isRecord, in: ctxt) } ctxt.set(name: "isRecord", function: isRecordFunc) /* toRecord */ let toRecordFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in if value.isRecord { return value } else { return JSValue(nullIn: ctxt) } } ctxt.set(name: "toRecord", function: toRecordFunc) /* isDate */ let isDateFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in let result: Bool = value.isDate return JSValue(bool: result, in: ctxt) } ctxt.set(name: "isDate", function: isDateFunc) /* toDate */ let toDateFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in if value.isDate { return value } else { return JSValue(nullIn: ctxt) } } ctxt.set(name: "toDate", function: toDateFunc) /* isURL */ let isURLFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in let result: Bool = value.isURL return JSValue(bool: result, in: ctxt) } ctxt.set(name: "isURL", function: isURLFunc) /* toURL */ let toURLFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in if value.isURL { return value } else { return JSValue(nullIn: ctxt) } } ctxt.set(name: "toURL", function: toURLFunc) /* isPoint */ let isPointFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in return JSValue(bool: value.isPoint, in: ctxt) } ctxt.set(name: "isPoint", function: isPointFunc) let toPointFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in if value.isPoint { return value } else { return JSValue(nullIn: ctxt) } } ctxt.set(name: "toPoint", function: toPointFunc) /* isSize */ let isSizeFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in let result: Bool = value.isSize return JSValue(bool: result, in: ctxt) } ctxt.set(name: "isSize", function: isSizeFunc) /* toSize */ let toSizeFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in if value.isSize { return value } else { return JSValue(nullIn: ctxt) } } ctxt.set(name: "toSize", function: toSizeFunc) /* isRect */ let isRectFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in let result: Bool = value.isRect return JSValue(bool: result, in: ctxt) } ctxt.set(name: "isRect", function: isRectFunc) /* toRect */ let toRectFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in if value.isRect { return value } else { return JSValue(nullIn: ctxt) } } ctxt.set(name: "toRect", function: toRectFunc) /* isBitmap */ let isBitmapFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in let result: Bool = value.isBitmap return JSValue(bool: result, in: ctxt) } ctxt.set(name: "isBitmap", function: isBitmapFunc) /* toBitmap */ let toBitmapFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in if value.isBitmap { return value } else { return JSValue(nullIn: ctxt) } } ctxt.set(name: "toBitmap", function: toBitmapFunc) /* toText */ let toTextFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in let result: KLTextProtocol let txt = value.toScript() if let line = txt as? CNTextLine { result = KLTextLine(text: line, context: ctxt) } else if let sect = txt as? CNTextSection { result = KLTextSection(text: sect, context: ctxt) } else if let table = txt as? CNTextTable { result = KLTextTable(text: table, context: ctxt) } else { let line = CNTextLine(string: "\(value)") result = KLTextLine(text: line, context: ctxt) } return JSValue(object: result, in: ctxt) } ctxt.set(name: "toText", function: toTextFunc) /* isEOF */ let isEofFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in var result = false if value.isNumber { if let num = value.toNumber() { if num.int32Value == CNFile.EOF { result = true } } } return JSValue(bool: result, in: ctxt) } ctxt.set(name: "isEOF", function: isEofFunc) /* asciiCodeName */ let asciiNameFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in if value.isNumber { let code = value.toInt32() if let name = Character.asciiCodeName(code: Int(code)) { return JSValue(object: name, in: ctxt) } } return JSValue(nullIn: ctxt) } ctxt.set(name: "asciiCodeName", function: asciiNameFunc) /* sleep */ let sleepFunc: @convention(block) (_ val: JSValue) -> JSValue = { (_ val: JSValue) -> JSValue in let result: Bool if val.isNumber { Thread.sleep(forTimeInterval: val.toDouble()) result = true } else { result = false } return JSValue(bool: result, in: ctxt) } ctxt.set(name: "sleep", function: sleepFunc) /* _openPanel */ let openPanelFunc: @convention(block) (_ titleval: JSValue, _ typeval: JSValue, _ extsval: JSValue, _ cbfunc: JSValue) -> Void = { (_ titleval: JSValue, _ typeval: JSValue, _ extsval: JSValue, _ cbfunc: JSValue) -> Void in #if os(OSX) if let title = KLLibraryCompiler.valueToString(value: titleval), let type = KLLibraryCompiler.valueToFileType(type: typeval), let exts = KLLibraryCompiler.valueToExtensions(extensions: extsval) { URL.openPanel(title: title, type: type, extensions: exts, callback: { (_ urlp: URL?) -> Void in let param: JSValue if let url = urlp { param = JSValue(URL: url, in: ctxt) } else { param = JSValue(nullIn: ctxt) } CNExecuteInUserThread(level: .event, execute: { cbfunc.call(withArguments: [param]) }) }) } else { if let param = JSValue(nullIn: ctxt) { cbfunc.call(withArguments: [param]) } else { CNLog(logLevel: .error, message: "Failed to allocate return value", atFunction: #function, inFile: #file) } } #else if let param = JSValue(nullIn: ctxt) { cbfunc.call(withArguments: [param]) } else { CNLog(logLevel: .error, message: "Failed to allocate return value", atFunction: #function, inFile: #file) } #endif } ctxt.set(name: "_openPanel", function: openPanelFunc) let savePanelFunc: @convention(block) (_ titleval: JSValue, _ cbfunc: JSValue) -> Void = { (_ titleval: JSValue, _ cbfunc: JSValue) -> Void in #if os(OSX) if let title = KLLibraryCompiler.valueToString(value: titleval) { URL.savePanel(title: title, outputDirectory: nil, callback: { (_ urlp: URL?) -> Void in let param: JSValue if let url = urlp { param = JSValue(URL: url, in: ctxt) } else { param = JSValue(nullIn: ctxt) } cbfunc.call(withArguments: [param]) }) } else { if let param = JSValue(nullIn: ctxt) { cbfunc.call(withArguments: [param]) } else { CNLog(logLevel: .error, message: "Failed to allocate return value", atFunction: #function, inFile: #file) } } #else if let param = JSValue(nullIn: ctxt) { cbfunc.call(withArguments: [param]) } else { CNLog(logLevel: .error, message: "Failed to allocate return value", atFunction: #function, inFile: #file) } #endif } ctxt.set(name: "_savePanel", function: savePanelFunc) /* openURL */ let openURLFunc: @convention(block) (_ urlval: JSValue, _ cbfunc: JSValue) -> JSValue = { (_ urlval: JSValue, _ cbfunc: JSValue) -> JSValue in if let url = KLLibraryCompiler.valueToURL(value: urlval) { CNExecuteInMainThread(doSync: false, execute: { () -> Void in CNWorkspace.open(URL: url, callback: { (_ result: Bool) -> Void in if let param = JSValue(bool: result, in: ctxt) { if !cbfunc.isNull { cbfunc.call(withArguments: [param]) } } }) }) } return JSValue(nullIn: ctxt) } ctxt.set(name: "_openURL", function: openURLFunc) /* exit */ let exitFunc: @convention(block) (_ value: JSValue) -> JSValue switch conf.applicationType { case .terminal: exitFunc = { (_ value: JSValue) -> JSValue in let ecode: Int32 if value.isNumber { ecode = value.toInt32() } else { cons.error(string: "Invalid parameter for exit() function") ecode = 1 } Darwin.exit(ecode) } ctxt.set(name: "exit", function: exitFunc) case .window: #if os(OSX) exitFunc = { [weak self] (_ value: JSValue) -> JSValue in if let myself = self { CNExecuteInMainThread(doSync: true, execute: { () -> Void in NSApplication.shared.terminate(myself) }) } return JSValue(undefinedIn: ctxt) } #else /* The method to quit iOS application is NOT defined */ exitFunc = { (_ value: JSValue) -> JSValue in return JSValue(undefinedIn: ctxt) } #endif ctxt.set(name: "exit", function: exitFunc) @unknown default: CNLog(logLevel: .error, message: "Unknown application type", atFunction: #function, inFile: #file) break } /* _select_exit_code */ let selExitFunc: @convention(block) (_ val0: JSValue, _ val1: JSValue) -> JSValue = { (_ val0: JSValue, _ val1: JSValue) -> JSValue in let result: Int32 if val0.isNumber && val1.isNumber { let code0 = val0.toInt32() let code1 = val1.toInt32() if code0 != 0 { result = code0 } else if code1 != 0 { result = code1 } else { result = 0 } } else { CNLog(logLevel: .error, message: "Invalid parameter for exit() function") result = -1 } return JSValue(int32: result, in: ctxt) } ctxt.set(name: "_select_exit_code", function: selExitFunc) } private func definePrimitiveObjects(context ctxt: KEContext, console cons: CNConsole, config conf: KEConfig) { /* Point */ let pointFunc: @convention(block) (_ xval: JSValue, _ yval: JSValue) -> JSValue = { (_ xval: JSValue, _ yval: JSValue) -> JSValue in if xval.isNumber && yval.isNumber { let x = xval.toDouble() let y = yval.toDouble() return CGPoint(x: x, y: y).toJSValue(context: ctxt) } cons.error(string: "Invalid parameter for Point constructor\n") return JSValue(undefinedIn: ctxt) } ctxt.set(name: "Point", function: pointFunc) /* Size */ let sizeFunc: @convention(block) (_ wval: JSValue, _ hval: JSValue) -> JSValue = { (_ wval: JSValue, _ hval: JSValue) -> JSValue in if wval.isNumber && hval.isNumber { let width = wval.toDouble() let height = hval.toDouble() return CGSize(width: width, height: height).toJSValue(context: ctxt) } cons.error(string: "Invalid parameter for Size constructor\n") return JSValue(undefinedIn: ctxt) } ctxt.set(name: "Size", function: sizeFunc) /* Rect */ let rectFunc: @convention(block) (_ xval: JSValue, _ yval: JSValue, _ widthval: JSValue, _ heightval: JSValue) -> JSValue = { (_ xval: JSValue, _ yval: JSValue, _ widthval: JSValue, _ heightval: JSValue) -> JSValue in if xval.isNumber && yval.isNumber && widthval.isNumber && heightval.isNumber { let x = xval.toDouble() let y = yval.toDouble() let width = widthval.toDouble() let height = heightval.toDouble() let rect = CGRect(x: x, y: y, width: width, height: height) return rect.toJSValue(context: ctxt) } else if xval.isPoint && yval.isSize { let org = xval.toPoint() let size = yval.toSize() let rect = CGRect(origin: org, size: size) return rect.toJSValue(context: ctxt) } cons.error(string: "Invalid parameter for Rect constructor\n") return JSValue(undefinedIn: ctxt) } ctxt.set(name: "Rect", function: rectFunc) } private func defineClassObjects(context ctxt: KEContext, terminalInfo terminfo: CNTerminalInfo, environment env: CNEnvironment, console cons: CNFileConsole, config conf: KEConfig) { /* Pipe() */ let pipeFunc: @convention(block) () -> JSValue = { () -> JSValue in let pipe = KLPipe(context: ctxt) return JSValue(object: pipe, in: ctxt) } ctxt.set(name: "Pipe", function: pipeFunc) /* File */ let file = KLFileManager(context: ctxt, environment: env, input: cons.inputFile, output: cons.outputFile, error: cons.errorFile) ctxt.set(name: "FileManager", object: file) let stdin = KLFile(file: cons.inputFile, context: ctxt) ctxt.set(name: KLFile.StdInName, object: stdin) let stdout = KLFile(file: cons.outputFile, context: ctxt) ctxt.set(name: KLFile.StdOutName, object: stdout) let stderr = KLFile(file: cons.errorFile, context: ctxt) ctxt.set(name: KLFile.StdErrName, object: stderr) /* Color manager */ let colmgr = KLColorManager(context: ctxt) ctxt.set(name: "Color", object: colmgr) /* Curses */ let curses = KLCurses(console: cons, terminalInfo: terminfo, context: ctxt) ctxt.set(name: "Curses", object: curses) /* FontManager */ let fontmgr = KLFontManager(context: ctxt) ctxt.set(name: "FontManager", object: fontmgr) /* ValueFile */ let native = KLNativeValueFile(context: ctxt) ctxt.set(name: "_JSONFile", object: native) /* Char */ let charobj = KLChar(context: ctxt) ctxt.set(name: "Char", object: charobj) /* EscapeCode */ let ecode = KLEscapeCode(context: ctxt) ctxt.set(name: "EscapeCode", object: ecode) /* Environment */ let envobj = KLEnvironment(environment: env, context: ctxt) ctxt.set(name: "Environment", object: envobj) /* Preference: This value will be override by KiwiShell */ let pref = KLPreference(context: ctxt) ctxt.set(name: "Preference", object: pref) /* Built-in script manager */ let scrmgr = KLBuiltinScriptManager(context: ctxt) ctxt.set(name: "ScriptManager", object: scrmgr) /* Symbols */ let symbol = KLSymbol(context: ctxt) ctxt.set(name: "Symbols", object: symbol) } private func defineGlobalObjects(context ctxt: KEContext, console cons: CNFileConsole, config conf: KEConfig) { /* console */ let newcons = KLConsole(context: ctxt, console: cons) ctxt.set(name: "console", object: newcons) } private func defineConstructors(context ctxt: KEContext, resource res: KEResource, console cons: CNConsole, config conf: KEConfig) { /* URL */ let urlFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in if let str = value.toString() { let url: URL? if let _ = FileManager.default.schemeInPath(pathString: str) { url = URL(string: str) } else { url = URL(fileURLWithPath: str) } if let u = url { return JSValue(URL: u, in: ctxt) } } cons.error(string: "Invalid parameter for URL: \(value.description)") return JSValue(nullIn: ctxt) } ctxt.set(name: "URL", function: urlFunc) /* Bitmap */ let allocBitmapFunc: @convention(block) (_ value: JSValue) -> JSValue = { (_ value: JSValue) -> JSValue in var result: KLBitmapData? = nil if value.isBitmap { result = value.toBitmap() } else if value.isObject { if let arr = value.toObject() as? Array<Array<KLColor>> { let carr = arr.map { $0.map { $0.core } } let bm = CNBitmapData(colorData: carr) result = KLBitmapData(bitmap: bm, context: ctxt) } } if let r = result { return JSValue(object: r, in: ctxt) } else { return JSValue(nullIn: ctxt) } } ctxt.set(name: "Bitmap", function: allocBitmapFunc) /* ArrayStorage */ let allocArrayFunc: @convention(block) (_ storageval: JSValue, _ pathval: JSValue) -> JSValue = { (_ storageval: JSValue, _ pathval: JSValue) -> JSValue in guard let path = KLLibraryCompiler.valueToString(value: pathval) else { CNLog(logLevel: .error, message: "Unexpected path expression: \(String(describing: pathval.toString))") return JSValue(nullIn: ctxt) } guard let storage = self.allocateStorage(name: storageval, resource: res) else { CNLog(logLevel: .error, message: "Failed to get storage named: \(String(describing: storageval.toString))") return JSValue(nullIn: ctxt) } switch CNValuePath.pathExpression(string: path) { case .success(let path): let arr = CNStorageArray(path: path, storage: storage) let arrobj = KLArray(array: arr, context: ctxt) return JSValue(object: arrobj, in: ctxt) case .failure(let err): CNLog(logLevel: .error, message: err.toString()) return JSValue(nullIn: ctxt) } } ctxt.set(name: "ArrayStorage", function: allocArrayFunc) /* SetStorage */ let allocSetFunc: @convention(block) (_ storageval: JSValue, _ pathval: JSValue) -> JSValue = { (_ storageval: JSValue, _ pathval: JSValue) -> JSValue in guard let path = KLLibraryCompiler.valueToString(value: pathval) else { CNLog(logLevel: .error, message: "Unexpected path expression: \(String(describing: pathval.toString))") return JSValue(nullIn: ctxt) } guard let storage = self.allocateStorage(name: storageval, resource: res) else { CNLog(logLevel: .error, message: "Failed to get storage named: \(String(describing: storageval.toString))") return JSValue(nullIn: ctxt) } switch CNValuePath.pathExpression(string: path) { case .success(let path): let set = CNStorageSet(path: path, storage: storage) let setobj = KLSet(set: set, context: ctxt) return JSValue(object: setobj, in: ctxt) case .failure(let err): CNLog(logLevel: .error, message: err.toString()) return JSValue(nullIn: ctxt) } } ctxt.set(name: "SetStorage", function: allocSetFunc) /* DictionaryStorage */ let allocDictSFunc: @convention(block) (_ storageval: JSValue, _ pathval: JSValue) -> JSValue = { (_ storageval: JSValue, _ pathval: JSValue) -> JSValue in guard let path = KLLibraryCompiler.valueToString(value: pathval) else { CNLog(logLevel: .error, message: "Unexpected path expression: \(String(describing: pathval.toString))") return JSValue(nullIn: ctxt) } guard let storage = self.allocateStorage(name: storageval, resource: res) else { CNLog(logLevel: .error, message: "Failed to get storage named: \(String(describing: storageval.toString))") return JSValue(nullIn: ctxt) } switch CNValuePath.pathExpression(string: path) { case .success(let path): let dict = CNStorageDictionary(path: path, storage: storage) let dictobj = KLDictionary(dictionary: dict, context: ctxt) return JSValue(object: dictobj, in: ctxt) case .failure(let err): CNLog(logLevel: .error, message: err.toString()) return JSValue(nullIn: ctxt) } } ctxt.set(name: "DictionaryStorage", function: allocDictSFunc) /* TableStorage */ let allocTableFunc: @convention(block) (_ storageval: JSValue, _ pathval: JSValue) -> JSValue = { (_ storageval: JSValue, _ pathval: JSValue) -> JSValue in guard let path = KLLibraryCompiler.valueToString(value: pathval) else { CNLog(logLevel: .error, message: "Unexpected path expression: \(String(describing: pathval.toString))") return JSValue(nullIn: ctxt) } guard let storage = self.allocateStorage(name: storageval, resource: res) else { CNLog(logLevel: .error, message: "Failed to get storage named: \(String(describing: storageval.toString))") return JSValue(nullIn: ctxt) } switch CNValuePath.pathExpression(string: path) { case .success(let path): let table = CNStorageTable(path: path, storage: storage) let tblobj = KLTable(table: table, context: ctxt) return JSValue(object: tblobj, in: ctxt) case .failure(let err): CNLog(logLevel: .error, message: err.toString()) return JSValue(nullIn: ctxt) } } ctxt.set(name: "TableStorage", function: allocTableFunc) /* MappingTable */ let allocMapTableFunc: @convention(block) (_ storageval: JSValue, _ pathval: JSValue) -> JSValue = { (_ storageval: JSValue, _ pathval: JSValue) -> JSValue in guard let path = KLLibraryCompiler.valueToString(value: pathval) else { CNLog(logLevel: .error, message: "Unexpected path expression: \(String(describing: pathval.toString))") return JSValue(nullIn: ctxt) } guard let storage = self.allocateStorage(name: storageval, resource: res) else { CNLog(logLevel: .error, message: "Failed to get storage named: \(String(describing: storageval.toString))") return JSValue(nullIn: ctxt) } switch CNValuePath.pathExpression(string: path) { case .success(let path): let table = CNStorageTable(path: path, storage: storage) let maptbl = CNMappingTable(sourceTable: table) let tblobj = KLMappingTable(mappingTable: maptbl, context: ctxt) return JSValue(object: tblobj, in: ctxt) case .failure(let err): CNLog(logLevel: .error, message: err.toString()) return JSValue(nullIn: ctxt) } } ctxt.set(name: "MappingTableStorage", function: allocMapTableFunc) /* Storage */ let allocStorageFunc: @convention(block) (_ nameval: JSValue) -> JSValue = { (_ nameval: JSValue) -> JSValue in var result: KLStorage? = nil if nameval.isString { if let name = nameval.toString() { if let storage = res.loadStorage(identifier: name) { result = KLStorage(storage: storage, context: ctxt) } } } if let obj = result { return JSValue(object: obj, in: ctxt) } else { return JSValue(nullIn: ctxt) } } ctxt.set(name: "Storage", function: allocStorageFunc) /* TextLine */ let textLineFunc: @convention(block) (_ str: JSValue) -> JSValue = { (_ str: JSValue) -> JSValue in let txt = CNTextLine(string: str.toString()) return JSValue(object: KLTextLine(text: txt, context: ctxt), in: ctxt) } ctxt.set(name: "TextLine", function: textLineFunc) /* TextSection */ let textSectionFunc: @convention(block) () -> JSValue = { () -> JSValue in let txt = CNTextSection() return JSValue(object: KLTextSection(text: txt, context: ctxt), in: ctxt) } ctxt.set(name: "TextSection", function: textSectionFunc) /* TextRecord */ let textRecordFunc: @convention(block) () -> JSValue = { () -> JSValue in let txt = CNTextRecord() return JSValue(object: KLTextRecord(text: txt, context: ctxt), in: ctxt) } ctxt.set(name: "TextRecord", function: textRecordFunc) /* TextTable */ let textTableFunc: @convention(block) () -> JSValue = { () -> JSValue in let txt = CNTextTable() return JSValue(object: KLTextTable(text: txt, context: ctxt), in: ctxt) } ctxt.set(name: "TextTable", function: textTableFunc) /* Collection */ let collectionFunc: @convention(block) () -> JSValue = { () -> JSValue in let newcol = CNCollection() return JSValue(object: KLCollection(collection: newcol, context: ctxt), in: ctxt) } ctxt.set(name: "CollectionData", function: collectionFunc) } private func importBuiltinLibrary(context ctxt: KEContext, console cons: CNConsole, config conf: KEConfig) { /* Contacts.js depends on the Process.js */ let libnames = ["Object", "Array", "Debug", "File", "Graphics", "Curses", "Math", "Process", "String", "Turtle", "Contacts"] do { for libname in libnames { if let url = CNFilePath.URLForResourceFile(fileName: libname, fileExtension: "js", subdirectory: "Library", forClass: KLLibraryCompiler.self) { let script = try String(contentsOf: url, encoding: .utf8) let _ = compileStatement(context: ctxt, statement: script, sourceFile: url, console: cons, config: conf) } else { cons.error(string: "Built-in script \"\(libname)\" is not found.") } } } catch { cons.error(string: "Failed to read built-in script in KiwiLibrary") } } private func allocateStorage(name nameval: JSValue, resource res: KEResource) -> CNStorage? { if let name = KLLibraryCompiler.valueToString(value: nameval) { if let storage = res.loadStorage(identifier: name) { return storage } } return nil } private func defineThreadFunction(context ctxt: KEContext, resource res: KEResource, processManager procmgr: CNProcessManager, terminalInfo terminfo: CNTerminalInfo, environment env: CNEnvironment, console cons: CNConsole, config conf: KEConfig) -> Bool { /* Thread */ let thfunc: @convention(block) (_ pathval: JSValue, _ inval: JSValue, _ outval: JSValue, _ errval: JSValue) -> JSValue = { (_ pathval: JSValue, _ inval: JSValue, _ outval: JSValue, _ errval: JSValue) -> JSValue in let launcher = KLThreadLauncher(context: ctxt, resource: res, processManager: procmgr, terminalInfo: terminfo, environment: env, config: conf) return launcher.run(path: pathval, input: inval, output: outval, error: errval) } ctxt.set(name: "Thread", function: thfunc) /* _allocateThread */ let runfunc: @convention(block) (_ pathval: JSValue, _ inval: JSValue, _ outval: JSValue, _ errval: JSValue) -> JSValue = { (_ pathval: JSValue, _ inval: JSValue, _ outval: JSValue, _ errval: JSValue) -> JSValue in let launcher = KLThreadLauncher(context: ctxt, resource: res, processManager: procmgr, terminalInfo: terminfo, environment: env, config: conf) return launcher.run(path: pathval, input: inval, output: outval, error: errval) } ctxt.set(name: "_allocateThread", function: runfunc) return true } private func defineDatabase(context ctxt: KEContext, console cons: CNConsole, config conf: KEConfig) { /* ContactDatabase */ let contact = KLContactDatabase(context: ctxt) ctxt.set(name: "Contacts", object: contact) } #if os(OSX) private enum Application { case textEdit case safari case other } private func applicationKind(application app: NSRunningApplication) -> Application { var result: Application = .other if let ident = app.bundleIdentifier { switch ident { case "com.apple.TextEdit": result = .textEdit case "com.apple.Safari": result = .safari default: break } } return result } #endif private class func valueToString(value val: JSValue) -> String? { if val.isString { return val.toString() } else { return nil } } private class func valueToURL(value val: JSValue) -> URL? { if val.isString { if let str = val.toString() { return URL(string: str) } } else if val.isObject { if let obj = val.toObject() as? KLURL { return obj.url } } return nil } private class func valueToURLs(URLvalues urlval: JSValue, console cons: CNConsole) -> Array<URL>? { if urlval.isArray { var result: Array<URL> = [] for val in urlval.toArray() { if let url = anyToURL(anyValue: val) { result.append(url) } else { let classname = type(of: val) cons.error(string: "Failed to get url: \(classname)\n") return nil } } return result } cons.error(string: "Invalid URL parameters\n") return nil } private class func valueToFileType(type tval: JSValue) -> CNFileType? { if let num = tval.toNumber() { if let sel = CNFileType(rawValue: num.intValue) { return sel } } return nil } private static func valueToExtensions(extensions tval: JSValue) -> Array<String>? { if tval.isArray { var types: Array<String> = [] if let vals = tval.toArray() { for elm in vals { if let str = elm as? String { types.append(str) } else { return nil } } } return types } return nil } private class func anyToURL(anyValue val: Any) -> URL? { var result: URL? = nil if let urlobj = val as? KLURL { if let url = urlobj.url { result = url } } else if let urlval = val as? JSValue { if let urlobj = urlval.toObject() as? KLURL { if let url = urlobj.url { result = url } } else if urlval.isString { if let str = urlval.toString() { result = URL(fileURLWithPath: str) } } } return result } #if os(OSX) private class func anyToProcess(anyValue val: Any) -> KLProcessProtocol? { if let proc = val as? KLProcessProtocol { return proc } else if let procval = val as? JSValue { if procval.isObject { if let procobj = procval.toObject() { return anyToProcess(anyValue: procobj) } } } return nil } #endif }
lgpl-2.1
3ec245fbb64a1c1ad7e790d433b1df91
32.917944
263
0.665905
3.313513
false
false
false
false
jensmeder/DarkLightning
Examples/Messenger/OSX/Sources/RootViewController.swift
1
1792
// // RootViewController.swift // OSX // // Created by Jens Meder on 16.05.17. // // import Cocoa import DarkLightning class RootViewController: NSViewController, RootViewDelegate, DaemonDelegate, DeviceDelegate { private var device: Device? private weak var rootView: RootView? // MARK: Init required init() { super.init(nibName: nil, bundle: nil)! } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: View lifecycle override func loadView() { weak var weakSelf = self let view = RootView(frame: NSRect(x: 0, y: 0, width: 600, height: 400), delegate: weakSelf!) view.setup() self.view = view self.rootView = view } // MARK: RootViewDelegate func sendMessage(message: String) { device?.writeData(data: message.data(using: .utf8)!) } // MARK: DaemonDelegate func daemon(_ daemon: Daemon, didAttach device: Device) { if self.device == nil { self.device = device device.connect() } } func daemon(_ daemon: Daemon, didDetach device: Device) { if let aDevice = self.device, device.isEqual(obj: aDevice) { self.device = nil } } // MARK: DeviceDelegate public func device(didConnect device: Device) { } public func device(didFailToConnect device: Device) { } public func device(didDisconnect device: Device) { } public func device(_ device: Device, didReceiveData data: OOData) { let message = String(data: data.dataValue, encoding: .utf8)! rootView?.appendMessage(message:message) } }
mit
770bb685a38ea0aba0a2fbda4b3285d0
22.578947
100
0.586496
4.360097
false
false
false
false
austinzheng/swift
test/Interpreter/object.swift
70
371
// RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test func test() { var d1 = Dictionary<String, Int>() var d2 = Dictionary<String, Int>() var d1_alias = d1 // Dictionary is no longer a class type // if d1 !== d2 { print("good") // } // if d1 === d1_alias { print("also good") // } } test() // CHECK: good // CHECK: also good
apache-2.0
ca6ca3c920da61194bf02f82bb1b84cb
17.55
48
0.587601
2.853846
false
true
false
false
yoichitgy/SwinjectMVVMExample_ForBlog
Carthage/Checkouts/Swinject/Swinject/OSX/SwinjectStoryboard.swift
1
5046
// // SwinjectStoryboard.swift // Swinject // // Created by Yoichi Tagaya on 8/1/15. // Copyright © 2015 Swinject Contributors. All rights reserved. // import AppKit /// The `SwinjectStoryboard` provides the features defined by its super class `NSStoryboard`, /// with dependencies of view or window controllers injected. /// /// To specify a registration name of a view or window controller registered to the `Container` as a service type, /// add a user defined runtime attribute with the following settings: /// /// - Key Path: `swinjectRegistrationName` /// - Type: String /// - Value: Registration name to the `Container` /// /// in User Defined Runtime Attributes section on Indentity Inspector pane. /// If no name is supplied to the registration, no runtime attribute should be specified. public class SwinjectStoryboard: _SwinjectStoryboardBase, SwinjectStoryboardType { /// A shared container used by SwinjectStoryboard instances that are instantiated without specific containers. /// /// Typical usecases of this property are: /// - Implicit instantiation of UIWindow and its root view controller from "Main" storyboard. /// - Storyboard references to transit from a storyboard to another. public static var defaultContainer = Container() // Boxing to workaround a runtime error [Xcode 7.1.1 and Xcode 7.2 beta 4] // If container property is Resolvable type and a ResolverType instance is assigned to the property, // the program crashes by EXC_BAD_ACCESS, which looks a bug of Swift. private var container: Box<ResolverType>! /// Do NOT call this method explicitly. It is designed to be called by the runtime. public override class func initialize() { struct Static { static var token: dispatch_once_t = 0 } dispatch_once(&Static.token) { if SwinjectStoryboard.respondsToSelector("setup") { SwinjectStoryboard.performSelector("setup") } } } private override init() { super.init() } /// Creates the new instance of `SwinjectStoryboard`. This method is used instead of an initializer. /// /// - Parameters: /// - name: The name of the storyboard resource file without the filename extension. /// - bundle: The bundle containing the storyboard file and its resources. Specify nil to use the main bundle. /// - container: The container with registrations of the view or window controllers in the storyboard and their dependencies. /// The shared singleton container `SwinjectStoryboard.defaultContainer` is used if no container is passed. /// /// - Returns: The new instance of `SwinjectStoryboard`. public class func create( name name: String, bundle storyboardBundleOrNil: NSBundle?, container: ResolverType = SwinjectStoryboard.defaultContainer) -> SwinjectStoryboard { // Use this factory method to create an instance because the initializer of NSStoryboard is "not inherited". let storyboard = SwinjectStoryboard._create(name, bundle: storyboardBundleOrNil) storyboard.container = Box(container) return storyboard } /// Instantiates the view or window controller with the specified identifier. /// The view or window controller and its child controllers have their dependencies injected /// as specified in the `Container` passed to the initializer of the `SwinjectStoryboard`. /// /// - Parameter identifier: The identifier set in the storyboard file. /// /// - Returns: The instantiated view or window controller with its dependencies injected. public override func instantiateControllerWithIdentifier(identifier: String) -> AnyObject { let controller = super.instantiateControllerWithIdentifier(identifier) injectDependency(controller) return controller } private func injectDependency(controller: AnyObject) { let registrationName = (controller as! RegistrationNameAssociatable).swinjectRegistrationName // Xcode 7.1 workaround for Issue #10. This workaround is not necessary with Xcode 7. // The actual controller type is distinguished by the dynamic type name in `nameWithActualType`. // // If a future update of Xcode fixes the problem, replace the resolution with the following code and fix registerForStoryboard too: // container.resolve(controller.dynamicType, argument: viewController as Container.Controller, name: registrationName) let nameWithActualType = String(reflecting: controller.dynamicType) + ":" + (registrationName ?? "") container.value.resolve(Container.Controller.self, name: nameWithActualType, argument: controller as Container.Controller) if let viewController = controller as? NSViewController { for child in viewController.childViewControllers { injectDependency(child) } } } }
mit
0da12c632431018af1079746bce99b49
48.460784
139
0.703469
5.32735
false
false
false
false
domenicosolazzo/practice-swift
Apps/EnhancedStormy/Stormy/DailyWeather.swift
1
2383
// // DailyWeather.swift // Stormy // // Created by Pasan Premaratne on 6/18/15. // Copyright (c) 2015 Treehouse. All rights reserved. // import Foundation import UIKit struct DailyWeather { let maxTemperature: Int? let minTemperature: Int? let humidity: Int? let precipChance: Int? let summary: String? var icon: UIImage? = UIImage(named: "default.png") var largeIcon: UIImage? = UIImage(named: "default_large.png") var sunriseTime: String? var sunsetTime: String? var day: String? let dateFormatter = DateFormatter() init(dailyWeatherDict: [String: AnyObject]) { maxTemperature = dailyWeatherDict["temperatureMax"] as? Int minTemperature = dailyWeatherDict["temperatreMin"] as? Int if let humidityFloat = dailyWeatherDict["humidity"] as? Double { humidity = Int(humidityFloat * 100) } else { humidity = nil } if let precipChanceFloat = dailyWeatherDict["precipProbability"] as? Double { precipChance = Int(precipChanceFloat * 100) } else { precipChance = nil } summary = dailyWeatherDict["summary"] as? String if let iconString = dailyWeatherDict["icon"] as? String, let iconEnum = Icon(rawValue: iconString) { (icon, largeIcon) = iconEnum.toImage() } if let sunriseDate = dailyWeatherDict["sunriseTime"] as? Double { sunriseTime = timeStringFromUnixTime(sunriseDate) } if let sunsetDate = dailyWeatherDict["sunsetTime"] as? Double { sunsetTime = timeStringFromUnixTime(sunsetDate) } if let time = dailyWeatherDict["time"] as? Double { day = dayStringFromTime(time) } } func timeStringFromUnixTime(_ unixTime: Double) -> String { let date = Date(timeIntervalSince1970: unixTime) // Returns date formatted as 12 hour time. dateFormatter.dateFormat = "hh:mm a" return dateFormatter.string(from: date) } func dayStringFromTime(_ unixTime: Double) -> String { let date = Date(timeIntervalSince1970: unixTime) dateFormatter.locale = Locale(identifier: Locale.current.identifier) dateFormatter.dateFormat = "EEEE" return dateFormatter.string(from: date) } }
mit
3169904964712becee420744d0e5695a
32.56338
85
0.6282
4.445896
false
false
false
false
evan0322/WorkoutCompanion
WorkoutCompanion/WorkoutCompanion/Swizzling.swift
1
3723
// // Swizzling.swift // WorkoutCompanion // // Created by Wei Xie on 2016-07-29. // Copyright © 2016 WEI.XIE. All rights reserved. // //Do the magic work here import Foundation import UIKit extension UIView { func addBorder(edges edges: UIRectEdge, colour: UIColor = UIColor.white, thickness: CGFloat = 1) -> [UIView] { var borders = [UIView]() func border() -> UIView { let border = UIView(frame: CGRect.zero) border.backgroundColor = colour border.translatesAutoresizingMaskIntoConstraints = false return border } if edges.contains(.top) || edges.contains(.all) { let top = border() addSubview(top) addConstraints( NSLayoutConstraint.constraints(withVisualFormat: "V:|-(0)-[top(==thickness)]", options: [], metrics: ["thickness": thickness], views: ["top": top])) addConstraints( NSLayoutConstraint.constraints(withVisualFormat: "H:|-(0)-[top]-(0)-|", options: [], metrics: nil, views: ["top": top])) borders.append(top) } if edges.contains(.left) || edges.contains(.all) { let left = border() addSubview(left) addConstraints( NSLayoutConstraint.constraints(withVisualFormat: "H:|-(0)-[left(==thickness)]", options: [], metrics: ["thickness": thickness], views: ["left": left])) addConstraints( NSLayoutConstraint.constraints(withVisualFormat: "V:|-(0)-[left]-(0)-|", options: [], metrics: nil, views: ["left": left])) borders.append(left) } if edges.contains(.right) || edges.contains(.all) { let right = border() addSubview(right) addConstraints( NSLayoutConstraint.constraints(withVisualFormat: "H:[right(==thickness)]-(0)-|", options: [], metrics: ["thickness": thickness], views: ["right": right])) addConstraints( NSLayoutConstraint.constraints(withVisualFormat: "V:|-(0)-[right]-(0)-|", options: [], metrics: nil, views: ["right": right])) borders.append(right) } if edges.contains(.bottom) || edges.contains(.all) { let bottom = border() addSubview(bottom) addConstraints( NSLayoutConstraint.constraints(withVisualFormat: "V:[bottom(==thickness)]-(0)-|", options: [], metrics: ["thickness": thickness], views: ["bottom": bottom])) addConstraints( NSLayoutConstraint.constraints(withVisualFormat: "H:|-(0)-[bottom]-(0)-|", options: [], metrics: nil, views: ["bottom": bottom])) borders.append(bottom) } return borders } func addDropShadowToView(targetView:UIView? ){ targetView!.layer.masksToBounds = false targetView!.layer.shadowColor = Constants.themeColorBlack.cgColor; targetView!.layer.shadowOpacity = 1.0 } } extension Date { func toString() -> String { let formatter = DateFormatter() formatter.dateFormat = "MM/dd/yy" return formatter.string(from: self) } }
mit
6908d69f29fdffc0268461f899acc87b
32.232143
114
0.500537
5.457478
false
false
false
false
y0ke/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/ActorCore/Providers/Storage/FMDBKeyValue.swift
2
4231
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation @objc class FMDBKeyValue: NSObject, ARKeyValueStorage { var db :FMDatabase! let databasePath: String let tableName: String let queryCreate: String let queryItem: String let queryItems: String let queryAll: String let queryAdd: String let queryDelete: String let queryDeleteAll: String var isTableChecked: Bool = false init(databasePath: String, tableName: String) { self.databasePath = databasePath self.tableName = tableName // Queries self.queryCreate = "CREATE TABLE IF NOT EXISTS " + tableName + " (" + "\"ID\" INTEGER NOT NULL, " + "\"BYTES\" BLOB NOT NULL, " + "PRIMARY KEY (\"ID\"));" self.queryItem = "SELECT \"BYTES\" FROM " + tableName + " WHERE \"ID\" = ?;" self.queryItems = "SELECT \"ID\", \"BYTES\" FROM " + tableName + " WHERE \"ID\" in ?;" self.queryAll = "SELECT \"ID\", \"BYTES\" FROM " + tableName + ";" self.queryAdd = "REPLACE INTO " + tableName + " (\"ID\", \"BYTES\") VALUES (?, ?);" self.queryDelete = "DELETE FROM " + tableName + " WHERE \"ID\" = ?;" self.queryDeleteAll = "DELETE FROM " + tableName + ";" super.init() } private func checkTable() { if (isTableChecked) { return } isTableChecked = true self.db = FMDatabase(path: databasePath) self.db.open() if (!db.tableExists(tableName)) { db.executeUpdate(queryCreate) } } func addOrUpdateItems(values: JavaUtilList!) { checkTable() db.beginTransaction() for i in 0..<values.size() { let record = values.getWithInt(i) as! ARKeyValueRecord db.executeUpdate(queryAdd, record.getId().toNSNumber(),record.getData().toNSData()) } db.commit() } func addOrUpdateItemWithKey(key: jlong, withData data: IOSByteArray!) { checkTable() db.beginTransaction() db.executeUpdate(queryAdd, key.toNSNumber(), data!.toNSData()) db.commit() } func removeItemsWithKeys(keys: IOSLongArray!) { checkTable() db.beginTransaction() for i in 0..<keys.length() { let key = keys.longAtIndex(UInt(i)); db.executeUpdate(queryDelete, key.toNSNumber()) } db.commit() } func removeItemWithKey(key: jlong) { checkTable() db.beginTransaction() db.executeUpdate(queryDelete, key.toNSNumber()) db.commit() } func loadItemWithKey(key: jlong) -> IOSByteArray! { checkTable() let result = db.dataForQuery(queryItem, key.toNSNumber()) if (result == nil) { return nil } return result.toJavaBytes() } func loadAllItems() -> JavaUtilList! { checkTable() let res = JavaUtilArrayList() if let result = db.executeQuery(queryAll) { while(result.next()) { res.addWithId(ARKeyValueRecord(key: jlong(result.longLongIntForColumn("ID")), withData: result.dataForColumn("BYTES").toJavaBytes())) } } return res } func loadItems(keys: IOSLongArray!) -> JavaUtilList! { checkTable() // Converting to NSNumbers var ids = [NSNumber]() for i in 0..<keys.length() { ids.append(keys.longAtIndex(UInt(i)).toNSNumber()) } let res = JavaUtilArrayList() if let result = db.executeQuery(queryItems, ids) { while(result.next()) { // TODO: Optimize lookup res.addWithId(ARKeyValueRecord(key: jlong(result.longLongIntForColumn("ID")), withData: result.dataForColumn("BYTES").toJavaBytes())) } } return res } func clear() { checkTable() db.beginTransaction() db.executeUpdate(queryDeleteAll) db.commit() } }
agpl-3.0
f76ef693da0fadbd31a9d2df5f4d8205
27.986301
149
0.544788
4.770011
false
false
false
false
zacharyclaysmith/SwiftBindingUI
SwiftBindingUI/BindableSwitch.swift
1
2352
// // File.swift // SwiftBindingUI // // Created by Zachary Smith on 2/27/15. // Copyright (c) 2015 Scal.io. All rights reserved. // import Foundation import UIKit import SwiftBinding public class BindableSwitch:UISwitch, PHiddenBindable{ private var _onBinding:BindableValue<Bool>? //DEPRECATED public var bindableValue:BindableValue<Bool>?{ get{ return _onBinding } set(newValue){ _onBinding?.removeListener(self) _onBinding = newValue _onBinding?.addListener(self, alertNow: true, listener:valueChanged) } } public var onBinding:BindableValue<Bool>?{ get{ return _onBinding } set(newValue){ _onBinding?.removeListener(self) _onBinding = newValue _onBinding?.addListener(self, alertNow: true, listener:valueChanged) } } override init(frame: CGRect) { super.init(frame: frame) self.addTarget(self, action: "switchChanged", forControlEvents: UIControlEvents.ValueChanged) } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.addTarget(self, action: "switchChanged", forControlEvents: UIControlEvents.ValueChanged) } private func valueChanged(newValue:Bool){ if(_onBinding != nil && _onBinding!.value != self.on){ self.on = newValue } } public func switchChanged(){ if(_onBinding != nil && _onBinding!.value != self.on){ _onBinding!.value = self.on } } deinit{ _onBinding?.removeListener(self) _hiddenBinding?.removeListener(self) } private var _hiddenBinding:BindableValue<Bool>? public var hiddenBinding:BindableValue<Bool>?{ get{ return _hiddenBinding } set(newValue){ _hiddenBinding?.removeListener(self) _hiddenBinding = newValue _hiddenBinding?.addListener(self, alertNow: true, listener:hiddenBinding_valueChanged) } } private func hiddenBinding_valueChanged(newValue:Bool){ self.hidden = newValue } }
mit
de9d338c7cc61c916c8b3734f13a55cb
24.301075
101
0.572279
4.809816
false
false
false
false
DenHeadless/DTCollectionViewManager
Sources/DTCollectionViewManager/DTCollectionViewDragDelegate.swift
1
5636
// // DTCollectionViewDragDelegate.swift // DTCollectionViewManager // // Created by Denys Telezhkin on 01.09.17. // Copyright © 2017 Denys Telezhkin. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit import DTModelStorage #if os(iOS) /// Object, that implements `UICollectionViewDragDelegate` methods for `DTCollectionViewManager`. open class DTCollectionViewDragDelegate : DTCollectionViewDelegateWrapper, UICollectionViewDragDelegate { override func delegateWasReset() { collectionView?.dragDelegate = nil collectionView?.dragDelegate = self } /// Implementation of `UICollectionViewDragDelegate` protocol. open func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] { if let items = perform4ArgumentCellReaction(.itemsForBeginningDragSessionAtIndexPath, argument: session, location: indexPath, provideCell: true) as? [UIDragItem] { return items } return (delegate as? UICollectionViewDragDelegate)?.collectionView(collectionView, itemsForBeginning: session, at:indexPath) ?? [] } /// Implementation of `UICollectionViewDragDelegate` protocol. open func collectionView(_ collectionView: UICollectionView, itemsForAddingTo session: UIDragSession, at indexPath: IndexPath, point: CGPoint) -> [UIDragItem] { if let items = perform5ArgumentCellReaction(.itemsForAddingToDragSessionAtIndexPath, argumentOne: session, argumentTwo: point, location: indexPath, provideCell: true) as? [UIDragItem] { return items } return (delegate as? UICollectionViewDragDelegate)?.collectionView?(collectionView, itemsForAddingTo: session, at: indexPath, point: point) ?? [] } /// Implementation of `UICollectionViewDragDelegate` protocol. open func collectionView(_ collectionView: UICollectionView, dragPreviewParametersForItemAt indexPath: IndexPath) -> UIDragPreviewParameters? { if let reaction = cellReaction(.dragPreviewParametersForItemAtIndexPath, location: indexPath) { return performNillableCellReaction(reaction, location: indexPath, provideCell: true) as? UIDragPreviewParameters } return (delegate as? UICollectionViewDragDelegate)?.collectionView?(collectionView, dragPreviewParametersForItemAt: indexPath) } /// Implementation of `UICollectionViewDragDelegate` protocol. open func collectionView(_ collectionView: UICollectionView, dragSessionWillBegin session: UIDragSession) { _ = performNonCellReaction(.dragSessionWillBegin, argument: session) (delegate as? UICollectionViewDragDelegate)?.collectionView?(collectionView, dragSessionWillBegin: session) } /// Implementation of `UICollectionViewDragDelegate` protocol. open func collectionView(_ collectionView: UICollectionView, dragSessionDidEnd session: UIDragSession) { _ = performNonCellReaction(.dragSessionDidEnd, argument: session) (delegate as? UICollectionViewDragDelegate)?.collectionView?(collectionView, dragSessionDidEnd: session) } /// Implementation of `UICollectionViewDragDelegate` protocol. open func collectionView(_ collectionView: UICollectionView, dragSessionAllowsMoveOperation session: UIDragSession) -> Bool { if let allows = performNonCellReaction(.dragSessionAllowsMoveOperation, argument: session) as? Bool { return allows } return (delegate as? UICollectionViewDragDelegate)?.collectionView?(collectionView, dragSessionAllowsMoveOperation: session) ?? true } /// Implementation of `UICollectionViewDragDelegate` protocol. open func collectionView(_ collectionView: UICollectionView, dragSessionIsRestrictedToDraggingApplication session: UIDragSession) -> Bool { if let allows = performNonCellReaction(.dragSessionIsRestrictedToDraggingApplication, argument: session) as? Bool { return allows } return (delegate as? UICollectionViewDragDelegate)?.collectionView?(collectionView, dragSessionIsRestrictedToDraggingApplication: session) ?? false } } #endif
mit
f3b155d2d4af7d2c2d1e97bdd402d2ec
55.35
164
0.707897
5.937829
false
false
false
false
juliantejera/JTDataStructures
Pods/Nimble/Sources/Nimble/Matchers/SatisfyAllOf.swift
7
4018
import Foundation /// A Nimble matcher that succeeds when the actual value matches with all of the matchers /// provided in the variable list of matchers. public func satisfyAllOf<T, U>(_ matchers: U...) -> Predicate<T> where U: Matcher, U.ValueType == T { return satisfyAllOf(matchers) } /// Deprecated. Please use `satisfyAnyOf<T>(_) -> Predicate<T>` instead. internal func satisfyAllOf<T, U>(_ matchers: [U]) -> Predicate<T> where U: Matcher, U.ValueType == T { return NonNilMatcherFunc<T> { actualExpression, failureMessage in let postfixMessages = NSMutableArray() var matches = true for matcher in matchers { if try matcher.doesNotMatch(actualExpression, failureMessage: failureMessage) { matches = false } postfixMessages.add(NSString(string: "{\(failureMessage.postfixMessage)}")) } failureMessage.postfixMessage = "match all of: " + postfixMessages.componentsJoined(by: ", and ") if let actualValue = try actualExpression.evaluate() { failureMessage.actualValue = "\(actualValue)" } return matches }.predicate } internal func satisfyAllOf<T>(_ predicates: [Predicate<T>]) -> Predicate<T> { return Predicate { actualExpression in var postfixMessages = [String]() var matches = true for predicate in predicates { let result = try predicate.satisfies(actualExpression) if result.toBoolean(expectation: .toNotMatch) { matches = false } postfixMessages.append("{\(result.message.expectedMessage)}") } var msg: ExpectationMessage if let actualValue = try actualExpression.evaluate() { msg = .expectedCustomValueTo( "match all of: " + postfixMessages.joined(separator: ", and "), "\(actualValue)" ) } else { msg = .expectedActualValueTo( "match all of: " + postfixMessages.joined(separator: ", and ") ) } return PredicateResult( bool: matches, message: msg ) }.requireNonNil } public func && <T>(left: Predicate<T>, right: Predicate<T>) -> Predicate<T> { return satisfyAllOf(left, right) } #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) extension NMBObjCMatcher { @objc public class func satisfyAllOfMatcher(_ matchers: [NMBMatcher]) -> NMBPredicate { return NMBPredicate { actualExpression in if matchers.isEmpty { return NMBPredicateResult( status: NMBPredicateStatus.fail, message: NMBExpectationMessage( fail: "satisfyAllOf must be called with at least one matcher" ) ) } var elementEvaluators = [Predicate<NSObject>]() for matcher in matchers { let elementEvaluator = Predicate<NSObject> { expression in if let predicate = matcher as? NMBPredicate { // swiftlint:disable:next line_length return predicate.satisfies({ try! expression.evaluate() }, location: actualExpression.location).toSwift() } else { let failureMessage = FailureMessage() // swiftlint:disable:next line_length let success = matcher.matches({ try! expression.evaluate() }, failureMessage: failureMessage, location: actualExpression.location) return PredicateResult(bool: success, message: failureMessage.toExpectationMessage()) } } elementEvaluators.append(elementEvaluator) } return try! satisfyAllOf(elementEvaluators).satisfies(actualExpression).toObjectiveC() } } } #endif
mit
8e60fd77909f53c6f3b0886cf50bcf48
38.782178
154
0.580139
5.42973
false
false
false
false
Greenshire/Calibre
Calibre Example/ProductsReducer.swift
1
948
// // ProductsReducer.swift // Calibre // // Created by Jeremy Tregunna on 9/6/16. // Copyright © 2016 Greenshire, Inc. All rights reserved. // import Calibre struct ProductsReducer: Reducer { func handleAction(action: Action, state: [Product]?) -> [Product] { var state = state ?? [] switch action { case let add as AddProductAction: // Only add a product if it doesn't already exist if !state.contains({ $0.name == add.name }) { let formatter = NSNumberFormatter() formatter.numberStyle = .CurrencyStyle let formattedPrice = formatter.numberFromString(add.price) ?? NSNumber(int: 0) let price = Int(round(formattedPrice.doubleValue * 100.0)) let product = Product(name: add.name, price: price) state += [product] } default: break } return state } }
mit
a01b41a3f3d1fe3aaf01a549e8c3a378
29.548387
94
0.576558
4.384259
false
false
false
false
peterfennema/AmazonSwiftStarter
AmazonSwiftStarter/AMZRemoteService.swift
1
12223
// // AMZRemoteService.swift // AmazonSwiftStarter // // Created by Peter Fennema on 16/02/16. // Copyright © 2016 Peter Fennema. All rights reserved. // import Foundation import AWSCore import AWSDynamoDB import AWSS3 class AMZRemoteService { // MARK: - RemoteService Properties var hasCurrentUserIdentity: Bool { return persistentUserId != nil } var currentUser: UserData? // MARK: - Properties var persistentUserId: String? { set { NSUserDefaults.standardUserDefaults().setValue(newValue, forKey: "userId") NSUserDefaults.standardUserDefaults().synchronize() } get { return NSUserDefaults.standardUserDefaults().stringForKey("userId") } } private (set) var identityProvider: AWSCognitoCredentialsProvider? private var deviceDirectoryForUploads: NSURL? private var deviceDirectoryForDownloads: NSURL? private static var sharedInstance: AMZRemoteService? // MARK: - Functions static func defaultService() -> RemoteService { if sharedInstance == nil { sharedInstance = AMZRemoteService() sharedInstance!.configure() } return sharedInstance! } func configure() { identityProvider = AWSCognitoCredentialsProvider( regionType: AMZConstants.COGNITO_REGIONTYPE, identityPoolId: AMZConstants.COGNITO_IDENTITY_POOL_ID) let configuration = AWSServiceConfiguration( region: AMZConstants.DEFAULT_SERVICE_REGION, credentialsProvider: identityProvider) AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration // The api I am using for uploading to and downloading from S3 (AWSS3TransferManager)can not deal with NSData directly, but uses files. // I need to create tmp directories for these files. deviceDirectoryForUploads = createLocalTmpDirectory("upload") deviceDirectoryForDownloads = createLocalTmpDirectory("download") } private func createLocalTmpDirectory(let directoryName: String) -> NSURL? { do { let url = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(directoryName) try NSFileManager.defaultManager().createDirectoryAtURL( url, withIntermediateDirectories: true, attributes: nil) return url } catch let error as NSError { print("Creating \(directoryName) directory failed. Error: \(error)") return nil } } // This is where the saving to S3 (image) and DynamoDB (data) is done. func saveAMZUser(user: AMZUser, completion: ErrorResultBlock) { precondition(user.userId != nil, "You should provide a user object with a userId when saving a user") let mapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper() // We create a task that will save the user to DynamoDB // This works because AMZUser extends AWSDynamoDBObjectModel and conforms to AWSDynamoDBModeling let saveToDynamoDBTask: AWSTask = mapper.save(user) // If there is no imageData we only have to save to DynamoDB if user.imageData == nil { saveToDynamoDBTask.continueWithBlock({ (task) -> AnyObject? in completion(error: task.error) return nil }) } else { // We have to save data to DynamoDB, and the image to S3 saveToDynamoDBTask.continueWithSuccessBlock({ (task) -> AnyObject? in // An example of the AWSTask api. We return a task and continueWithBlock is called on this task. return self.createUploadImageTask(user) }).continueWithBlock({ (task) -> AnyObject? in completion(error: task.error) return nil }) } } private func createUploadImageTask(user: UserData) -> AWSTask { guard let userId = user.userId else { preconditionFailure("You should provide a user object with a userId when uploading a user image") } guard let imageData = user.imageData else { preconditionFailure("You are trying to create an UploadImageTask, but the user has no imageData") } // Save the image as a file. The filename is the userId let fileName = "\(userId).jpg" let fileURL = deviceDirectoryForUploads!.URLByAppendingPathComponent(fileName) imageData.writeToFile(fileURL.path!, atomically: true) // Create a task to upload the file let uploadRequest = AWSS3TransferManagerUploadRequest() uploadRequest.body = fileURL uploadRequest.key = fileName uploadRequest.bucket = AMZConstants.S3BUCKET_USERS let transferManager = AWSS3TransferManager.defaultS3TransferManager() return transferManager.upload(uploadRequest) } private func createDownloadImageTask(userId: String) -> AWSTask { // The location where the downloaded file has to be saved on the device let fileName = "\(userId).jpg" let fileURL = deviceDirectoryForDownloads!.URLByAppendingPathComponent(fileName) // Create a task to download the file let downloadRequest = AWSS3TransferManagerDownloadRequest() downloadRequest.downloadingFileURL = fileURL downloadRequest.bucket = AMZConstants.S3BUCKET_USERS downloadRequest.key = fileName let transferManager = AWSS3TransferManager.defaultS3TransferManager() return transferManager.download(downloadRequest) } } // MARK: - RemoteService extension AMZRemoteService: RemoteService { func createCurrentUser(userData: UserData? , completion: ErrorResultBlock ) { precondition(currentUser == nil, "currentUser should not exist when createCurrentUser(..) is called") precondition(userData == nil || userData!.userId == nil, "You can not create a user with a given userId. UserId's are assigned automatically") precondition(persistentUserId == nil, "A persistent userId should not yet exist") guard let identityProvider = identityProvider else { preconditionFailure("No identity provider available, did you forget to call configure() before using AMZRemoteService?") } // This covers the scenario that an app was deleted and later reinstalled. // The goal is to create a new identity and a new user profile for this use case. // By default, Cognito stores a Cognito identity in the keychain. // This identity survives app uninstalls, so there can be an identity left from a previous app install. // When we detect this scenario we remove all data from the keychain, so we can start from scratch. if identityProvider.identityId != nil { identityProvider.clearKeychain() assert(identityProvider.identityId == nil) } // Create a new Cognito identity let task: AWSTask = identityProvider.getIdentityId() task.continueWithBlock { (task) -> AnyObject? in if let error = task.error { completion(error: error) } else { // The new cognito identity token is now stored in the keychain. // Create a new empty user object of type AMZUser var newUser = AMZUser() // Copy the data from the parameter userData if let userData = userData { newUser.updateWithData(userData) } // create a unique ID for the new user newUser.userId = NSUUID().UUIDString // Now save the data on AWS. This will save the image on S3, the other data in DynamoDB self.saveAMZUser(newUser) { (error) -> Void in if let error = error { completion(error: error) } else { // Here we can be certain that the user was saved on AWS, so we set the local user instance self.currentUser = newUser self.persistentUserId = newUser.userId completion(error: nil) } } } return nil } } func updateCurrentUser(userData: UserData, completion: ErrorResultBlock) { guard var currentUser = currentUser else { preconditionFailure("currentUser should already exist when updateCurrentUser(..) is called") } precondition(userData.userId == nil || userData.userId == currentUser.userId, "Updating current user with a different userId is not allowed") precondition(persistentUserId != nil, "A persistent userId should exist") // create a new empty user var updatedUser = AMZUser() // apply the new userData updatedUser.updateWithData(userData) // restore the userId of the current user updatedUser.userId = currentUser.userId // If there are no changes, there is no need to update. if updatedUser.isEqualTo(currentUser) { completion(error: nil) return } self.saveAMZUser(updatedUser) { (error) -> Void in if let error = error { completion(error: error) } else { // Here we can be certain that the user was saved on AWS, so we update the local user property currentUser.updateWithData(updatedUser) completion(error: nil) } } } func fetchCurrentUser(completion: UserDataResultBlock ) { precondition(persistentUserId != nil, "A persistent userId should exist") // Task to download the image let downloadImageTask: AWSTask = createDownloadImageTask(persistentUserId!) // Task to fetch the DynamoDB data let mapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper() let loadFromDynamoDBTask: AWSTask = mapper.load(AMZUser.self, hashKey: persistentUserId!, rangeKey: nil) // Download the image downloadImageTask.continueWithBlock { (imageTask) -> AnyObject? in var didDownloadImage = false if let error = imageTask.error { // If there is an error we will ignore it, it's not fatal. Maybe there is no user image. print("Error downloading image: \(error)") } else { didDownloadImage = true } // Download the data from DynamoDB loadFromDynamoDBTask.continueWithBlock({ (dynamoTask) -> AnyObject? in if let error = dynamoTask.error { completion(userData: nil, error: error) } else { if let user = dynamoTask.result as? AMZUser { if didDownloadImage { let fileName = "\(self.persistentUserId!).jpg" let fileURL = self.deviceDirectoryForDownloads!.URLByAppendingPathComponent(fileName) user.imageData = NSData(contentsOfURL: fileURL) } if var currentUser = self.currentUser { currentUser.updateWithData(user) } else { self.currentUser = user } completion(userData: user, error: nil) } else { // should probably never happen assertionFailure("No userData and no error, why?") completion(userData: nil, error: nil) } } return nil }) return nil } } }
mit
56ce645b7868d9e5ddd08dcab9c23ef5
41.148276
150
0.60612
5.53282
false
false
false
false
lionchina/RxSwiftBook
RxGithubSignup/RxGithubSignup/DefaultImplementations.swift
1
3035
// // DefaultImplementations.swift // RxGithubSignup // // Created by MaxChen on 06/08/2017. // Copyright © 2017 com.linglustudio. All rights reserved. // import RxSwift import Foundation class GitHubDefaultValidationService: GitHubValidationService { let API: GitHubAPI static let sharedValidationService = GitHubDefaultValidationService(API: GitHubDefaultAPI.sharedAPI) init(API: GitHubAPI) { self.API = API } let minPasswordCount = 5 func validateUsername(_ username: String) -> Observable<ValidationResult> { if username.characters.count == 0 { return .just(.empty) } if username.rangeOfCharacter(from: CharacterSet.alphanumerics.inverted) != nil { return .just(.failed(message: "Username can only contain numbers or digits")) } let loadingValue = ValidationResult.validating return API.usernameAvailable(username) .map { available in if available { return .ok(message: "Username available") } else { return .failed(message: "Username already taken") } } .startWith(loadingValue) } func validatePassword(_ password: String) -> ValidationResult { let numberOfCharacters = password.characters.count if numberOfCharacters == 0 { return .empty } if numberOfCharacters < minPasswordCount { return .failed(message: "Password must be at least \(minPasswordCount) characters") } return .ok(message: "Password acceptable") } func validatePasswordRepeat(_ password: String, passwordRepeat: String) -> ValidationResult { if passwordRepeat.characters.count == 0 { return .empty } if passwordRepeat == password { return .ok(message: "Password repeated") } else { return .failed(message: "Password different") } } } class GitHubDefaultAPI: GitHubAPI { let urlSession: URLSession static let sharedAPI = GitHubDefaultAPI(urlSession: URLSession.shared) init(urlSession: URLSession) { self.urlSession = urlSession } func usernameAvailable(_ username: String) -> Observable<Bool> { let url = URL(string: "https://github.com/\(username.URLEscaped)")! let request = URLRequest(url: url) return self.urlSession.rx.response(request: request) .map { (response, _) in return response.statusCode == 404 } .catchErrorJustReturn(false) } func signup(_ username: String, password: String) -> Observable<Bool> { let signupResult = arc4random() % 5 == 0 ? false : true return Observable.just(signupResult).delay(1.0, scheduler: MainScheduler.instance) } } extension String { var URLEscaped: String { return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? "" } }
apache-2.0
b0301e9359ebf054a889da2007d42e7e
33.089888
104
0.625247
4.933333
false
false
false
false
xiaomudegithub/iosstar
iOSStar/AppAPI/SocketAPI/SocketReqeust/SocketConst.swift
3
7724
// // SockOpcode.swift // viossvc // // Created by yaowang on 2016/11/22. // Copyright © 2016年 ywwlcom.yundian. All rights reserved. // import Foundation class SocketConst: NSObject { enum OPCode:UInt16 { // 心跳包 case heart = 1000 // 获取图片上传token case imageToken = 1047 // 错误码 case errorCode = 0 // 登录 case login = 3003 // 注册 case register = 3001 // 注册 case reducetime = 9017 //减少时间 case getlist = 6013 // 重设密码 case repwd = 3019 // 声音验证码 case voiceCode = 1006 // 设置用户信息 case userInfo = 10010 case bindWchat = 3015 //设置账号信息 case WchatLogin = 3013 case verifycode = 3011 case getRealm = 3027 // 校验用户 case checkRegist = 3029 //网易云 case registWY = 9005 case userinfo = 3007 // 修改昵称 case modifyNickname = 3031 case paypwd = 7011 case getorderstars = 10012 case tokenLogin = 3009 //明星个人信息 case starInfo = 11005 //资讯列表 case newsInfo = 10013 // banner case banners = 10015 //行情分类 case marketType = 11001 //搜索 case searchStar = 13001 //搜索 case weixinpay = 7033 case alipay = 7049 //我的资产 case accountMoney = 1004 case detailList = 1005 case creditlist = 6003 case restPwd = 3005 case authentication = 3021 //分类明星 case marketStar = 11003 //添加自选 case addOptinal = 11015 case realName = 7045 //评论列表 case commetList = 10017 //明星经历 case starExperience = 11009 //明星成就 case starAchive = 11011 //明星信息 case newsStarInfo = 10001 // 明星服务类型 case starServiceType = 10019 // 订购明星服务 case buyStarService = 10021 // 获取已购明星数量 case buyStarCount = 10023 //实时报价 case realTime = 4001 //分时图 case timeLine = 4003 //明星列表 case starList = 4007 case starScrollList = 4009 //明星实时价格 case starRealtime = 4011 //发送评论 case sendComment = 12001 //评论列表 case commentList = 12003 //发起委托 case buyOrSell = 5001 //收到匹配成功 case receiveMatching = 5101 //获取拍卖时间 case auctionStatus = 5005 //所有订单 case allOrder = 6029 //确认订单 case sureOrder = 5007 //取消订单 case cancelOrder = 5009 //双方确认后结果推送 case orderResult = 5102 //当天委托 case todayEntrust = 6001 //历史委托 case historyEntrust = 6005 //当天成交 case todayOrder = 6007 //历史交易 case historyOrder = 6009 //委托粉丝榜粉丝榜 case fansList = 6021 //委托粉丝榜粉丝榜 case requestfansList = 6025 case getalllist = 10029 //订单粉丝榜 case orderFansList = 6015 //持有明星时间 case positionCount = 10025 case barrage = 6023 //问答 case askVideo = 15019 //获取用户问答信息 case userask = 15015 case starask = 15017 case qeepask = 15025 //拍卖买卖占比 case buySellPercent = 6017 //获取明星总时间 case starTotalTime = 10027 //获取版本更新信息 case update = 3033 //更新devicetoken case updateDeviceToken = 3035 case bankcardList = 8003 case unbindcard = 8007 case bindCard = 8005 case withdraw = 7057 case withdrawlist = 6019 case commissionModel = 3037 case bankinfo = 8009 //单点登录 case onlyLogin = 3040 //取消充值 case cancelRecharge = 7055 //抢购剩余时间 case remainingTime = 14001 //抢购明星信息 case panicBuyStarInfo = 14003 //明星介绍页详情 case starDetailInfo = 10031 //抢购明星时间 case panicBuy = 14005 //朋友圈 case circleList = 15001 //某个明星的朋友圈 case starCircle = 15003 //发布朋友圈 case sendCircle = 15005 //删除朋友圈 case deleteCircle = 15007 //点赞朋友圈 case approveCircle = 15009 case uptoken = 15029 //评论朋友圈 case commentCircle = 15011 //明星回复评论 case starComment = 15013 case configRequst = 10033 //交易时间 case miuCount = 10037 //七牛URL链接头 case qiniuHttp = 4015 //明星详情页面 case circleListdetail = 15027 } enum type:UInt8 { case error = 0 case wp = 1 case chat = 2 case user = 3 case time = 4 case deal = 5 case operate = 6 case order = 7 case getlist = 9 case bank = 8 case news = 10 case market = 11 case comment = 12 case search = 13 case buy = 14 case circle = 15 } enum aType:UInt8 { case shares = 1 //股票 case spot = 2 //现货 case futures = 3 //期货 case currency = 4 //外汇 } class Key { static let name = "name" static let phone = "phone" static let pwd = "pwd" static let pos = "startPos" static let code = "vCode" static let appid = "appid" static let secret = "secret" static let grant_type = "grant_type" static let memberId = "memberId" static let agentId = "agentId" static let recommend = "recommend" static let status = "status" static let uid = "id" static let vToken = "vToken" static let avatarLarge = "avatarLarge" static let timestamp = "timeStamp" static let timetamp = "timestamp" static let aType = "aType" static let name_value = "name_value" static let accid_value = "accid_value" static let deviceId = "deviceId" static let vCode = "vCode" static let openid = "openid" static let nickname = "nickname" static let headerUrl = "headerUrl" static let headimgurl = "headimgurl" static let accessToken = "access_token" static let accid = "accid" static let createtime = "createtime" static let starcode = "starcode" static let deduct_amount = "deduct_amount" static let startnum = "startnum" static let endnum = "endnum" static let all = "all" static let countNuber = "count" static let starCode = "code" static let type = "type" static let sorttype = "sorttype" static let title = "title" static let price = "price" static let token = "token" static let realname = "realname" static let id_card = "id_card" static let checkRegist = "checkRegist" static let time = "time" static let id = "uid" static let paypwd = "paypwd" } }
gpl-3.0
badbac924c7dd13a8eed1543c1e1ea02
25.486792
59
0.526713
3.974519
false
false
false
false
ziyincody/MTablesView
MTablesView/Classes/extensions.swift
1
1528
// // extensions.swift // Pods // // Created by Ziyin Wang on 2017-02-18. // // import UIKit extension UIView { @available(iOS 9.0, *) func anchor(_ top:NSLayoutYAxisAnchor? = nil, left:NSLayoutXAxisAnchor? = nil, bottom:NSLayoutYAxisAnchor? = nil, right:NSLayoutXAxisAnchor? = nil, topConstant:CGFloat = 0, leftConstant:CGFloat = 0, bottomConstant:CGFloat = 0, rightConstant:CGFloat = 0, widthConstant:CGFloat = 0, heightConstant:CGFloat = 0) -> [NSLayoutConstraint] { translatesAutoresizingMaskIntoConstraints = false var anchors = [NSLayoutConstraint]() if let top = top { anchors.append(topAnchor.constraint(equalTo: top,constant: topConstant)) } if let bottom = bottom { anchors.append(bottomAnchor.constraint(equalTo: bottom,constant: bottomConstant)) } if let left = left { anchors.append(leftAnchor.constraint(equalTo: left,constant: leftConstant)) } if let right = right { anchors.append(rightAnchor.constraint(equalTo: right,constant: -rightConstant)) } if widthConstant > 0 { anchors.append(widthAnchor.constraint(equalToConstant: widthConstant)) } if heightConstant > 0 { anchors.append(heightAnchor.constraint(equalToConstant: heightConstant)) } anchors.forEach({$0.isActive = true}) return anchors } }
mit
bb23217f03c583ae146ac6397713dade
30.833333
338
0.61322
5.059603
false
false
false
false
diwip/inspector-ios
Inspector/ViewControllers/Root/RootViewController.swift
1
1997
// // RootViewController.swift // Inspector // // Created by Kevin Hury on 2/15/16. // Copyright © 2016 diwip. All rights reserved. // import Cocoa import RxSwift enum TabIdentifier: String { case NodeTree = "NodeTreeTab" case Caches = "CachesTab" } class RootViewController: NSTabViewController { let disposeBag = DisposeBag() lazy var discoverVC: DiscoveryViewController = { let vc = self.storyboard!.instantiateControllerWithIdentifier("DiscoverDevices") as! DiscoveryViewController let service = (NSApplication.sharedApplication().delegate as! AppDelegate).browserHandler vc.viewModel = DiscoveryViewModel(devicesService: service) return vc }() override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter() .rx_notification("ConnectionLost") .observeOn(MainScheduler.instance) .subscribeNext { _ in self.popDiscoveryVC() } .addDisposableTo(disposeBag) guard let nodetree = try? viewController(NodeTreeViewController.self, forIdentifier: .NodeTree), let caches = try? viewController(CachesViewController.self, forIdentifier: .Caches) else { return assert(false, "mismatch viewcontroller with identifier") } nodetree.viewModel = NodeTreeViewModel() caches.viewModel = CachesViewModel() } override func viewDidAppear() { super.viewDidAppear() popDiscoveryVC() } func viewController<T: NSViewController>(type: T.Type, forIdentifier identifier: TabIdentifier) throws -> T { let index = self.tabView.indexOfTabViewItemWithIdentifier(identifier.rawValue) let item = self.tabViewItems[index] as NSTabViewItem let vc = item.viewController as! T return vc } func popDiscoveryVC() { self.presentViewControllerAsSheet(discoverVC) } }
mit
4c577963ea338fb558a8388637187ca7
30.698413
116
0.661824
5.157623
false
false
false
false
kstaring/swift
test/Constraints/dynamic_lookup.swift
4
6490
// RUN: rm -rf %t && mkdir -p %t // RUN: %target-swift-frontend -emit-module %S/Inputs/PrivateObjC.swift -o %t // RUN: %target-parse-verify-swift -I %t // REQUIRES: objc_interop import Foundation import PrivateObjC @objc class A { init() {} } @objc class B : A { override init() { super.init() } } @objc class C { init() {} } class X { init() {} @objc func foo(_ i: Int) { } @objc func bar() { } @objc func ovl2() -> A { } // expected-note{{found this candidate}} @objc func ovl4() -> B { } @objc func ovl5() -> B { } // expected-note{{found this candidate}} @objc class func staticFoo(_ i : Int) { } @objc func prop3() -> Int { return 5 } } class Y : P { init() {} @objc func foo(_ s: String) { } @objc func wibble() { } // expected-note 2 {{did you mean 'wibble'?}} @objc func ovl1() -> A { } @objc func ovl4() -> B { } @objc func ovl5() -> C { } // expected-note{{found this candidate}} @objc var prop1 : Int { get { return 5 } } var _prop2 : String @objc var prop2 : String { get { return _prop2 } set(value) { _prop2 = value } } @objc var prop3 : Int { get { return 5 } } @objc subscript (idx : Int) -> String { get { return "hello" } set {} } } class Z : Y { @objc override func ovl1() -> B { } @objc func ovl2() -> C { } // expected-note{{found this candidate}} @objc(ovl3_A) func ovl3() -> A { } @objc func ovl3() -> B { } func generic4<T>(_ x : T) { } } @objc protocol P { func wibble() } @objc protocol P2 { func wonka() var protoProp : Int { get } static func staticWibble() subscript (idx : A) -> Int { get set } } struct S { func wobble() { } } class D<T> { func generic1(_ x : T) { } } extension Z { @objc func ext1() -> A { } } // Find methods via dynamic method lookup. typealias Id = AnyObject var obj : Id = X() obj.bar!() obj.foo!(5) obj.foo!("hello") obj.wibble!() obj.wobble!() // expected-error{{value of type 'Id' (aka 'AnyObject') has no member 'wobble'}} obj.ext1!() // expected-warning {{result of call is unused}} obj.wonka!() // Same as above but without the '!' obj.bar() obj.foo(5) obj.foo("hello") obj.wibble() obj.wobble() // expected-error{{value of type 'Id' (aka 'AnyObject') has no member 'wobble'}} obj.ext1() // expected-warning {{result of call is unused}} obj.wonka() // Find class methods via dynamic method lookup. type(of: obj).staticFoo!(5) type(of: obj).staticWibble!() // Same as above but without the '!' type(of: obj).staticFoo(5) type(of: obj).staticWibble() // Overloading and ambiguity resolution // When we have overriding, pick the least restrictive declaration. var ovl1Result = obj.ovl1!() ovl1Result = A() // verify that we got an A, not a B // Same as above but without the '!' obj.ovl1() // expected-warning {{result of call is unused}} // Don't allow overload resolution between declarations from different // classes. var ovl2ResultA = obj.ovl2!() // expected-error{{ambiguous use of 'ovl2()'}} // ... but it's okay to allow overload resolution between declarations // from the same class. var ovl3Result = obj.ovl3!() ovl3Result = B() // For [objc] declarations, we can ignore declarations with the same // selector and type. var ovl4Result = obj.ovl4!() // ... but not when the types are different. var ovl5Result = obj.ovl5!() // expected-error{{ambiguous use of 'ovl5()'}} // Same as above but without the '!' obj.ovl4() // expected-warning {{result of call is unused}} // Generics // Dynamic lookup cannot find members of a generic class (or a class // that's a member of anything generic), because we wouldn't be able // to figure out the generic arguments. var generic1Result = obj.generic1!(17) // expected-error{{value of type 'Id' (aka 'AnyObject') has no member 'generic1'}} obj.generic2!() // expected-error{{value of type 'Id' (aka 'AnyObject') has no member 'generic2'}} obj.generic3!() // expected-error{{value of type 'Id' (aka 'AnyObject') has no member 'generic3'}} // Dynamic method lookup can't find non-[objc] members obj.generic4!(5) // expected-error{{value of type 'Id' (aka 'AnyObject') has no member 'generic4'}} // Find properties via dynamic lookup. var prop1Result : Int = obj.prop1! var prop2Result : String = obj.prop2! obj.prop2 = "hello" // expected-error{{cannot assign to property: 'obj' is immutable}} var protoPropResult : Int = obj.protoProp! // Find subscripts via dynamic lookup var sub1Result : String = obj[5]! var sub2Result : Int = obj[A()]! // Subscript then call without the '!' var sub1ResultNE = obj[5].hasPrefix("foo") var sub2ResultNE = obj[A()].hashValue // Property/function ambiguities. var prop3ResultA : Int? = obj.prop3 var prop3ResultB : (() -> Int)? = obj.prop3 var prop3ResultC = obj.prop3 let prop3ResultCChecked: Int? = prop3ResultC var obj2 : AnyObject & P = Y() class Z2 : AnyObject { } class Z3<T : AnyObject> { } class Z4<T> where T : AnyObject { } // Don't allow one to call instance methods on the Type via // dynamic method lookup. type(of: obj).foo!(obj)(5) // expected-error{{instance member 'foo' cannot be used on type 'Id' (aka 'AnyObject')}} // Checked casts to AnyObject var p: P = Y() // expected-warning @+1 {{forced cast from 'P' to 'AnyObject' always succeeds; did you mean to use 'as'?}} var obj3 : AnyObject = (p as! AnyObject)! // expected-error{{cannot force unwrap value of non-optional type 'AnyObject'}} {{41-42=}} // Implicit force of an implicitly unwrapped optional let uopt : AnyObject! = nil uopt.wibble!() // Should not be able to see private or internal @objc methods. uopt.privateFoo!() // expected-error{{'privateFoo' is inaccessible due to 'private' protection level}} uopt.internalFoo!() // expected-error{{'internalFoo' is inaccessible due to 'internal' protection level}} let anyValue: Any = X() _ = anyValue.bar() // expected-error {{value of type 'Any' has no member 'bar'}} // expected-note@-1 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}}{{5-5=(}}{{13-13= as AnyObject)}} _ = (anyValue as AnyObject).bar() _ = (anyValue as! X).bar() var anyDict: [String : Any] = Dictionary<String, Any>() anyDict["test"] = anyValue _ = anyDict["test"]!.bar() // expected-error {{value of type 'Any' has no member 'bar'}} // expected-note@-1 {{cast 'Any' to 'AnyObject' or use 'as!' to force downcast to a more specific type to access members}}{{5-5=(}}{{21-21= as AnyObject)}}
apache-2.0
c288effa54bd92cf6b8a2782878905c4
26.974138
155
0.651156
3.302799
false
false
false
false
BanyaKrylov/Learn-Swift
Skill/Homework 14/Homework 14/CoreDataTVC.swift
1
3390
// // CoreDataTVC.swift // Homework 14 // // Created by Ivan Krylov on 27.02.2020. // Copyright © 2020 Ivan Krylov. All rights reserved. // import UIKit import CoreData class CoreDataTVC: UITableViewController { @IBAction func addTaskCore(_ sender: Any) { let alertController = UIAlertController(title: "Создать новую задачу", message: nil, preferredStyle: .alert) alertController.addTextField { (textField) in textField.placeholder = "Опишите задачу" } let alertActionCancel = UIAlertAction(title: "Отменить", style: .destructive) { (alert) in } let alertActionCreate = UIAlertAction(title: "Создать", style: .cancel) { (alert) in let newItem = alertController.textFields![0].text addNewTaskCore(nameTask: newItem!) self.tableView.reloadData() } alertController.addAction(alertActionCancel) alertController.addAction(alertActionCreate) present(alertController, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tasks.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CellCore", for: indexPath) let currentItem = tasks[indexPath.row] cell.textLabel?.text = currentItem.value(forKey: "names") as? String if (currentItem.value(forKey: "isCompleted") as? Bool)! { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if changeStatusCore(at: indexPath.row) { tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark } else { tableView.cellForRow(at: indexPath)?.accessoryType = .none } } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { removeTaskCore(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let appDelegate = UIApplication.shared.delegate as! AppDelegate let managedContext = appDelegate.persistentContainer.viewContext let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:"Items2") let fetchedResults = try! managedContext.fetch(fetchRequest) let results = fetchedResults tasks = results as! [NSManagedObject] } }
apache-2.0
03ed3a5e016287924db01fa06ce8c37d
33.822917
137
0.638349
5.158951
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Retail
iOS/ReadyAppRetail/ReadyAppRetail/Controllers/HorizontalPagedCollectionViewController.swift
1
3857
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit class HorizontalPagedCollectionViewController: UICollectionViewController { var dataArray : [ItemMetaDataObject] = [] override func viewDidLoad() { super.viewDidLoad() self.setUpPlaceHolderItems() self.setUpCollectionView() } /** This method sets up the collectionview to have 3 placeholder products while it waits for a call back from Worklight */ private func setUpPlaceHolderItems(){ for(var i = 0; i<3; i++){ self.dataArray.append(ItemMetaDataObject()) } } /** This method is called when there has been data recieved and parsed from Worklight. It sets up the collectionview to handle this new data. - parameter newDataArray: */ func refresh(newDataArray : [ItemMetaDataObject]){ if(newDataArray.count > 0){ self.dataArray = newDataArray self.collectionView!.reloadData() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /** This method sets up the collectionview with various settings. */ private func setUpCollectionView(){ self.collectionView!.showsHorizontalScrollIndicator = false; let collectionPageViewLayout : HorizontalPagedCollectionViewFlowLayout = HorizontalPagedCollectionViewFlowLayout() self.collectionView!.setCollectionViewLayout(collectionPageViewLayout, animated: false); let nib : UINib = UINib(nibName: "HorizontalPagedCollectionViewCell", bundle:nil) self.collectionView!.registerNib(nib, forCellWithReuseIdentifier: "horizontalpagedcell"); } // MARK: UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { //#warning Incomplete method implementation -- Return the number of sections return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //#warning Incomplete method implementation -- Return the number of items in the section return dataArray.count } /** This method generates the cell for item at indexPath - parameter collectionView: - parameter indexPath: - returns: */ override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("horizontalpagedcell", forIndexPath: indexPath) as! HorizontalPagedCollectionViewCell let itemMetaDataObject : ItemMetaDataObject = dataArray[indexPath.row] as ItemMetaDataObject let url = NSURL(string: itemMetaDataObject.imageUrl as String) cell.imageView.sd_setImageWithURL(url, placeholderImage: UIImage(named: "Product_PlaceHolder")) return cell } // /** This method determines the action that is taken when an items is tapped. It tells the browseViewController what item was tapped. - parameter collectionView: - parameter indexPath: */ override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let browseViewController : BrowseViewController = self.parentViewController as! BrowseViewController let itemMetaDataObject : ItemMetaDataObject = dataArray[indexPath.row] as ItemMetaDataObject if(itemMetaDataObject.type == "product"){ browseViewController.showProductDetail(itemMetaDataObject.id) } } }
epl-1.0
50e46b98c2c844bab2b6756d5d8ede38
31.133333
158
0.685685
5.91411
false
false
false
false