repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
yramanchuk/gitTest | SmartFeedTests/SmartFeedTests.swift | 1 | 3678 | //
// SmartFeedTests.swift
// SmartFeedTests
//
// Created by Yury Ramanchuk on 3/24/16.
// Copyright © 2016 Yury Ramanchuk. All rights reserved.
//
import XCTest
import RealmSwift
@testable import SmartFeed
class SmartFeedTests: XCTestCase {
override func setUp() {
super.setUp()
isTestMode = true
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testDbCRUD() {
// bad idea to mock singleton!
// class MockModelManager : SFModelManager {
// override func realm() -> Realm {
// return try! Realm(configuration: Realm.Configuration(inMemoryIdentifier: TEST_MODE))
// }
// }
// let modelManager = MockModelManager.sharedInstance
let modelManager = SFModelManager.sharedInstance
let feed = SFFeed()
//test create
let feedId = modelManager.updateFeedSync(feed)
XCTAssertEqual(feedId, feed.feedId)
XCTAssertNotNil(feedId)
//test read
let foundFeed = modelManager.getFeed(byLink: feed.link)
XCTAssertNotNil(foundFeed)
XCTAssertEqual(feedId, foundFeed?.feedId)
XCTAssertEqual(feed.title, foundFeed?.title)
XCTAssertEqual(feed.link, foundFeed?.link)
// //test update
// feed.link = "http://test2.com"
// let feedIdAfterUpdate = modelManager.updateFeedSync(feed)
// XCTAssertEqual(feedId, feedIdAfterUpdate)
//test read
let allFeeds = modelManager.getAllFeeds()
XCTAssertTrue(allFeeds.count == 1)
let feedAfterUpdate = allFeeds.first!
XCTAssertEqual(feedId, feedAfterUpdate.feedId) //feed was not changed
XCTAssertEqual(foundFeed!.link, feedAfterUpdate.link)
//test delete
let expectation = expectationWithDescription("feed is deleted")
modelManager.deleteFeedAsync(feedId) {
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(2) { (error) in
if error != nil {
print("Time out deleting feedId \(feedId)")
}
let allFeedsEmpty = modelManager.getAllFeeds()
XCTAssertTrue(allFeedsEmpty.count == 0)
}
}
func testPerformanceReadability() {
// This is an example of a performance test case.
self.measureBlock {
let expectation = self.expectationWithDescription("Test html is parsed")
let url = NSURL(fileURLWithPath: NSBundle(forClass: SmartFeedTests.classForCoder()).pathForResource("test", ofType: "html")!)
let readability = DZReadability.init(URLToDownload: url, options: nil, completionHandler: { (sender, content, error) in
XCTAssertNil(error)
XCTAssertNotNil(content)
XCTAssertTrue(content.characters.count > 0)
expectation.fulfill()
})
readability .start()
self.waitForExpectationsWithTimeout(10, handler: { (error) in
if error != nil {
print("Time out parsing test page \(url)")
}
})
XCTAssertNotNil(readability)
// Put the code you want to measure the time of here.
}
}
}
| mit | ab18ff5e0ca51c232d81ae924f109367 | 30.161017 | 137 | 0.58662 | 5.085754 | false | true | false | false |
justindhill/Facets | Facets/OZLThirdPartyIntegrations.swift | 1 | 399 | //
// OZLThirdPartyIntegrations.swift
// Facets
//
// Created by Justin Hill on 6/9/16.
// Copyright © 2016 Justin Hill. All rights reserved.
//
class OZLThirdPartyIntegrations {
static let Enabled = false
class HockeyApp {
static let AppKey = ""
}
class Helpshift {
static let Domain = ""
static let AppId = ""
static let APIKey = ""
}
}
| mit | 82ab29f8765dccf4a682266c66c75d9d | 17.952381 | 54 | 0.600503 | 3.940594 | false | false | false | false |
beeth0ven/BNKit | BNKit/Source/Rx+/ItemsViewModel.swift | 1 | 1968 | //
// ItemsViewModel.swift
// BNKit
//
// Created by luojie on 2017/5/17.
// Copyright © 2017年 LuoJie. All rights reserved.
//
import RxSwift
public struct ItemsViewModel<Item, Param, Response> {
// Input
public let reloadTrigger: PublishSubject<Void> = .init()
// Output
public let items: Observable<[Item]>
public let error: Observable<Error>
public let isEmpty: Observable<Bool>
public let isLoading: Observable<Bool>
public init(
getParam: @escaping () -> Param,
mapToResponse: @escaping (Param) -> Observable<Response>,
mapToItems: @escaping (Response) -> [Item]
) {
// Input -> Output
let _isLoading: BehaviorSubject<Bool> = .init(value: false)
let _error: PublishSubject<Error> = .init()
let _items: Observable<[Item]> = reloadTrigger
.startWith(())
.withLatestFrom(_isLoading) { _, loading in loading }
.filter { loading in !loading }
.mapToVoid()
.map(getParam)
.do(onNext: { _ in _isLoading.onNext(true) })
.flatMapLatest { param -> Observable<[Item]> in
mapToResponse(param)
.do(onNext: { _ in _isLoading.onNext(false) })
.do(onError: { _ in _isLoading.onNext(false) })
.map(mapToItems)
.do(onError: _error.onNext)
.catchError { _ in .empty() }
}
.shareReplay(1)
let _isEmpty: Observable<Bool> = _items
.withLatestFrom(_isLoading) { items, loading in items.isEmpty && !loading }
.shareReplay(1)
items = _items.observeOnMainScheduler()
isLoading = _isLoading.observeOnMainScheduler()
error = _error.observeOnMainScheduler()
isEmpty = _isEmpty.observeOnMainScheduler()
}
}
| mit | 6147d79cd2a329688f6f5e4d103b6b5b | 30.693548 | 87 | 0.546056 | 4.559165 | false | false | false | false |
uias/Tabman | Sources/Tabman/Bar/BarButton/TMBarButtonInteractionController.swift | 1 | 1908 | //
// TMBarButtonInteractionController.swift
// Tabman
//
// Created by Merrick Sapsford on 05/07/2018.
// Copyright © 2022 UI At Six. All rights reserved.
//
import Foundation
internal protocol TMBarButtonInteractionHandler: AnyObject {
func barButtonInteraction(controller: TMBarButtonInteractionController,
didHandlePressOf button: TMBarButton,
at index: Int)
}
/// A bar button controller that is responsbile for handling interaction that occurs in bar buttons.
internal final class TMBarButtonInteractionController: TMBarButtonController, Hashable, Equatable {
// MARK: Properties
private weak var handler: TMBarButtonInteractionHandler?
// MARK: Init
init(for barButtons: [TMBarButton], handler: TMBarButtonInteractionHandler) {
self.handler = handler
super.init(for: barButtons)
barButtons.forEach({ (button) in
button.addTarget(self, action: #selector(barButtonPressed(_:)), for: .touchUpInside)
})
}
override init(for barButtons: [TMBarButton]?) {
fatalError("Use init(for barButtons: handler:)")
}
// MARK: Actions
@objc private func barButtonPressed(_ sender: TMBarButton) {
guard let index = barButtons.firstIndex(where: { $0.object === sender }) else {
return
}
handler?.barButtonInteraction(controller: self,
didHandlePressOf: sender,
at: index)
}
func hash(into hasher: inout Hasher) {
}
static func == (lhs: TMBarButtonInteractionController, rhs: TMBarButtonInteractionController) -> Bool {
if lhs === rhs {
return true
}
if type(of: lhs) != type(of: rhs) {
return false
}
return true
}
}
| mit | 0fada2a6dcee7aabcf6536f3b7257d6b | 29.269841 | 107 | 0.609858 | 4.966146 | false | false | false | false |
nodes-ios/nstack-translations-generator | LocalizationsGenerator Tests/GeneratorTests.swift | 1 | 1996 | //
// GeneratorTests.swift
// LocalizationsGeneratorTests
//
// Created by Marius Constantinescu on 29/05/2020.
// Copyright © 2020 Nodes. All rights reserved.
//
@testable import LocalizationsGenerator
import XCTest
class GeneratorTests: XCTestCase {
// This is using the Taxa api endpoints, to test with your application
// modify values accordingly
lazy var settings = GeneratorSettings(plistPath: nil, keys: nil, outputPath: nil, flatTranslations: false, convertFromSnakeCase: true, availableFromObjC: false, standalone: true, authorization: nil, extraHeaders: nil, jsonPath: "", jsonLocaleIdentifier: nil)
func testGenerateLocalizationsWithDefaultSection() {
guard let jsonData = GeneratorTestsData.jsonWithDefaultString.data(using: .utf8) else {
XCTFail()
return
}
guard let (code, _) = try? LGenerator().generateFromData(jsonData, settings, localeId: "en-GB") else {
XCTFail()
return
}
XCTAssertEqual(code, GeneratorTestsData.expectedCodeWithDefault)
}
func testGenerateLocalizationsWithNoDefaultSection() {
guard let jsonData = GeneratorTestsData.jsonWithoutDefaultString.data(using: .utf8) else {
XCTFail()
return
}
guard let (code, _) = try? LGenerator().generateFromData(jsonData, settings, localeId: "en-GB") else {
XCTFail()
return
}
XCTAssertEqual(code, GeneratorTestsData.expectedCodeWithoutDefault)
}
func testGeneratedLocalizationsOrder() {
guard let jsonData = GeneratorTestsData.jsonWithManyKeysAndSectionsString.data(using: .utf8) else {
XCTFail()
return
}
guard let (code, _) = try? LGenerator().generateFromData(jsonData, settings, localeId: "da-DK") else {
XCTFail()
return
}
XCTAssertEqual(code, GeneratorTestsData.expectedCodeWithManyKeysAndSections)
}
}
| mit | 2b4b239606b6b32b0b08f9be69c52163 | 33.396552 | 262 | 0.66817 | 4.761337 | false | true | false | false |
david1mdavis/IOS-nRF-Toolbox | nRF Toolbox/DFU/FileSelection/NORFileTypeViewController.swift | 2 | 3076 | //
// NORFileTypeViewController.swift
// nRF Toolbox
//
// Created by Mostafa Berg on 12/05/16.
// Copyright © 2016 Nordic Semiconductor. All rights reserved.
//
import UIKit
import iOSDFULibrary
class NORFileTypeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//MARK: - Properties
var delegate : NORFileTypeSelectionDelegate?
var chosenFirmwareType : DFUFirmwareType?
var options : NSArray?
//MARK: - View Actions
@IBAction func doneButtonTapped(_ sender: AnyObject) {
handleDoneButtonTapEvent()
}
@IBAction func cancelButtonTapped(_ sender: AnyObject) {
handleCancelButtonTapEvent()
}
//MARK: - UIViewControllerDelgeate
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
options = ["Softdevice", "Bootloader", "Application"]
UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.default, animated: true)
}
override func viewWillDisappear(_ animated: Bool) {
UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: true)
super.viewWillDisappear(animated)
}
//MARK: - NORFileTypeViewController implementation
func handleDoneButtonTapEvent() {
delegate?.onFileTypeSelected(fileType: chosenFirmwareType!)
self.dismiss(animated: true, completion: nil)
}
func handleCancelButtonTapEvent() {
delegate?.onFileTypeNotSelected()
self.dismiss(animated: true, completion: nil)
}
func pathToType(path aPath : NSIndexPath) -> DFUFirmwareType {
switch aPath.row {
case 0:
return DFUFirmwareType.softdevice
case 1:
return DFUFirmwareType.bootloader
default:
return DFUFirmwareType.application
}
}
//MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (options?.count)!
}
//MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let aCell = tableView.dequeueReusableCell(withIdentifier: "FileTypeCell", for: indexPath)
let cellType = options?.object(at: (indexPath as NSIndexPath).row) as? String
//Configure cell
aCell.textLabel?.text = cellType
if chosenFirmwareType == self.pathToType(path: indexPath as NSIndexPath) {
aCell.accessoryType = UITableViewCellAccessoryType.checkmark
}else{
aCell.accessoryType = UITableViewCellAccessoryType.none
}
return aCell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
chosenFirmwareType = self.pathToType(path: indexPath as NSIndexPath)
tableView.reloadData()
self.navigationItem.rightBarButtonItem?.isEnabled = true
}
}
| bsd-3-clause | a164a3195063d847945472f5e66feaf2 | 31.712766 | 100 | 0.674797 | 5.292599 | false | false | false | false |
sunilsharma08/CustomTextView | CustomTextViewExample/ViewController.swift | 1 | 6564 | //
// ViewController.swift
// CustomTextViewExample
//
// Created by Sunil Sharma on 08/06/16.
// Copyright © 2016 Sunil Sharma. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,CustomTextViewDelegate {
@IBOutlet weak var tableView: UITableView!
let defaultTableCellIdentifier = "defaultCellIdentifier"
let dataArray = NSMutableArray()
let customtTextView: CustomTextView = CustomTextView(frame: CGRectZero)
var bottomChatViewConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.tableFooterView = UIView()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: defaultTableCellIdentifier)
self.tableView.keyboardDismissMode = .OnDrag
dataArray.addObjectsFromArray(["Something1","Something2","Something3","Something4","Something5","Something6","Something7","Something8"])
self.setupChatView()
self.setupLayoutConstraints()
self.view.layoutIfNeeded()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationItem.title = "CustomTextView"
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardWillHide(sender: NSNotification) {
if let userInfo = sender.userInfo {
if let _ = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue.size.height {
self.bottomChatViewConstraint.constant = 0
UIView.animateWithDuration(0.25, animations: { () -> Void in self.view.layoutIfNeeded() })
}
}
}
func keyboardWillShow(sender: NSNotification) {
if let userInfo = sender.userInfo {
if let keyboardHeight = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue.size.height {
self.bottomChatViewConstraint.constant = -keyboardHeight
UIView.animateWithDuration(0.25, animations: { () -> Void in
self.view.layoutIfNeeded()
})
}
}
}
func setupChatView(){
self.view.addSubview(customtTextView)
customtTextView.delegate = self
customtTextView.placeholder = "Write something..."
customtTextView.maxCharCount = 250
}
func setupLayoutConstraints() {
self.customtTextView.translatesAutoresizingMaskIntoConstraints = false
self.tableView.translatesAutoresizingMaskIntoConstraints = false
self.view.addConstraints(self.chatInputConstraints())
self.view.addConstraints(self.tableViewConstraints())
}
func chatInputConstraints() -> [NSLayoutConstraint] {
self.bottomChatViewConstraint = NSLayoutConstraint(item: self.customtTextView, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1.0, constant: 0)
let leftConstraint = NSLayoutConstraint(item: self.customtTextView, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1.0, constant: 0.0)
let rightConstraint = NSLayoutConstraint(item: self.customtTextView, attribute: .Right, relatedBy: .Equal, toItem: self.view, attribute: .Right, multiplier: 1.0, constant: 0.0)
return [leftConstraint, self.bottomChatViewConstraint, rightConstraint]
}
func tableViewConstraints() -> [NSLayoutConstraint] {
let leftConstraint = NSLayoutConstraint(item: self.tableView, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1.0, constant: 0.0)
let rightConstraint = NSLayoutConstraint(item: self.tableView, attribute: .Right, relatedBy: .Equal, toItem: self.view, attribute: .Right, multiplier: 1.0, constant: 0.0)
let topConstraint = NSLayoutConstraint(item: self.tableView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1.0, constant: 0.0)
let bottomConstraint = NSLayoutConstraint(item: self.tableView, attribute: .Bottom, relatedBy: .Equal, toItem: self.customtTextView, attribute: .Top, multiplier: 1.0, constant: 0)
return [rightConstraint, leftConstraint, topConstraint, bottomConstraint]
}
func customTextView(customTextView: CustomTextView, didSendMessage message: String) {
//Chat send button is pressed.
let indexPath = NSIndexPath(forRow: 0 , inSection: 0)
self.tableView.beginUpdates()
self.dataArray.insertObject(message, atIndex: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Top)
self.tableView.endUpdates()
self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true)
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
func chatViewDidResize(customTextView: CustomTextView) {
//ChatView size is updated.
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(defaultTableCellIdentifier)
cell?.textLabel?.text = dataArray[indexPath.row] as? String
return cell!
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 60
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataArray.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | 122149b8bcc32b27ee02bacb207f3a6c | 46.905109 | 194 | 0.706689 | 5.233652 | false | false | false | false |
byu-oit-appdev/ios-byuSuite | byuSuite/Apps/IDCard/controller/IDCardViewController.swift | 1 | 2274 | //
// IDCardViewController.swift
// byuSuite
//
// Created by Alex Boswell on 12/20/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
import UIKit
private let IDCARD_DEFAULT = "idCardDefault.png"
private let IDCARD_BEARD = "idCardBeard.png"
class IDCardViewController: ByuViewController2 {
//MARK: Private variables
private var callbackCounter = 0
//MARK: Control Outlets
@IBOutlet private weak var personImageView: UIImageView!
@IBOutlet private weak var cardImageView: UIImageView!
@IBOutlet private weak var nameLabel: UILabel!
@IBOutlet private weak var roleLabel: UILabel!
@IBOutlet private weak var byuIDLabel: UILabel!
@IBOutlet private weak var expirationDateLabel: UILabel!
@IBOutlet private weak var spinner: UIActivityIndicatorView!
//MARK: Viewcontroller lifecycle
override func viewDidLoad() {
super.viewDidLoad()
//This is just to get rid of the placeholder text in the storyboard
nameLabel.text = ""
roleLabel.text = ""
byuIDLabel.text = ""
expirationDateLabel.text = ""
loadData()
}
//MARK: Custom Methods
private func loadData() {
callbackCounter += 1
IDCardClient.getIDCard { (idCard, error) in
self.stopAnimatingSpinnerIfReady()
if let idCard = idCard {
var backgroundImageName = IDCARD_DEFAULT
if idCard.beard {
backgroundImageName = IDCARD_BEARD
}
self.cardImageView.image = UIImage(named: backgroundImageName)
self.nameLabel.text = idCard.idCardName
self.roleLabel.text = idCard.idCardRole
self.byuIDLabel.text = "\(idCard.byuId ?? "") \(idCard.issueNumber ?? "")"
if let expirationDate = idCard.expirationDate {
let dateFormatter = DateFormatter.defaultDateFormat("d-MMM-yyyy")
self.expirationDateLabel.text = "EXP \(dateFormatter.string(from: expirationDate))"
}
} else {
self.displayAlert(error: error)
}
}
callbackCounter += 1
PersonPhotoClient2.getPhoto { (image, error) in
self.stopAnimatingSpinnerIfReady()
if let image = image {
self.personImageView.image = image
} else {
self.displayAlert(error: error)
}
}
}
private func stopAnimatingSpinnerIfReady() {
callbackCounter -= 1
if callbackCounter == 0 {
spinner.stopAnimating()
}
}
}
| apache-2.0 | f1b6348ed21f67cd4b520795e594047b | 24.829545 | 88 | 0.713594 | 3.738487 | false | false | false | false |
byu-oit-appdev/ios-byuSuite | byuSuite/Apps/Vending/controller/VendingProductsViewController.swift | 1 | 2440 | //
// VendingProductsViewController.swift
// byuSuite
//
// Created by Alex Boswell on 1/4/18.
// Copyright © 2018 Brigham Young University. All rights reserved.
//
import UIKit
class VendingProductsViewController: ByuSearchTableDataViewController {
@IBOutlet private weak var spinner: UIActivityIndicatorView!
var category: VendingCategory?
private var callbackCountdown = 0
private var tempProducts = [VendingProduct]()
override func viewDidLoad() {
super.viewDidLoad()
//If a category is provided load products for that one, else load all products.
if let category = category {
title = category.desc
loadProducts(forCategoryId: category.categoryId)
} else {
//The services does not provide an endpoint to get all products, so we have to loop through each category and get all products for each and put them together.
VendingClient.getAllCategories(callback: { (categories, error) in
if let categories = categories {
categories.forEach { self.loadProducts(forCategoryId: $0.categoryId)}
} else {
super.displayAlert(error: error)
}
})
}
tableView.hideEmptyCells()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToMap", let vc = segue.destination as? VendingMapViewController, let product: VendingProduct = objectForSender(cellSender: sender) {
vc.type = .product
vc.product = product
}
}
//MARK: Custom Functions
private func loadProducts(forCategoryId categoryId: Int) {
callbackCountdown += 1
spinner.startAnimating()
VendingClient.getAllProductsInCategory(categoryId: categoryId) { (products, error) in
if let products = products {
self.tempProducts.append(contentsOf: products)
} else {
super.displayAlert(error: error)
}
self.stopSpinnerIfReady()
}
}
private func stopSpinnerIfReady() {
callbackCountdown -= 1
if callbackCountdown == 0 {
spinner.stopAnimating()
tempProducts.sort()
masterTableData = TableData(rows: tempProducts.map {
var detailText: String?
if let price = $0.price {
detailText = String(format: "$%.2f", Float(price) / 100.0)
}
return Row(text: $0.desc, detailText: detailText, object: $0)
})
//If we are showing multiple products, the list can get pretty long. Use the section indexes.
if category == nil {
useIndexSections = true
}
tempProducts = []
tableView.reloadData()
}
}
}
| apache-2.0 | 8a85260dafb911bf7075ff74fe4a89eb | 28.385542 | 161 | 0.714637 | 3.793157 | false | false | false | false |
brave/browser-ios | Client/Frontend/Share/ShareExtensionHelper.swift | 1 | 6562 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
private let log = Logger.browserLogger
class ShareExtensionHelper: NSObject {
fileprivate weak var selectedTab: Browser?
fileprivate let selectedURL: URL
fileprivate var onePasswordExtensionItem: NSExtensionItem!
fileprivate let activities: [UIActivity]
init(url: URL, tab: Browser?, activities: [UIActivity]) {
self.selectedURL = url
self.selectedTab = tab
self.activities = activities
}
func createActivityViewController(_ completionHandler: @escaping (Bool) -> Void) -> UIActivityViewController {
var activityItems = [AnyObject]()
let printInfo = UIPrintInfo(dictionary: nil)
let absoluteString = selectedTab?.url?.absoluteString ?? selectedURL.absoluteString
printInfo.jobName = absoluteString
printInfo.outputType = .general
activityItems.append(printInfo)
if let tab = selectedTab {
activityItems.append(BrowserPrintPageRenderer(browser: tab))
}
if let title = selectedTab?.title {
activityItems.append(TitleActivityItemProvider(title: title))
}
activityItems.append(self)
let activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: activities)
// Hide 'Add to Reading List' which currently uses Safari.
// We would also hide View Later, if possible, but the exclusion list doesn't currently support
// third-party activity types (rdar://19430419).
activityViewController.excludedActivityTypes = [
UIActivityType.addToReadingList,
]
// This needs to be ready by the time the share menu has been displayed and
// activityViewController(activityViewController:, activityType:) is called,
// which is after the user taps the button. So a million cycles away.
if (ShareExtensionHelper.isPasswordManagerExtensionAvailable()) {
findLoginExtensionItem()
}
activityViewController.completionWithItemsHandler = { activityType, completed, returnedItems, activityError in
if completed, let activityType = activityType, self.isPasswordManagerActivityType(activityType.rawValue) {
if let logins = returnedItems {
self.fillPasswords(logins as [AnyObject])
}
}
completionHandler(completed)
}
return activityViewController
}
}
extension ShareExtensionHelper: UIActivityItemSource {
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
if let displayURL = selectedTab?.displayURL {
return displayURL
}
return selectedURL
}
// IMPORTANT: This method needs Swift compiler optimization DISABLED to prevent a nasty
// crash from happening in release builds. It seems as though the check for `nil` may
// get removed by the optimizer which leads to a crash when that happens.
@_semantics("optimize.sil.never") func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivityType?) -> Any? {
// activityType actually is nil sometimes (in the simulator at least)
if let type = activityType, isPasswordManagerActivityType(type.rawValue) {
return onePasswordExtensionItem
} else {
// Return the URL for the selected tab. If we are in reader view then decode
// it so that we copy the original and not the internal localhost one.
if let url = selectedTab?.url?.displayURL, url.isReaderModeURL {
return url.decodeReaderModeURL
}
return selectedTab?.url?.displayURL ?? selectedURL
}
}
func activityViewController(_ activityViewController: UIActivityViewController, dataTypeIdentifierForActivityType activityType: UIActivityType?) -> String {
// Temporary solution for bug: https://github.com/agilebits/onepassword-app-extension/issues/385
return "public.url"
}
}
private extension ShareExtensionHelper {
static func isPasswordManagerExtensionAvailable() -> Bool {
return OnePasswordExtension.shared().isAppExtensionAvailable()
}
func isPasswordManagerActivityType(_ activityType: String) -> Bool {
if (!ShareExtensionHelper.isPasswordManagerExtensionAvailable()) {
return false
}
// A 'password' substring covers the most cases, such as pwsafe and 1Password.
// com.agilebits.onepassword-ios.extension
// com.app77.ios.pwsafe2.find-login-action-password-actionExtension
// If your extension's bundle identifier does not contain "password", simply submit a pull request by adding your bundle identifier.
let additionalIdentifiers = [
"com.lastpass.ilastpass.LastPassExt",
"com.8bit.bitwarden.find-login-action-extension",
"com.intelsecurity.truekey.find-login-action"
]
return activityType.contains("password") || additionalIdentifiers.contains(activityType)
}
func findLoginExtensionItem() {
guard let selectedWebView = selectedTab?.webView else {
return
}
if selectedWebView.URL?.absoluteString == nil {
return
}
// Add 1Password to share sheet
OnePasswordExtension.shared().createExtensionItem(forWebView: selectedWebView, completion: {(extensionItem, error) -> Void in
if extensionItem == nil {
log.error("Failed to create the password manager extension item: \(error).")
return
}
// Set the 1Password extension item property
self.onePasswordExtensionItem = extensionItem
})
}
func fillPasswords(_ returnedItems: [AnyObject]) {
guard let selectedWebView = selectedTab?.webView else {
return
}
OnePasswordExtension.shared().fillReturnedItems(returnedItems, intoWebView: selectedWebView, completion: { (success, returnedItemsError) -> Void in
if !success {
log.error("Failed to fill item into webview: \(returnedItemsError).")
}
})
}
}
| mpl-2.0 | f2f40c8d3f90edfc7d8dc7f71dc19b24 | 40.27044 | 178 | 0.674032 | 5.716028 | false | false | false | false |
felipeuntill/WeddingPlanner | IOS/WeddingPlanner/RequirementListViewController.swift | 1 | 1967 | //
// RequirementViewController.swift
// WeddingPlanner
//
// Created by Felipe Assunção on 4/21/16.
// Copyright © 2016 Felipe Assunção. All rights reserved.
//
import Foundation
class RequirementListViewController : UITableViewController {
// override func viewDidLoad() {
// super.viewDidLoad()
// self.hideKeyboardWhenTappedAround()
// if revealViewController() != nil {
// self.view.addGestureRecognizer(revealViewController().panGestureRecognizer())
// }
// }
//
// override func viewDidAppear(animated: Bool) {
// super.viewDidAppear(animated)
// tableView.reloadData()
// }
//
// override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// return 3
// }
//
// override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// let cell = tableView.dequeueReusableCellWithIdentifier("requirement")! as! RequirementTableViewCell
// return cell.adapt(indexPath);
// }
//
// override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
// if(editingStyle == .Delete)
// {
// //RecipeManager.DeleteRecipe(indexPath.item)
// tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
// }
// }
// override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// if(segue.identifier == "detailSegue"){
// let cell = sender as! CustomTableViewCell
// let detailview = segue.destinationViewController as! DetailViewController
// let id = RecipeManager.recipes.indexOf({ $0.title == cell.recipe?.title })
// let recipe = RecipeManager.LoadRecipe(id!)
// detailview.recipe = recipe
// }
// }
} | mit | 67834256aba1901abc0fa6aa084514d5 | 35.351852 | 159 | 0.650866 | 4.682578 | false | false | false | false |
paulofaria/SwiftHTTPServer | UV HTTP Server/UVHTTPServer.swift | 3 | 1640 | // UVHTTPServer.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// 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 UVHTTPServer: Server {
let runLoop: RunLoop = UVRunLoop.defaultLoop
let acceptTCPClient = UVAcceptTCPClient
let parseRequest = HTTPRequestParser.parseRequest
let respond: HTTPRequest -> HTTPResponse
let serializeResponse = HTTPResponseSerializer.serializeResponse
init(respond: (request: HTTPRequest) -> HTTPResponse) {
self.respond = respond >>> Middleware.keepAlive >>> Middleware.addHeaders(["server": "HTTP Server"])
}
} | mit | 481d085a00dd20f4c8bb3685347c86c7 | 41.076923 | 108 | 0.745732 | 4.739884 | false | false | false | false |
vchuo/Photoasis | Photoasis/Classes/Constants/POColors.swift | 1 | 2338 | //
// POColors.swift
// カラー定数。
//
// Created by Vernon Chuo Chian Khye on 2017/02/26.
// Copyright © 2017 Vernon Chuo Chian Khye. All rights reserved.
//
import UIKit
struct POColors {
// MARK: - 画像はまだロードされていないのイメージビューの背景色
static let NoImageBackgroundColor = UIColor.fromHexa(0x778899)
// MARK: - ナビゲーションボタン
static let NavigationButtonSelectedStateBackgroundColor = UIColor.fromHexa(0x00688B)
static let NavigationButtonUnselectedStateBackgroundColor = UIColor.fromHexa(0x9BC3D0)
// MARK: - テーブルビューセル
// ホーム
static let HomeTableViewCellToggleSaveButtonNotSavedStateDefaultBackgroundColor = UIColor.fromHexa(0xA53E2D)
static let HomeTableViewCellToggleSaveButtonSavedStateDefaultBackgroundColor = UIColor.fromHexa(0x1F724C)
static let HomeTableViewCellToggleSaveButtonTextColor = UIColor.whiteColor()
// セーブしたフォト
static let SavedPhotosTableViewCellUnsaveButtonBackgroundColor = UIColor.fromHexa(0x1F724C)
static let SavedPhotosTableViewCellUnsaveButtonTextColor = UIColor.whiteColor()
// MARK: - 他のビュー
// ホーム
static let HomeViewLoadingIndicatorColor = UIColor.fromHexa(0x323232, alpha: 0.9)
// イメージビューアー
static let ImageViewerBackButtonBackgroundColor = UIColor.fromHexa(0x0088B5, alpha: 0.9)
// イメージビューアーヒント
static let ImageViewerAuthorNameViewBackgroundColor = UIColor.fromHexa(0x323232, alpha: 0.7)
static let ImageViewerAuthorNameViewTextColor = UIColor.whiteColor()
static let ImageViewerHintToastViewContainerBackgroundColor = UIColor.fromHexa(0xF6FBFC, alpha: 0.8)
static let ImageViewerHintToastViewLabelTextColor = UIColor.fromHexa(0x323232)
static let ImageViewerPhotoSavedToCameraRollToastViewBackgroundColor = UIColor.fromHexa(0xF6FBFC, alpha: 0.8)
static let ImageViewerPhotoSavedToCameraRollToastViewLabelTextColor = UIColor.fromHexa(0x323232)
// フォトを未保存するアクションを元に戻すボタン
static let UndoUnsaveButtonViewBackgroundColor = UIColor.fromHexa(0x000000, alpha: 0.85)
static let UndoUnsaveButtonViewTextColor = UIColor.whiteColor()
}
| mit | 7421e7c22adcde33a5e0cb6a61692423 | 40.392157 | 113 | 0.773567 | 3.769643 | false | false | false | false |
dialogflow/api-ai-cocoa-swift | AI/src/Requests/QueryRequest.swift | 2 | 3057 | //
// QueryRequest.swift
// AI
//
// Created by Kuragin Dmitriy on 13/11/15.
// Copyright © 2015 Kuragin Dmitriy. All rights reserved.
//
import Foundation
public enum Language {
case english
case spanish
case russian
case german
case portuguese
case portuguese_Brazil
case french
case italian
case japanese
case korean
case chinese_Simplified
case chinese_HongKong
case chinese_Taiwan
}
extension Language {
var stringValue: String {
switch self {
case .english:
return "en"
case .spanish:
return "es"
case .russian:
return "ru"
case .german:
return "de"
case .portuguese:
return "pt"
case .portuguese_Brazil:
return "pt-BR"
case .french:
return "fr"
case .italian:
return "it"
case .japanese:
return "ja"
case .korean:
return "ko"
case .chinese_Simplified:
return "zh-CN"
case .chinese_HongKong:
return "zh-HK"
case .chinese_Taiwan:
return "zh-TW"
}
}
}
public protocol QueryRequest: Request {
associatedtype ResponseType = QueryResponse
var queryParameters: QueryParameters { get }
var language: Language { get }
}
extension QueryRequest where Self: QueryContainer {
func query() -> String {
return "v=20150910"
}
}
public struct Entry {
public var value: String
public var synonyms: [String]
}
public struct Entity {
public var id: String? = .none
public var name: String
public var entries: [Entry]
}
public struct QueryParameters {
public var contexts: [Context] = []
public var resetContexts: Bool = false
public var sessionId: String? = SessionStorage.defaultSessionIdentifier
public var timeZone: TimeZone? = TimeZone.autoupdatingCurrent
public var entities: [Entity] = []
public init() {}
}
extension QueryParameters {
func jsonObject() -> [String: Any] {
var parameters = [String: Any]()
parameters["contexts"] = contexts.map({ (context) -> [String: Any] in
return ["name": context.name, "parameters": context.parameters]
})
parameters["resetContexts"] = resetContexts
if let sessionId = sessionId {
parameters["sessionId"] = sessionId
}
if let timeZone = timeZone {
parameters["timezone"] = timeZone.identifier
}
parameters["entities"] = entities.map({ (entity) -> [String: Any] in
var entityObject = [String: Any]()
entityObject["name"] = entity.name
entityObject["entries"] = entity.entries.map({ (entry) -> [String:Any] in
["value": entry.value, "synonyms": entry.synonyms]
})
return entityObject
})
return parameters
}
}
| apache-2.0 | 524d33d4e4f1a92d7658be44e1c7bd70 | 23.448 | 85 | 0.568717 | 4.554396 | false | false | false | false |
jianwoo/ios-charts | Charts/Classes/Renderers/ChartYAxisRenderer.swift | 1 | 12187 | //
// ChartYAxisRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 3/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
public class ChartYAxisRenderer: ChartAxisRendererBase
{
internal var _yAxis: ChartYAxis!
public init(viewPortHandler: ChartViewPortHandler, yAxis: ChartYAxis, transformer: ChartTransformer!)
{
super.init(viewPortHandler: viewPortHandler, transformer: transformer);
_yAxis = yAxis;
}
/// Computes the axis values.
public func computeAxis(var #yMin: Float, var yMax: Float)
{
// calculate the starting and entry point of the y-labels (depending on
// zoom / contentrect bounds)
if (viewPortHandler.contentWidth > 10.0 && !viewPortHandler.isFullyZoomedOutY)
{
var p1 = transformer.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop));
var p2 = transformer.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom));
if (!_yAxis.isInverted)
{
yMin = Float(p2.y);
yMax = Float(p1.y);
}
else
{
if (!_yAxis.isStartAtZeroEnabled)
{
yMin = Float(min(p1.y, p2.y));
}
else
{
yMin = 0.0;
}
yMax = Float(max(p1.y, p2.y));
}
}
computeAxisValues(min: yMin, max: yMax);
}
/// Sets up the y-axis labels. Computes the desired number of labels between
/// the two given extremes. Unlike the papareXLabels() method, this method
/// needs to be called upon every refresh of the view.
internal func computeAxisValues(#min: Float, max: Float)
{
var yMin = min;
var yMax = max;
var labelCount = _yAxis.labelCount;
var range = abs(yMax - yMin);
if (labelCount == 0 || range <= 0)
{
_yAxis.entries = [Float]();
return;
}
var rawInterval = range / Float(labelCount);
var interval = ChartUtils.roundToNextSignificant(number: Double(rawInterval));
var intervalMagnitude = pow(10.0, round(log10(interval)));
var intervalSigDigit = (interval / intervalMagnitude);
if (intervalSigDigit > 5)
{
// Use one order of magnitude higher, to avoid intervals like 0.9 or 90
interval = floor(10.0 * intervalMagnitude);
}
// if the labels should only show min and max
if (_yAxis.isShowOnlyMinMaxEnabled)
{
_yAxis.entries = [yMin, yMax];
}
else
{
var first = ceil(Double(yMin) / interval) * interval;
var last = ChartUtils.nextUp(floor(Double(yMax) / interval) * interval);
var f: Double;
var i: Int;
var n = 0;
for (f = first; f <= last; f += interval)
{
++n;
}
if (_yAxis.entries.count < n)
{
// Ensure stops contains at least numStops elements.
_yAxis.entries = [Float](count: n, repeatedValue: 0.0);
}
else if (_yAxis.entries.count > n)
{
_yAxis.entries.removeRange(n..<_yAxis.entries.count);
}
for (f = first, i = 0; i < n; f += interval, ++i)
{
_yAxis.entries[i] = Float(f);
}
}
}
/// draws the y-axis labels to the screen
public override func renderAxisLabels(#context: CGContext)
{
if (!_yAxis.isEnabled || !_yAxis.isDrawLabelsEnabled)
{
return;
}
var xoffset = _yAxis.xOffset;
var yoffset = _yAxis.labelFont.lineHeight / 2.5;
var dependency = _yAxis.axisDependency;
var labelPosition = _yAxis.labelPosition;
var xPos = CGFloat(0.0);
var textAlign: NSTextAlignment;
if (dependency == .Left)
{
if (labelPosition == .OutsideChart)
{
textAlign = .Right;
xPos = viewPortHandler.offsetLeft - xoffset;
}
else
{
textAlign = .Left;
xPos = viewPortHandler.offsetLeft + xoffset;
}
}
else
{
if (labelPosition == .OutsideChart)
{
textAlign = .Left;
xPos = viewPortHandler.contentRight + xoffset;
}
else
{
textAlign = .Right;
xPos = viewPortHandler.contentRight - xoffset;
}
}
drawYLabels(context: context, fixedPosition: xPos, offset: yoffset - _yAxis.labelFont.lineHeight, textAlign: textAlign);
}
internal override func renderAxisLine(#context: CGContext)
{
if (!_yAxis.isEnabled || !_yAxis.drawAxisLineEnabled)
{
return;
}
CGContextSaveGState(context);
CGContextSetStrokeColorWithColor(context, _yAxis.axisLineColor.CGColor);
CGContextSetLineWidth(context, _yAxis.axisLineWidth);
if (_yAxis.axisLineDashLengths != nil)
{
CGContextSetLineDash(context, _yAxis.axisLineDashPhase, _yAxis.axisLineDashLengths, _yAxis.axisLineDashLengths.count);
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0);
}
var lineSegments = UnsafeMutablePointer<CGPoint>.alloc(2)
if (_yAxis.axisDependency == .Left)
{
lineSegments[0].x = viewPortHandler.contentLeft;
lineSegments[0].y = viewPortHandler.contentTop;
lineSegments[1].x = viewPortHandler.contentLeft;
lineSegments[1].y = viewPortHandler.contentBottom;
CGContextStrokeLineSegments(context, lineSegments, 2);
}
else
{
lineSegments[0].x = viewPortHandler.contentRight;
lineSegments[0].y = viewPortHandler.contentTop;
lineSegments[1].x = viewPortHandler.contentRight;
lineSegments[1].y = viewPortHandler.contentBottom;
CGContextStrokeLineSegments(context, lineSegments, 2);
}
lineSegments.dealloc(2);
CGContextRestoreGState(context);
}
/// draws the y-labels on the specified x-position
internal func drawYLabels(#context: CGContext, fixedPosition: CGFloat, offset: CGFloat, textAlign: NSTextAlignment)
{
var labelFont = _yAxis.labelFont;
var labelTextColor = _yAxis.labelTextColor;
var valueToPixelMatrix = transformer.valueToPixelMatrix;
var pt = CGPoint();
for (var i = 0; i < _yAxis.entryCount; i++)
{
var text = _yAxis.getFormattedLabel(i);
if (!_yAxis.isDrawTopYLabelEntryEnabled && i >= _yAxis.entryCount - 1)
{
break;
}
pt.x = 0;
pt.y = CGFloat(_yAxis.entries[i]);
pt = CGPointApplyAffineTransform(pt, valueToPixelMatrix);
pt.x = fixedPosition;
pt.y += offset;
ChartUtils.drawText(context: context, text: text, point: pt, align: textAlign, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]);
}
}
private var _gridLineBuffer = [CGPoint](count: 2, repeatedValue: CGPoint());
public override func renderGridLines(#context: CGContext)
{
if (!_yAxis.isDrawGridLinesEnabled || !_yAxis.isEnabled)
{
return;
}
CGContextSaveGState(context);
CGContextSetStrokeColorWithColor(context, _yAxis.gridColor.CGColor);
CGContextSetLineWidth(context, _yAxis.gridLineWidth);
if (_yAxis.gridLineDashLengths != nil)
{
CGContextSetLineDash(context, _yAxis.gridLineDashPhase, _yAxis.gridLineDashLengths, _yAxis.gridLineDashLengths.count);
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0);
}
var valueToPixelMatrix = transformer.valueToPixelMatrix;
var position = CGPoint(x: 0.0, y: 0.0);
// draw the horizontal grid
for (var i = 0, count = _yAxis.entryCount; i < count; i++)
{
position.x = 0.0;
position.y = CGFloat(_yAxis.entries[i]);
position = CGPointApplyAffineTransform(position, valueToPixelMatrix)
_gridLineBuffer[0].x = viewPortHandler.contentLeft;
_gridLineBuffer[0].y = position.y;
_gridLineBuffer[1].x = viewPortHandler.contentRight;
_gridLineBuffer[1].y = position.y;
CGContextStrokeLineSegments(context, _gridLineBuffer, 2);
}
CGContextRestoreGState(context);
}
/// Draws the LimitLines associated with this axis to the screen.
public func renderLimitLines(#context: CGContext)
{
var limitLines = _yAxis.limitLines;
if (limitLines.count == 0)
{
return;
}
CGContextSaveGState(context);
var trans = transformer.valueToPixelMatrix;
var position = CGPoint(x: 0.0, y: 0.0);
var lineSegments = UnsafeMutablePointer<CGPoint>.alloc(2)
for (var i = 0; i < limitLines.count; i++)
{
var l = limitLines[i];
position.x = 0.0;
position.y = CGFloat(l.limit);
position = CGPointApplyAffineTransform(position, trans);
lineSegments[0].x = viewPortHandler.contentLeft;
lineSegments[0].y = position.y;
lineSegments[1].x = viewPortHandler.contentRight;
lineSegments[1].y = position.y;
CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor);
CGContextSetLineWidth(context, l.lineWidth);
if (l.lineDashLengths != nil)
{
CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count);
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0);
}
CGContextStrokeLineSegments(context, lineSegments, 2);
var label = l.label;
// if drawing the limit-value label is enabled
if (label.lengthOfBytesUsingEncoding(NSUTF16StringEncoding) > 0)
{
var xOffset = CGFloat(4.0);
var labelLineHeight = l.valueFont.lineHeight;
var yOffset = l.lineWidth + labelLineHeight / 2.0;
if (l.labelPosition == .Right)
{
ChartUtils.drawText(context: context, text: label, point: CGPoint(x: viewPortHandler.contentRight - xOffset, y: position.y - yOffset - labelLineHeight), align: .Right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]);
}
else
{
ChartUtils.drawText(context: context, text: label, point: CGPoint(x: viewPortHandler.contentLeft + xOffset, y: position.y - yOffset - labelLineHeight), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]);
}
}
}
lineSegments.dealloc(2);
CGContextRestoreGState(context);
}
} | apache-2.0 | d9fabfc7802dd8b6898640d1d9ea1f6e | 33.332394 | 286 | 0.54673 | 5.268915 | false | false | false | false |
quickthyme/PUTcat | Tests/iOS/Project/ProjectPresenterTests.swift | 1 | 8975 |
import XCTest
class ProjectPresenterTests: XCTestCase {
var subject: ProjectPresenterSpy!
var scene: ProjectSceneMock!
override func setUp() {
super.setUp()
scene = ProjectSceneMock()
subject = ProjectPresenterSpy()
}
func autoExpect(_ expect: XCTestExpectation, timeout: TimeInterval) {
DispatchQueue.main.asyncAfter(deadline: .now()+timeout) { expect.fulfill() }
}
}
// MARK: - Project Scene Delegate
extension ProjectPresenterTests {
func test_when_get_scene_data__it_invokes_proper_use_case_with_correct_parameters() {
let expect = expectation(description: "it_invokes_proper_use_case_with_correct_parameters")
subject.getSceneData(scene)
autoExpect(expect, timeout: 0.25)
waitForExpectations(timeout: 0.5) { _ in
XCTAssertTrue(self.subject.ucFetchProjectListWasCalled)
}
}
func test_when_get_scene_data__it_sets_scene_data_on_scene_and_calls_refresh() {
let expect = expectation(description: "it_sets_scene_data_on_scene_and_calls_refresh")
subject.getSceneData(scene)
autoExpect(expect, timeout: 0.25)
waitForExpectations(timeout: 0.5) { _ in
XCTAssertGreaterThan(self.scene.sceneData.section.count, 0)
XCTAssertTrue(self.scene.refreshSceneWasCalled)
}
}
func test_when_scene_did_select_item_with_segueid__it_tells_scene_to_navigate() {
let expect = expectation(description: "it_tells_scene_to_navigate")
let item = createProjectSceneDataItem1()
subject.scene(self.scene, didSelect: item)
autoExpect(expect, timeout: 0.25)
waitForExpectations(timeout: 0.5) { _ in
XCTAssertTrue(self.scene.navigateWasCalled)
XCTAssertEqual(self.scene.navigateSegueID, SegueID.Service)
}
}
func test_when_scene_did_select_item_without_segueid__it_does_not_tell_scene_to_navigate() {
let expect = expectation(description: "it_does_not_tell_scene_to_navigate")
var item = createProjectSceneDataItem1()
item.segue = nil
subject.scene(self.scene, didSelect: item)
autoExpect(expect, timeout: 0.25)
waitForExpectations(timeout: 0.5) { _ in
XCTAssertFalse(self.scene.navigateWasCalled)
XCTAssertNil(self.scene.navigateSegueID)
}
}
func test_when_add_item__it_invokes_proper_use_case_with_correct_parameters() {
let expect = expectation(description: "it_invokes_proper_use_case_with_correct_parameters")
subject.addItem(scene: scene)
autoExpect(expect, timeout: 0.25)
waitForExpectations(timeout: 0.5) { _ in
XCTAssertTrue(self.subject.ucAddProjectWasCalled)
}
}
func test_when_add_item__it_calls_refresh() {
let expect = expectation(description: "it_calls_refresh")
subject.addItem(scene: scene)
autoExpect(expect, timeout: 0.25)
waitForExpectations(timeout: 0.5) { _ in
XCTAssertTrue(self.scene.refreshSceneWasCalled)
}
}
func test_when_update_item__it_invokes_proper_use_case_with_correct_parameters() {
let expect = expectation(description: "it_invokes_proper_use_case_with_correct_parameters")
let item = createProjectSceneDataItem1()
subject.scene(scene, didUpdate: item)
autoExpect(expect, timeout: 0.25)
waitForExpectations(timeout: 0.5) { _ in
XCTAssertTrue(self.subject.ucUpdateProjectWasCalled)
XCTAssertEqual(self.subject.ucUpdateProjectParameter_id, "123")
XCTAssertEqual(self.subject.ucUpdateProjectParameter_name, "Title 1")
}
}
func test_when_update_item__it_calls_refresh() {
let expect = expectation(description: "it_calls_refresh")
let item = createProjectSceneDataItem1()
subject.scene(scene, didUpdate: item)
autoExpect(expect, timeout: 0.25)
waitForExpectations(timeout: 0.5) { _ in
XCTAssertTrue(self.scene.refreshSceneWasCalled)
}
}
func test_when_delete_item__it_invokes_proper_use_case_with_correct_parameters() {
let expect = expectation(description: "it_invokes_proper_use_case_with_correct_parameters")
let item = createProjectSceneDataItem1()
subject.scene(scene, didDelete: item)
autoExpect(expect, timeout: 0.25)
waitForExpectations(timeout: 0.5) { _ in
XCTAssertTrue(self.subject.ucDeleteProjectWasCalled)
XCTAssertEqual(self.subject.ucDeleteProjectParameter_projectID, "123")
}
}
func test_when_delete_item__it_calls_refresh() {
let expect = expectation(description: "it_calls_refresh")
let item = createProjectSceneDataItem1()
subject.scene(scene, didDelete: item)
autoExpect(expect, timeout: 0.25)
waitForExpectations(timeout: 0.5) { _ in
XCTAssertTrue(self.scene.refreshSceneWasCalled)
}
}
func test_when_update_ordinality__it_invokes_proper_use_case_with_correct_parameters() {
let expect = expectation(description: "it_invokes_proper_use_case_with_correct_parameters")
let data = createProjectSceneData()
subject.scene(scene, didUpdateOrdinality: data)
autoExpect(expect, timeout: 0.25)
waitForExpectations(timeout: 0.5) { _ in
XCTAssertTrue(self.subject.ucSortProjectListWasCalled)
XCTAssertEqual(self.subject.ucSortProjectListParameter_ordinality!, ["123","456"])
}
}
func test_when_update_ordinality__it_calls_refresh() {
let expect = expectation(description: "it_calls_refresh")
let data = createProjectSceneData()
subject.scene(scene, didUpdateOrdinality: data)
autoExpect(expect, timeout: 0.25)
waitForExpectations(timeout: 0.5) { _ in
XCTAssertTrue(self.scene.refreshSceneWasCalled)
}
}
func test_when_export_project__it_invokes_proper_use_case_with_correct_parameters() {
let expect = expectation(description: "it_invokes_proper_use_case_with_correct_parameters")
let scene = ProjectSceneMock()
subject.exportProject(name: "Project 1", scene: scene)
autoExpect(expect, timeout: 0.25)
waitForExpectations(timeout: 0.5) { _ in
XCTAssertTrue(self.subject.ucBuildFullyConstructedProjectWasCalled)
XCTAssertEqual(self.subject.ucBuildFullyConstructedProjectParameter_name, "Project 1")
}
}
func test_when_export_project__it_calls_present_send_email() {
let expect = expectation(description: "it_calls_present_send_email")
subject.exportProject(name: "Project 1", scene: scene)
autoExpect(expect, timeout: 0.25)
waitForExpectations(timeout: 0.5) { _ in
XCTAssertTrue(self.scene.presentSendEmailWithAttachmentWasCalled)
XCTAssertEqual(self.scene.presentSendEmailSubject, "Export of Project 1 Project")
XCTAssertGreaterThan(self.scene.presentSendEmailAttachment!.count, 0)
XCTAssertEqual(self.scene.presentSendEmailFilename, "Project 1.putcatProject")
XCTAssertEqual(self.scene.presentSendEmailMimeType, "application/putcat")
}
}
// MARK: - Local Mocks
fileprivate typealias CellID = ProjectSceneDataItem.CellID
fileprivate typealias SegueID = ProjectSceneDataItem.SegueID
fileprivate typealias Icon = ProjectSceneDataItem.Icon
fileprivate func createProjectSceneData() -> ProjectSceneData {
return ProjectSceneData(section:
[
ProjectSceneDataSection(title: "Section",
item: [createProjectSceneDataItem1(),
createProjectSceneDataItem2()])
]
)
}
fileprivate func createProjectSceneDataItem1() -> ProjectSceneDataItem {
return ProjectSceneDataItem(refID: "123",
cellID: CellID.BasicCell,
title: "Title 1",
detail: "Description 1",
segue: SegueID.Service,
icon: UIImage(named: Icon.Project),
associatedID: "123")
}
fileprivate func createProjectSceneDataItem2() -> ProjectSceneDataItem {
return ProjectSceneDataItem(refID: "456",
cellID: CellID.BasicCell,
title: "Title 2",
detail: "Description 2",
segue: SegueID.Service,
icon: UIImage(named: Icon.Project),
associatedID: "123")
}
}
| apache-2.0 | 075d872988cb58767ef67790b0190626 | 38.19214 | 99 | 0.630084 | 4.572084 | false | true | false | false |
edx/edx-app-ios | Source/UITextView/FillBackgroundLayoutManager.swift | 1 | 4948 | //
// FillBackgroundLayoutManager.swift
// edX
//
// Created by Muhammad Umer on 08/10/2020.
// Copyright © 2020 edX. All rights reserved.
//
import Foundation
class FillBackgroundLayoutManager: NSLayoutManager {
private var borderColor: UIColor = .clear
private var lineWidth: CGFloat = 0.5
private var cornerRadius = 5
func set(borderColor: UIColor, lineWidth: CGFloat, cornerRadius: Int) {
self.borderColor = borderColor
self.lineWidth = lineWidth
self.cornerRadius = cornerRadius
}
override func fillBackgroundRectArray(_ rectArray: UnsafePointer<CGRect>, count rectCount: Int, forCharacterRange charRange: NSRange, color: UIColor) {
guard let _ = textStorage,
let currentCGContext = UIGraphicsGetCurrentContext() else {
super.fillBackgroundRectArray(rectArray, count: rectCount, forCharacterRange: charRange, color: color)
return
}
currentCGContext.saveGState()
for i in 0..<rectCount {
var previousRect = CGRect.zero
let currentRect = rectArray[i]
if i > 0 {
previousRect = rectArray[i - 1]
}
let frame = rectArray[i]
let rect = CGRect.init(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: frame.size.height + 2)
let cornerRadii = CGSize(width: cornerRadius, height: cornerRadius)
let rectanglePath = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: cornerRadii)
color.set()
currentCGContext.setAllowsAntialiasing(true)
currentCGContext.setShouldAntialias(true)
currentCGContext.setFillColor(color.cgColor)
currentCGContext.addPath(rectanglePath.cgPath)
currentCGContext.drawPath(using: .fill)
let overlappingLine = UIBezierPath()
let leftVerticalJoiningLine = UIBezierPath()
let rightVerticalJoiningLine = UIBezierPath()
let leftVerticalJoiningLineShadow = UIBezierPath()
let rightVerticalJoiningLineShadow = UIBezierPath()
if previousRect != .zero, (currentRect.maxX - previousRect.minX) > CGFloat(cornerRadius) {
let yDifference = currentRect.minY - previousRect.maxY
overlappingLine.move(to: CGPoint(x: max(previousRect.minX, currentRect.minX) + lineWidth / 2, y: previousRect.maxY + yDifference / 2))
overlappingLine.addLine(to: CGPoint(x: min(previousRect.maxX, currentRect.maxX) - lineWidth / 2, y: previousRect.maxY + yDifference / 2))
let leftX = max(previousRect.minX, currentRect.minX)
let rightX = min(previousRect.maxX, currentRect.maxX)
leftVerticalJoiningLine.move(to: CGPoint(x: leftX, y: previousRect.maxY))
leftVerticalJoiningLine.addLine(to: CGPoint(x: leftX, y: currentRect.minY))
rightVerticalJoiningLine.move(to: CGPoint(x: rightX, y: previousRect.maxY))
rightVerticalJoiningLine.addLine(to: CGPoint(x: rightX, y: currentRect.minY))
let leftShadowX = max(previousRect.minX, currentRect.minX) + lineWidth
let rightShadowX = min(previousRect.maxX, currentRect.maxX) - lineWidth
leftVerticalJoiningLineShadow.move(to: CGPoint(x: leftShadowX, y: previousRect.maxY))
leftVerticalJoiningLineShadow.addLine(to: CGPoint(x: leftShadowX, y: currentRect.minY))
rightVerticalJoiningLineShadow.move(to: CGPoint(x: rightShadowX, y: previousRect.maxY))
rightVerticalJoiningLineShadow.addLine(to: CGPoint(x: rightShadowX, y: currentRect.minY))
}
currentCGContext.setLineWidth(lineWidth * 4)
currentCGContext.setStrokeColor(borderColor.cgColor)
currentCGContext.addPath(leftVerticalJoiningLineShadow.cgPath)
currentCGContext.addPath(rightVerticalJoiningLineShadow.cgPath)
currentCGContext.drawPath(using: .stroke)
currentCGContext.setShadow(offset: .zero, blur: 0, color: UIColor.clear.cgColor)
currentCGContext.setLineWidth(lineWidth)
currentCGContext.setStrokeColor(borderColor.cgColor)
currentCGContext.addPath(rectanglePath.cgPath)
currentCGContext.addPath(leftVerticalJoiningLine.cgPath)
currentCGContext.addPath(rightVerticalJoiningLine.cgPath)
currentCGContext.drawPath(using: .stroke)
currentCGContext.setShadow(offset: .zero, blur: 0, color: UIColor.clear.cgColor)
currentCGContext.setStrokeColor(color.cgColor)
currentCGContext.addPath(overlappingLine.cgPath)
}
currentCGContext.restoreGState()
}
}
| apache-2.0 | b86a5fb1e745d591b536e024f58aa6f5 | 48.969697 | 155 | 0.65373 | 4.788964 | false | false | false | false |
FutureKit/FutureKit | FutureKit/Completion.swift | 1 | 17589 | //
// Completion.swift
// FutureKit
//
// Created by Michael Gray on 4/21/15.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
// the onSuccess and onComplete handlers will return either a generic type __Type, or any object confirming to the CompletionType.
// CompletionType include Completion<T>, FutureResult<T>, Future<T>, Promise<T>...
public protocol CompletionType : CustomStringConvertible, CustomDebugStringConvertible {
associatedtype T
var completion : Completion<T> { get }
}
// a type-erased CompletionType
public struct AnyCompletion : CompletionType {
public typealias T = Any
public var completion : Completion<Any>
init<C:CompletionType>(completionType:C) {
self.completion = completionType.completion.mapAs()
}
}
extension CompletionType {
func toAnyCompletion() -> AnyCompletion {
return AnyCompletion(completionType: self)
}
}
/**
Defines a simple enumeration of the legal Completion states of a Future.
- case Success(T): the Future has completed Succesfully.
- case Fail(ErrorType): the Future has failed.
- case Cancelled: the Future was cancelled. This is typically not seen as an error.
*/
public enum FutureResult<T> {
case success(T)
case fail(Error)
case cancelled
}
/**
Defines a an enumeration that can be used to complete a Promise/Future.
- Success(T): The Future should complete with a `FutureResult.Success(T)`
- Fail(ErrorType): The Future should complete with a `FutureResult.Fail(ErrorType)`
- Cancelled:
The Future should complete with with `FutureResult.Cancelled`.
- CompleteUsing(Future<T>):
The Future should be completed with the result of a another dependent Future, when the dependent Future completes.
If The Future receives a cancelation request, than the cancellation request will be forwarded to the depedent future.
*/
public enum Completion<T> {
case success(T)
case fail(Error)
case cancelled
case completeUsing(Future<T>)
}
extension Future : CompletionType {
public var completion : Completion<T> {
return .completeUsing(self)
}
}
extension Promise : CompletionType {
public var completion : Completion<T> {
return .completeUsing(self.future)
}
}
extension Completion : CompletionType { // properties
public var completion : Completion<T> {
return self
}
}
extension FutureResult : CompletionType {
public var completion : Completion<T> {
switch self {
case let .success(result):
return .success(result)
case let .fail(error):
return error.toCompletion()
case .cancelled:
return .cancelled
}
}
}
extension CompletionType {
public static func SUCCESS(_ value:T) -> Completion<T> {
return Completion<T>(success: value)
}
public static func FAIL(_ fail:Error) -> Completion<T> {
return Completion<T>(fail: fail)
}
public static func FAIL(_ failWithErrorMessage:String) -> Completion<T> {
return Completion<T>(failWithErrorMessage:failWithErrorMessage)
}
public static func CANCELLED<T>(_ cancelled:()) -> Completion<T> {
return Completion<T>(cancelled: cancelled)
}
public static func COMPLETE_USING<T>(_ completeUsing:Future<T>) -> Completion<T> {
return Completion<T>(completeUsing: completeUsing)
}
}
public func SUCCESS<T>(_ value:T) -> Completion<T> {
return Completion<T>(success: value)
}
public func FAIL<T>(_ fail:Error) -> Completion<T> {
return Completion<T>(fail: fail)
}
public func CANCELLED<T>(_ cancelled:()) -> Completion<T> {
return Completion<T>(cancelled: cancelled)
}
public func COMPLETE_USING<T>(_ completeUsing:Future<T>) -> Completion<T> {
return Completion<T>(completeUsing: completeUsing)
}
public extension FutureResult { // initializers
/**
returns a .Fail(FutureNSError) with a simple error string message.
*/
public init(failWithErrorMessage : String) {
self = .fail(FutureKitError(genericError: failWithErrorMessage))
}
/**
converts an NSException into an NSError.
useful for generic Objective-C excecptions into a Future
*/
public init(exception ex:NSException) {
self = .fail(FutureKitError(exception: ex))
}
public init(success:T) {
self = .success(success)
}
public init(fail: Error) {
self = .fail(fail)
}
public init(cancelled: ()) {
self = .cancelled
}
}
public extension CompletionType {
/**
make sure this enum is a .Success before calling `result`. Do a check 'completion.state {}` or .isFail() first.
*/
public var value : T! {
get {
switch self.completion {
case let .success(t):
return t
case let .completeUsing(f):
if let v = f.value {
return v
}
else {
return nil
}
default:
return nil
}
}
}
/**
make sure this enum is a .Fail before calling `result`. Use a switch or check .isError() first.
*/
public var error : Error! {
get {
switch self.completion {
case let .fail(e):
return e.testForCancellation ? nil : e
default:
return nil
}
}
}
public var isSuccess : Bool {
get {
switch self.completion {
case .success:
return true
default:
return false
}
}
}
public var isFail : Bool {
get {
switch self.completion {
case let .fail(e):
return !e.testForCancellation
default:
return false
}
}
}
public var isCancelled : Bool {
get {
switch self.completion {
case .cancelled:
return true
case let .fail(e):
return e.testForCancellation
default:
return false
}
}
}
public var isCompleteUsing : Bool {
get {
switch self.completion {
case .completeUsing:
return true
default:
return false
}
}
}
internal var completeUsingFuture:Future<T>! {
get {
switch self.completion {
case let .completeUsing(f):
return f
default:
return nil
}
}
}
var result : FutureResult<T>! {
switch self.completion {
case .completeUsing:
return nil
case let .success(value):
return .success(value)
case let .fail(error):
return error.toResult() // check for possible cancellation errors
case .cancelled:
return .cancelled
}
}
/**
can be used inside a do/try/catch block to 'try' and get the result of a Future.
Useful if you want to use a swift 2.0 error handling block to resolve errors
let f: Future<Int> = samplefunction()
f.onComplete { (value) -> Void in
do {
let r: Int = try resultValue()
}
catch {
print("error : \(error)")
}
}
*/
func tryValue() throws -> T {
switch self.completion {
case let .success(value):
return value
case let .fail(error):
throw error
case .cancelled:
throw FutureKitError(genericError: "Future was canceled.")
case let .completeUsing(f):
if let v = f.value {
return v
}
throw FutureKitError(genericError: "Future was not completed.")
}
}
/**
can be used inside a do/try/catch block to 'try' and get the result of a Future.
Useful if you want to use a swift 2.0 error handling block to resolve errors
let f: Future<Int> = samplefunction()
f.onComplete { (value) -> Void in
do {
try throwIfFail()
}
catch {
print("error : \(error)")
}
}`
.Cancelled does not throw an error. If you want to also trap cancellations use 'throwIfFailOrCancel()`
*/
func throwIfFail() throws {
switch self.completion {
case let .fail(error):
if (!error.testForCancellation) {
throw error
}
default:
break
}
}
/**
can be used inside a do/try/catch block to 'try' and get the result of a Future.
Useful if you want to use a swift 2.0 error handling block to resolve errors
let f: Future<Int> = samplefunction()
f.onComplete { (value) -> Void in
do {
try throwIfFailOrCancel()
}
catch {
print("error : \(error)")
}
}
*/
func throwIfFailOrCancel() throws {
switch self.completion {
case let .fail(error):
throw error
case .cancelled:
throw FutureKitError(genericError: "Future was canceled.")
default:
break
}
}
/**
convert this completion of type Completion<T> into another type Completion<S>.
may fail to compile if T is not convertable into S using "`as!`"
works iff the following code works:
'let t : T`
'let s = t as! S'
- example:
`let c : Complete<Int> = .Success(5)`
`let c2 : Complete<Int32> = c.mapAs()`
`assert(c2.result == Int32(5))`
you will need to formally declare the type of the new variable, in order for Swift to perform the correct conversion.
*/
public func map<__Type>(_ block: @escaping (T) throws -> __Type) -> Completion<__Type> {
switch self.completion {
case let .success(t):
do {
return .success(try block(t))
}
catch {
return .fail(error)
}
case let .fail(f):
return .fail(f)
case .cancelled:
return .cancelled
case let .completeUsing(f):
let mapf :Future<__Type> = f.map(.primary,block: block)
return .completeUsing(mapf)
}
}
/**
convert this completion of type `Completion<T>` into another type `Completion<S?>`.
WARNING: if `T as! S` isn't legal, than all Success values may be converted to nil
- example:
let c : Complete<String> = .Success("5")
let c2 : Complete<[Int]?> = c.convertOptional()
assert(c2.result == nil)
you will need to formally declare the type of the new variable, in order for Swift to perform the correct conversion.
- returns: a new result of type Completion<S?>
*/
public func mapAsOptional<O : OptionalProtocol>(type:O.Type) -> Completion<O.Wrapped?> {
return self.map { v -> O.Wrapped? in
return v as? O.Wrapped
}
}
/**
convert this completion of type Completion<T> into another type Completion<S>.
may fail to compile if T is not convertable into S using "`as!`"
works iff the following code works:
'let t : T`
'let s = t as! S'
- example:
`let c : Complete<Int> = .Success(5)`
`let c2 : Complete<Int32> = c.mapAs()`
`assert(c2.result == Int32(5))`
you will need to formally declare the type of the new variable, in order for Swift to perform the correct conversion.
*/
public func mapAs<__Type>() -> Completion<__Type> {
switch self.completion {
case let .success(t):
assert(t is __Type, "you can't cast \(type(of: t)) to \(__Type.self)")
if (t is __Type) {
let r = t as! __Type
return .success(r)
}
else {
return Completion<__Type>(failWithErrorMessage:"can't cast \(type(of: t)) to \(__Type.self)");
}
case let .fail(f):
return .fail(f)
case .cancelled:
return .cancelled
case let .completeUsing(f):
return .completeUsing(f.mapAs())
}
}
public func mapAs() -> Completion<T> {
return self.completion
}
public func mapAs() -> Completion<Void> {
switch self.completion {
case .success:
return .success(())
case let .fail(f):
return .fail(f)
case .cancelled:
return .cancelled
case let .completeUsing(f):
return .completeUsing(f.mapAs())
}
}
public func As() -> Completion<T> {
return self.completion
}
@available(*, deprecated: 1.1, message: "renamed to mapAs()")
public func As<__Type>() -> Completion<__Type> {
return self.mapAs()
}
}
extension FutureResult : CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
switch self {
case let .success(result):
return ".Success<\(T.self)>(\(result))"
case let .fail(error):
return ".Fail<\(T.self)>(\(error))"
case .cancelled:
return ".Cancelled<\(T.self)>)"
}
}
public var debugDescription: String {
return self.description
}
/**
This doesn't seem to work yet in the XCode Debugger or Playgrounds.
it seems that only NSObjectProtocol objects can use this method.
Since this is a Swift Generic, it seems to be ignored.
Sigh.
*/
func debugQuickLookObject() -> AnyObject? {
return self.debugDescription as AnyObject?
}
}
public extension Completion { // initializers
/**
returns a .Fail(FutureNSError) with a simple error string message.
*/
public init(failWithErrorMessage : String) {
self = .fail(FutureKitError(genericError: failWithErrorMessage))
}
/**
converts an NSException into an NSError.
useful for generic Objective-C excecptions into a Future
*/
public init(exception ex:NSException) {
self = .fail(FutureKitError(exception: ex))
}
public init(success:T) {
self = .success(success)
}
public init(fail: Error) {
self = fail.toCompletion() // make sure it's not really a cancellation
}
public init(cancelled: ()) {
self = .cancelled
}
public init(completeUsing:Future<T>){
self = .completeUsing(completeUsing)
}
}
extension CompletionType {
@available(*, deprecated: 1.1, message: "depricated use completion",renamed: "completion")
func asCompletion() -> Completion<T> {
return self.completion
}
@available(*, deprecated: 1.1, message: "depricated use result",renamed: "result")
func asResult() -> FutureResult<T> {
return self.result
}
}
extension CompletionType {
public var description: String {
switch self.completion {
case let .success(t):
return "\(Self.self).CompletionType.Success<\(T.self)>(\(t))"
case let .fail(f):
return "\(Self.self).CompletionType.Fail<\(T.self)>(\(f))"
case .cancelled:
return "\(Self.self).CompletionType.Cancelled<\(T.self)>)"
case let .completeUsing(f):
return "\(Self.self).CompletionType.CompleteUsing<\(T.self)>(\(f.description))"
}
}
public var debugDescription: String {
return self.description
}
/**
This doesn't seem to work yet in the XCode Debugger or Playgrounds.
it seems that only NSObjectProtocol objects can use this method.
Since this is a Swift Generic, it seems to be ignored.
Sigh.
*/
func debugQuickLookObject() -> AnyObject? {
return self.debugDescription as AnyObject?
}
}
| mit | b9e92396189231bc3e0f57fdb268780c | 25.69044 | 130 | 0.572915 | 4.557917 | false | false | false | false |
kinetic-fit/sensors-swift | Sources/SwiftySensors/CyclingPowerSerializer.swift | 1 | 11371 | //
// CyclingPowerSerializer.swift
// SwiftySensors
//
// https://github.com/kinetic-fit/sensors-swift
//
// Copyright © 2017 Kinetic. All rights reserved.
//
import Foundation
/// :nodoc:
open class CyclingPowerSerializer {
public struct Features: OptionSet {
public let rawValue: UInt32
public static let PedalPowerBalanceSupported = Features(rawValue: 1 << 0)
public static let AccumulatedTorqueSupported = Features(rawValue: 1 << 1)
public static let WheelRevolutionDataSupported = Features(rawValue: 1 << 2)
public static let CrankRevolutionDataSupported = Features(rawValue: 1 << 3)
public static let ExtremeMagnitudesSupported = Features(rawValue: 1 << 4)
public static let ExtremeAnglesSupported = Features(rawValue: 1 << 5)
public static let TopAndBottomDeadSpotAnglesSupported = Features(rawValue: 1 << 6)
public static let AccumulatedEnergySupported = Features(rawValue: 1 << 7)
public static let OffsetCompensationIndicatorSupported = Features(rawValue: 1 << 8)
public static let OffsetCompensationSupported = Features(rawValue: 1 << 9)
public static let ContentMaskingSupported = Features(rawValue: 1 << 10)
public static let MultipleSensorLocationsSupported = Features(rawValue: 1 << 11)
public static let CrankLengthAdjustmentSupported = Features(rawValue: 1 << 12)
public static let ChainLengthAdjustmentSupported = Features(rawValue: 1 << 13)
public static let ChainWeightAdjustmentSupported = Features(rawValue: 1 << 14)
public static let SpanLengthAdjustmentSupported = Features(rawValue: 1 << 15)
public static let SensorMeasurementContext = Features(rawValue: 1 << 16)
public static let InstantaneousMeasurementDirectionSupported = Features(rawValue: 1 << 17)
public static let FactoryCalibrationDateSupported = Features(rawValue: 1 << 18)
public init(rawValue: UInt32) {
self.rawValue = rawValue
}
}
public static func readFeatures(_ data: Data) -> Features {
let bytes = data.map { $0 }
var rawFeatures: UInt32 = 0
if bytes.count > 0 { rawFeatures |= UInt32(bytes[0]) }
if bytes.count > 1 { rawFeatures |= UInt32(bytes[1]) << 8 }
if bytes.count > 2 { rawFeatures |= UInt32(bytes[2]) << 16 }
if bytes.count > 3 { rawFeatures |= UInt32(bytes[3]) << 24 }
return Features(rawValue: rawFeatures)
}
struct MeasurementFlags: OptionSet {
let rawValue: UInt16
static let PedalPowerBalancePresent = MeasurementFlags(rawValue: 1 << 0)
static let AccumulatedTorquePresent = MeasurementFlags(rawValue: 1 << 2)
static let WheelRevolutionDataPresent = MeasurementFlags(rawValue: 1 << 4)
static let CrankRevolutionDataPresent = MeasurementFlags(rawValue: 1 << 5)
static let ExtremeForceMagnitudesPresent = MeasurementFlags(rawValue: 1 << 6)
static let ExtremeTorqueMagnitudesPresent = MeasurementFlags(rawValue: 1 << 7)
static let ExtremeAnglesPresent = MeasurementFlags(rawValue: 1 << 8)
static let TopDeadSpotAnglePresent = MeasurementFlags(rawValue: 1 << 9)
static let BottomDeadSpotAnglePresent = MeasurementFlags(rawValue: 1 << 10)
static let AccumulatedEnergyPresent = MeasurementFlags(rawValue: 1 << 11)
static let OffsetCompensationIndicator = MeasurementFlags(rawValue: 1 << 12)
}
public struct MeasurementData: CyclingMeasurementData {
public var timestamp: Double = 0
public var instantaneousPower: Int16 = 0
public var pedalPowerBalance: UInt8?
public var pedalPowerBalanceReference: Bool?
public var accumulatedTorque: UInt16?
public var cumulativeWheelRevolutions: UInt32?
public var lastWheelEventTime: UInt16?
public var cumulativeCrankRevolutions: UInt16?
public var lastCrankEventTime: UInt16?
public var maximumForceMagnitude: Int16?
public var minimumForceMagnitude: Int16?
public var maximumTorqueMagnitude: Int16?
public var minimumTorqueMagnitude: Int16?
public var maximumAngle: UInt16?
public var minimumAngle: UInt16?
public var topDeadSpotAngle: UInt16?
public var bottomDeadSpotAngle: UInt16?
public var accumulatedEnergy: UInt16?
}
public static func readMeasurement(_ data: Data) -> MeasurementData {
var measurement = MeasurementData()
let bytes = data.map { $0 }
var index: Int = 0
if bytes.count >= 2 {
let rawFlags: UInt16 = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
let flags = MeasurementFlags(rawValue: rawFlags)
if bytes.count >= 4 {
measurement.instantaneousPower = Int16(bytes[index++=]) | Int16(bytes[index++=]) << 8
if flags.contains(.PedalPowerBalancePresent) && bytes.count >= index {
measurement.pedalPowerBalance = bytes[index++=]
measurement.pedalPowerBalanceReference = rawFlags & 0x2 == 0x2
}
if flags.contains(.AccumulatedTorquePresent) && bytes.count >= index + 1 {
measurement.accumulatedTorque = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
}
if flags.contains(.WheelRevolutionDataPresent) && bytes.count >= index + 6 {
var cumulativeWheelRevolutions = UInt32(bytes[index++=])
cumulativeWheelRevolutions |= UInt32(bytes[index++=]) << 8
cumulativeWheelRevolutions |= UInt32(bytes[index++=]) << 16
cumulativeWheelRevolutions |= UInt32(bytes[index++=]) << 24
measurement.cumulativeWheelRevolutions = cumulativeWheelRevolutions
measurement.lastWheelEventTime = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
}
if flags.contains(.CrankRevolutionDataPresent) && bytes.count >= index + 4 {
measurement.cumulativeCrankRevolutions = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
measurement.lastCrankEventTime = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
}
if flags.contains(.ExtremeForceMagnitudesPresent) && bytes.count >= index + 4 {
measurement.maximumForceMagnitude = Int16(bytes[index++=]) | Int16(bytes[index++=]) << 8
measurement.minimumForceMagnitude = Int16(bytes[index++=]) | Int16(bytes[index++=]) << 8
}
if flags.contains(.ExtremeTorqueMagnitudesPresent) && bytes.count >= index + 4 {
measurement.maximumTorqueMagnitude = Int16(bytes[index++=]) | Int16(bytes[index++=]) << 8
measurement.minimumTorqueMagnitude = Int16(bytes[index++=]) | Int16(bytes[index++=]) << 8
}
if flags.contains(.ExtremeAnglesPresent) && bytes.count >= index + 3 {
// TODO: this bit shifting is not correct.
measurement.minimumAngle = UInt16(bytes[index++=]) | UInt16(bytes[index] & 0xF0) << 4
measurement.maximumAngle = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 4
}
if flags.contains(.TopDeadSpotAnglePresent) && bytes.count >= index + 2 {
measurement.topDeadSpotAngle = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
}
if flags.contains(.BottomDeadSpotAnglePresent) && bytes.count >= index + 2 {
measurement.bottomDeadSpotAngle = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
}
if flags.contains(.AccumulatedEnergyPresent) && bytes.count >= index + 2 {
measurement.accumulatedEnergy = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
}
}
}
measurement.timestamp = Date.timeIntervalSinceReferenceDate
return measurement
}
struct VectorFlags: OptionSet {
let rawValue: UInt8
static let CrankRevolutionDataPresent = VectorFlags(rawValue: 1 << 0)
static let FirstCrankAnglePresent = VectorFlags(rawValue: 1 << 1)
static let InstantaneousForcesPresent = VectorFlags(rawValue: 1 << 2)
static let InstantaneousTorquesPresent = VectorFlags(rawValue: 1 << 3)
}
public struct VectorData {
public enum MeasurementDirection {
case unknown
case tangentialComponent
case radialComponent
case lateralComponent
}
public var instantaneousMeasurementDirection: MeasurementDirection = .unknown
public var cumulativeCrankRevolutions: UInt16?
public var lastCrankEventTime: UInt16?
public var firstCrankAngle: UInt16?
public var instantaneousForce: [Int16]?
public var instantaneousTorque: [Double]?
}
public static func readVector(_ data: Data) -> VectorData {
var vector = VectorData()
let bytes = data.map { $0 }
let flags = VectorFlags(rawValue: bytes[0])
let measurementDirection = (bytes[0] & 0x30) >> 4
switch measurementDirection {
case 0:
vector.instantaneousMeasurementDirection = .unknown
case 1:
vector.instantaneousMeasurementDirection = .tangentialComponent
case 2:
vector.instantaneousMeasurementDirection = .radialComponent
case 3:
vector.instantaneousMeasurementDirection = .lateralComponent
default:
vector.instantaneousMeasurementDirection = .unknown
}
var index: Int = 1
if flags.contains(.CrankRevolutionDataPresent) {
vector.cumulativeCrankRevolutions = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
vector.lastCrankEventTime = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
}
if flags.contains(.FirstCrankAnglePresent) {
vector.firstCrankAngle = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
}
// These two arrays are mutually exclusive
if flags.contains(.InstantaneousForcesPresent) {
} else if flags.contains(.InstantaneousTorquesPresent) {
let torqueRaw = Int16(bytes[index++=]) | Int16(bytes[index++=]) << 8
let torque = Double(torqueRaw) / 32.0
print(torque)
}
return vector
}
}
| mit | 3a93547e272ea67c7b68e981f4d24483 | 47.798283 | 115 | 0.591733 | 4.767296 | false | false | false | false |
benmatselby/sugarcrmcandybar | sugarcrmcandybarTests/SugarCRM/Record/RecordLeadTest.swift | 1 | 1184 | //
// RecordLeadTest.swift
// sugarcandybar
//
// Created by Ben Selby on 22/10/2016.
// Copyright © 2016 Ben Selby. All rights reserved.
//
import XCTest
@testable import sugarcrmcandybar
class RecordLeadTest: XCTestCase {
let jsonStructure: JSON = [
"id": "007-001-002-006",
"first_name": "Alec",
"last_name": "Trevelyan",
"description": "For England James?",
"_module": "Contacts",
]
func testGetIdReturnsIdSetInDictionary() {
let record = RecordLead(rawRecord: self.jsonStructure)
XCTAssertEqual("007-001-002-006", record.getId())
}
func testGetNameReturnsNameSetInDictionary() {
let record = RecordLead(rawRecord: self.jsonStructure)
XCTAssertEqual("Alec Trevelyan", record.getName())
}
func testGetDescriptionReturnsDescriptionSetInDictionary() {
let record = RecordLead(rawRecord: self.jsonStructure)
XCTAssertEqual("For England James?", record.getDescription())
}
func testGetModuleReturnModuleSetInDictionary() {
let record = RecordLead(rawRecord: self.jsonStructure)
XCTAssertEqual("Contacts", record.getModule())
}
}
| mit | aa9944204b3c9b1b2bcf90086bc828b0 | 27.853659 | 69 | 0.669484 | 3.943333 | false | true | false | false |
toshi0383/xcconfig-extractor | Sources/Utilities/OperatorAndFunctions.swift | 1 | 2552 | import Foundation
import PathKit
public func compare(_ l: Any, _ r: Any) -> Bool {
switch l {
case let ls as String:
if let rs = r as? String {
return ls == rs
} else {
return false
}
case let ls as [String: Any]:
if let rs = r as? [String: Any] {
return ls == rs
} else {
return false
}
case let ls as [Any]:
if let rs = r as? [Any] {
guard ls.count == rs.count else { return false }
for i in (0..<ls.count).map({ $0 }) {
if compare(ls[i], rs[i]) == false {
return false
}
}
return true
} else {
return false
}
default:
return false
}
}
public func convertToLines(_ dictionary: [String: Any]) -> [String] {
let result = dictionary.map { (k, v) -> String in
switch v {
case let s as String:
return "\(k) = \(s)"
case let s as [String]:
return "\(k) = \(s.map{$0}.joined(separator: " "))"
case is [String: Any]:
fatalError("Unexpected Object. Please file an issue if you believe this as a bug.")
default:
fatalError("Unexpected Object. Please file an issue if you believe this as a bug.")
}
}
return result
}
public func commonElements<T: Equatable>(_ args: [T]...) -> [T] {
return commonElements(args)
}
public func commonElements<T: Equatable>(_ args: [[T]]) -> [T] {
if args.isEmpty {
return []
}
var fst: [T] = args[0]
for i in (0..<fst.count).reversed() {
for cur in args.dropFirst() {
if fst.isEmpty {
return fst
}
if cur.contains(fst[i]) == false {
fst.remove(at: i)
break // this breaks only inner loop
}
}
}
return fst
}
public func distinctArray<T: Equatable>(_ array: [T]) -> [T] {
var result: [T] = []
for e in array {
if result.contains(e) == false {
result.append(e)
}
}
return result
}
// MARK: Operators
infix operator +|
public func +|<T: Equatable>(l: [T], r: [T]) -> [T] {
var o = l
o.append(contentsOf: r)
return o
}
public func -<T: Equatable>(l: [T], r: [T]) -> [T] {
return l.filter { t in r.contains(t) == false }
}
public func ==(lhs: [String: Any], rhs: [String: Any] ) -> Bool {
return NSDictionary(dictionary: lhs).isEqual(to: rhs)
}
| mit | 9faf57a92a588a923b639871335fa5c5 | 25.583333 | 95 | 0.492163 | 3.775148 | false | false | false | false |
alblue/swift | test/IRGen/generic_types.swift | 1 | 5114 | // RUN: %target-swift-frontend %s -emit-ir | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime
// REQUIRES: CPU=x86_64
// CHECK: [[A:%T13generic_types1AC]] = type <{ [[REF:%swift.refcounted]], [[INT:%TSi]] }>
// CHECK: [[INT]] = type <{ i64 }>
// CHECK: [[B:%T13generic_types1BC]] = type <{ [[REF:%swift.refcounted]], [[UNSAFE:%TSp]] }>
// CHECK: [[C:%T13generic_types1CC]] = type
// CHECK: [[D:%T13generic_types1DC]] = type
// CHECK-LABEL: @"$s13generic_types1ACMI" = internal global [16 x i8*] zeroinitializer, align 8
// CHECK-LABEL: @"$s13generic_types1ACMn" = hidden constant
// CHECK-SAME: i32 -2147483440,
// CHECK-SAME: @"$s13generic_typesMXM"
// <name>
// CHECK-SAME: @"$s13generic_types1ACMa"
// -- superclass
// CHECK-SAME: i32 0,
// -- negative size in words
// CHECK-SAME: i32 2,
// -- positive size in words
// CHECK-SAME: i32 17,
// -- num immediate members
// CHECK-SAME: i32 7,
// -- num fields
// CHECK-SAME: i32 1,
// -- field offset vector offset
// CHECK-SAME: i32 16,
// -- instantiation cache
// CHECK-SAME: @"$s13generic_types1ACMI"
// -- instantiation pattern
// CHECK-SAME: @"$s13generic_types1ACMP"
// -- num generic params
// CHECK-SAME: i16 1,
// -- num generic requirement
// CHECK-SAME: i16 0,
// -- num key arguments
// CHECK-SAME: i16 1,
// -- num extra arguments
// CHECK-SAME: i16 0,
// -- parameter descriptor 1
// CHECK-SAME: i8 -128,
// CHECK-LABEL: @"$s13generic_types1ACMP" = internal constant
// -- instantiation function
// CHECK-SAME: @"$s13generic_types1ACMi"
// -- heap destructor
// CHECK-SAME: void ([[A]]*)* @"$s13generic_types1ACfD"
// -- ivar destroyer
// CHECK-SAME: i32 0,
// -- flags
// CHECK-SAME: i32 {{3|2}},
// CHECK-SAME: }
// CHECK-LABEL: @"$s13generic_types1BCMI" = internal global [16 x i8*] zeroinitializer, align 8
// CHECK-LABEL: @"$s13generic_types1BCMn" = hidden constant
// CHECK-SAME: @"$s13generic_types1BCMa"
// CHECK-SAME: @"$s13generic_types1BCMI"
// CHECK-SAME: @"$s13generic_types1BCMP"
// CHECK-LABEL: @"$s13generic_types1BCMP" = internal constant
// -- instantiation function
// CHECK-SAME: @"$s13generic_types1BCMi"
// -- heap destructor
// CHECK-SAME: void ([[B]]*)* @"$s13generic_types1BCfD"
// -- ivar destroyer
// CHECK-SAME: i32 0,
// -- class flags
// CHECK-SAME: i32 {{3|2}},
// CHECK-SAME: }
// CHECK-LABEL: @"$s13generic_types1CCMP" = internal constant
// -- instantiation function
// CHECK-SAME: @"$s13generic_types1CCMi"
// -- heap destructor
// CHECK-SAME: void ([[C]]*)* @"$s13generic_types1CCfD"
// -- ivar destroyer
// CHECK-SAME: i32 0,
// -- class flags
// CHECK-SAME: i32 {{3|2}},
// CHECK-SAME: }
// CHECK-LABEL: @"$s13generic_types1DCMP" = internal constant
// -- instantiation function
// CHECK-SAME: @"$s13generic_types1DCMi"
// -- heap destructor
// CHECK-SAME: void ([[D]]*)* @"$s13generic_types1DCfD"
// -- ivar destroyer
// CHECK-SAME: i32 0,
// -- class flags
// CHECK-SAME: i32 {{3|2}},
// CHECK-SAME: }
class A<T> {
var x = 0
func run(_ t: T) {}
init(y : Int) {}
}
class B<T> {
var ptr : UnsafeMutablePointer<T>
init(ptr: UnsafeMutablePointer<T>) {
self.ptr = ptr
}
deinit {
ptr.deinitialize(count: 1)
}
}
class C<T> : A<Int> {}
class D<T> : A<Int> {
override func run(_ t: Int) {}
}
struct E<T> {
var x : Int
func foo() { bar() }
func bar() {}
}
class ClassA {}
class ClassB {}
// This type is fixed-size across specializations, but it needs to use
// a different implementation in IR-gen so that types match up.
// It just asserts if we get it wrong.
struct F<T: AnyObject> {
var value: T
}
func testFixed() {
var a = F(value: ClassA()).value
var b = F(value: ClassB()).value
}
// Checking generic requirement encoding
protocol P1 { }
protocol P2 {
associatedtype A
}
struct X1: P1 { }
struct X2: P2 {
typealias A = X1
}
// Check for correct root generic parameters in the generic requirements of X3.
// CHECK-LABEL: @"$sq_1A13generic_types2P2P_MXA" = linkonce_odr hidden constant
// Root: generic parameter 1
// CHECK-SAME: i32 1
// Protocol P2
// CHECK-SAME: $s13generic_types2P2Mp
struct X3<T, U> where U: P2, U.A: P1 { }
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} internal %swift.type* @"$s13generic_types1ACMi"(%swift.type_descriptor*, i8**, i8*) {{.*}} {
// CHECK: [[T0:%.*]] = bitcast i8** %1 to %swift.type**
// CHECK: %T = load %swift.type*, %swift.type** [[T0]],
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_descriptor* %0, i8** %1, i8* %2)
// CHECK-NEXT: ret %swift.type* [[METADATA]]
// CHECK: }
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} internal %swift.type* @"$s13generic_types1BCMi"(%swift.type_descriptor*, i8**, i8*) {{.*}} {
// CHECK: [[T0:%.*]] = bitcast i8** %1 to %swift.type**
// CHECK: %T = load %swift.type*, %swift.type** [[T0]],
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_descriptor* %0, i8** %1, i8* %2)
// CHECK-NEXT: ret %swift.type* [[METADATA]]
// CHECK: }
| apache-2.0 | df77216a5e499195daa7e8405e83bf24 | 28.732558 | 149 | 0.627493 | 2.937392 | false | false | false | false |
e-government-ua/iMobile | iGov/SMSTableViewCell.swift | 1 | 1903 | //
// SMSTableViewCell.swift
// iGov
//
// Created by Sergii Maksiuta on 2/27/17.
// Copyright © 2017 iGov. All rights reserved.
//
import UIKit
class SMSTableViewCell: UITableViewCell {
static let kReuseID = "SMSTableViewCell"
var textFields = [UITextField]()
let smsdigits = 6
override func awakeFromNib() {
super.awakeFromNib()
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
let offset:CGFloat = 15.0
let fieldWidth = (self.bounds.size.width-CGFloat(smsdigits+1)*offset)/CGFloat(smsdigits)
let container = UIView()
self.addSubview(container)
container.snp.makeConstraints { (make) in
make.width.equalTo(CGFloat(smsdigits)*fieldWidth + CGFloat(smsdigits + 1)*offset)
make.top.bottom.equalTo(self)
make.centerX.equalTo(self)
}
for i in 1...smsdigits{
let textField = UITextField()
textField.keyboardType = .numberPad
textFields.append(textField)
container.addSubview(textField);
textField.backgroundColor = UIColor.red
textField.snp.makeConstraints({ (make) in
make.left.equalTo(CGFloat(i - 1)*fieldWidth+CGFloat(i)*offset)
make.width.equalTo(fieldWidth)
make.centerY.height.equalTo(self)
});
}
}
func numberFromSMSCode () -> String {
var result : String = ""
for field in textFields
{
result += field.text!
}
return result
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
class var reuseIdentifier: String{
return kReuseID
}
}
| gpl-3.0 | 06c0c9a68cae5f3a94a5ff78c6394c69 | 28.261538 | 96 | 0.590957 | 4.661765 | false | false | false | false |
P0ed/Magikombat | Magikombat/LevelKit/LevelGenerator.swift | 1 | 3018 | import Foundation
import GameplayKit
private struct PlatformDimensions {
var minWidth = 8
var maxWidth = 32
var requiredHeight = 16
}
private let platformDimensions = PlatformDimensions()
final class TileMapGenerator {
var map: TileMap
var steps: [TileMap] = []
let random: GKARC4RandomSource
init(seed: Int, width: Int, height: Int) {
var seedValue = seed
let seedData = NSData(bytes: &seedValue, length: sizeof(seedValue.dynamicType))
random = GKARC4RandomSource(seed: seedData)
map = TileMap(width: width, height: height)
}
func generateLevel() -> Level {
let walls = makeWalls()
let floor = makeFloor(walls)
makePlatforms(floor)
return Level(rootNode: walls.first!, size: map.size)
}
private func makePlatform(at position: Position, length: Int, type: Tile) -> PlatformNode {
return makePlatform(at: position, size: Size(width: length, height: 1), type: type)
}
private func makePlatform(at position: Position, size: Size, type: Tile) -> PlatformNode{
let platform = Platform(position: position, size: size, type: type)
platform.forEach {
map.setTile(type, at: $0)
}
return PlatformNode(platform)
}
private func makeWalls() -> [PlatformNode] {
let left = makePlatform(at: Position(x: 0, y: 0), size: Size(width: 8, height: map.size.height), type: .Wall)
let right = makePlatform(at: Position(x: map.size.width - 8, y: 0), size: Size(width: 8, height: map.size.height), type: .Wall)
return [left, right]
}
private func makeFloor(walls: [PlatformNode]) -> [PlatformNode] {
let leftWallWidth = walls.first!.platform.size.width
let rightWallWidth = walls.last!.platform.size.width
var emptyTiles = map.size.width - leftWallWidth - rightWallWidth
var floorPlatforms = [PlatformNode]()
while emptyTiles > platformDimensions.minWidth + platformDimensions.maxWidth {
let width = platformDimensions.minWidth + random.nextIntWithUpperBound(platformDimensions.maxWidth - platformDimensions.minWidth)
let platform = makePlatform(at: Position(x: map.size.width - emptyTiles - leftWallWidth, y: 0), length: width, type: .Platform)
platform.left = floorPlatforms.last ?? walls.first
floorPlatforms.append(platform)
emptyTiles -= width
}
let lastPlatform = makePlatform(at: Position(x: map.size.width - emptyTiles - leftWallWidth, y: 0), length: emptyTiles, type: .Platform)
lastPlatform.left = floorPlatforms.last
lastPlatform.right = walls.last
return floorPlatforms
}
private func makePlatforms(floor: [PlatformNode]) {
var topPlatforms = floor
let platformIndex = random.nextIntWithUpperBound(topPlatforms.count)
let parent = topPlatforms[platformIndex]
let height = platformDimensions.requiredHeight / 2 + random.nextIntWithUpperBound(platformDimensions.requiredHeight / 2)
let position = Position(x: parent.platform.position.x, y: parent.platform.position.y + height)
let platform = makePlatform(at: position, length: parent.platform.size.width, type: .Platform)
platform.bottom = parent
}
}
| mit | 1c31ca57403ee5cb1e2b288b80cac35b | 31.451613 | 138 | 0.737906 | 3.476959 | false | false | false | false |
JadenGeller/Helium | Helium/Helium/Window/HeliumWindowController.swift | 1 | 9531 | //
// HeliumWindowController.swift
// Helium
//
// Created by Jaden Geller on 4/9/15.
// Copyright (c) 2015 Jaden Geller. All rights reserved.
//
import AppKit
import OpenCombine
import OpenCombineFoundation
import WebKit
class HeliumWindowController: NSWindowController, NSWindowDelegate {
convenience init() {
self.init(window: nil)
}
// FIXME: Don't use IUO or var here
var toolbar: BrowserToolbar!
private override init(window: NSWindow?) {
precondition(window == nil, "call init() with no window")
let webController = WebViewController()
webController.view.frame.size = .init(width: 480, height: 300)
let window = HeliumWindow(contentViewController: webController)
window.bind(.title, to: webController, withKeyPath: "title", options: nil)
super.init(window: window)
window.delegate = self
// FIXME: Are there memeory leaks here?
toolbar = BrowserToolbar(model: BrowserToolbar.Model(
directionalNagivationButtonsModel: DirectionalNavigationButtonsToolbarItem.Model(
observeCanGoBack: { handler in
self.webViewController.webView.observe(\.canGoBack, options: [.initial, .new]) { webView, change in
handler(change.newValue!)
}
},
observeCanGoForward: { handler in
self.webViewController.webView.observe(\.canGoForward, options: [.initial, .new]) { webView, change in
handler(change.newValue!)
}
},
backForwardList: webViewController.webView.backForwardList,
navigateToBackForwardListItem: { backForwardListItem in webController.webView.go(to: backForwardListItem) }
),
searchFieldModel: SearchFieldToolbarItem.Model(
observeLocation: { handler in
self.webViewController.webView.observe(\.url, options: [.initial, .new]) { webView, change in
handler(change.newValue!)
}
},
navigateWithSearchTerm: { searchTerm in webController.loadAlmostURL(searchTerm) }
),
zoomVideoToolbarButtonModel: ZoomVideoButtonToolbarItem.Model(
zoomVideo: { self.webViewController.zoomVideo() }
),
hideToolbarButtonModel: HideToolbarButtonToolbarItem.Model(
hideToolbar: { self.toolbarVisibility = .hidden }
)
))
window.titleVisibility = .hidden
window.toolbar = toolbar
NotificationCenter.default.addObserver(self, selector: #selector(HeliumWindowController.didBecomeActive), name: NSApplication.didBecomeActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(HeliumWindowController.willResignActive), name: NSApplication.willResignActiveNotification, object: nil)
cancellables.append(UserSetting.$disabledFullScreenFloat.sink { [unowned self] disabledFullScreenFloat in
if disabledFullScreenFloat {
self.window!.collectionBehavior.remove(.canJoinAllSpaces)
self.window!.collectionBehavior.insert(.moveToActiveSpace)
} else {
self.window!.collectionBehavior.remove(.moveToActiveSpace)
self.window!.collectionBehavior.insert(.canJoinAllSpaces)
}
})
cancellables.append(UserSetting.$translucencyMode.sink { [unowned self] _ in
self.updateTranslucency()
})
cancellables.append(UserSetting.$translucencyEnabled.sink { [unowned self] _ in
self.updateTranslucency()
})
cancellables.append(UserSetting.$opacityPercentage.sink { [unowned self] _ in
self.updateTranslucency()
})
cancellables.append(UserSetting.$toolbarVisibility.assign(to: \.toolbarVisibility, on: self))
}
var toolbarVisibility: ToolbarVisibility = UserSetting.toolbarVisibility {
didSet {
switch toolbarVisibility {
case .visible:
window!.styleMask.insert(.titled)
window!.toolbar = toolbar
case .hidden:
window!.styleMask.remove(.titled)
window!.toolbar = nil
}
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var webViewController: WebViewController {
get {
return self.window?.contentViewController as! WebViewController
}
}
private var mouseOver: Bool = false
var shouldBeTranslucentForMouseState: Bool {
guard UserSetting.translucencyEnabled else { return false }
switch UserSetting.translucencyMode {
case .always:
return true
case .mouseOver:
return mouseOver
case .mouseOutside:
return !mouseOver
}
}
func updateTranslucency() {
if !NSApplication.shared.isActive {
window!.ignoresMouseEvents = shouldBeTranslucentForMouseState
}
if shouldBeTranslucentForMouseState {
window!.animator().alphaValue = CGFloat(UserSetting.opacityPercentage) / 100
window!.isOpaque = false
}
else {
window!.isOpaque = true
window!.animator().alphaValue = 1
}
}
// MARK: Window lifecycle
var cancellables: [AnyCancellable] = []
// MARK: Mouse events
override func mouseEntered(with event: NSEvent) {
mouseOver = true
updateTranslucency()
}
override func mouseExited(with event: NSEvent) {
mouseOver = false
updateTranslucency()
}
// MARK: Translucency
@objc func openLocationPress(_ sender: AnyObject) {
let alert = NSAlert()
alert.alertStyle = .informational
alert.messageText = "Enter Destination URL"
let urlField = NSTextField()
urlField.frame = NSRect(x: 0, y: 0, width: 300, height: 20)
urlField.lineBreakMode = .byTruncatingHead
urlField.usesSingleLineMode = true
alert.accessoryView = urlField
alert.accessoryView!.becomeFirstResponder()
alert.addButton(withTitle: "Load")
alert.addButton(withTitle: "Cancel")
alert.beginSheetModal(for: self.window!, completionHandler: { response in
if response == .alertFirstButtonReturn {
// Load
let text = (alert.accessoryView as! NSTextField).stringValue
self.webViewController.loadAlmostURL(text)
}
})
urlField.becomeFirstResponder()
}
@objc func openFilePress(_ sender: AnyObject) {
let open = NSOpenPanel()
open.allowsMultipleSelection = false
open.canChooseFiles = true
open.canChooseDirectories = false
if open.runModal() == .OK {
if let url = open.url {
webViewController.loadURL(url)
}
}
}
@objc func setHomePage(_ sender: AnyObject){
let alert = NSAlert()
alert.alertStyle = .informational
alert.messageText = "Enter new Home Page URL"
let urlField = NSTextField()
urlField.frame = NSRect(x: 0, y: 0, width: 300, height: 20)
urlField.lineBreakMode = .byTruncatingHead
urlField.usesSingleLineMode = true
alert.accessoryView = urlField
alert.addButton(withTitle: "Set")
alert.addButton(withTitle: "Cancel")
alert.beginSheetModal(for: self.window!, completionHandler: { response in
if response == .alertFirstButtonReturn {
var text = (alert.accessoryView as! NSTextField).stringValue
// Add prefix if necessary
if !(text.lowercased().hasPrefix("http://") || text.lowercased().hasPrefix("https://")) {
text = "http://" + text
}
// Save to defaults if valid. Else, use Helium default page
if self.validateURL(text) {
UserSetting.homePageURL = text
}
else{
UserSetting.homePageURL = nil
}
}
})
}
//MARK: Actual functionality
func validateURL(_ stringURL: String) -> Bool {
let urlRegEx = "((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+"
let predicate = NSPredicate(format:"SELF MATCHES %@", argumentArray:[urlRegEx])
return predicate.evaluate(with: stringURL)
}
override func showWindow(_ sender: Any?) {
super.showWindow(sender)
// Focus search field
if let searchFieldItem = window?.toolbar?.items.first(where: { item in
item.itemIdentifier == .searchField
}) as! SearchFieldToolbarItem? {
window?.makeFirstResponder(searchFieldItem.view)
}
}
@objc private func didBecomeActive() {
window!.ignoresMouseEvents = false
}
@objc private func willResignActive() {
guard let window = window else { return }
window.ignoresMouseEvents = !window.isOpaque
}
}
| mit | 3fc9985a0b9aee7b6cafdebb63f64d73 | 35.799228 | 177 | 0.594271 | 5.461891 | false | false | false | false |
sharath-cliqz/browser-ios | Utils/Extensions/HexExtensions.swift | 2 | 2160 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
extension String {
public var hexDecodedData: Data {
// Convert to a CString and make sure it has an even number of characters (terminating 0 is included, so we
// check for uneven!)
guard let cString = self.cString(using: String.Encoding.ascii), (cString.count % 2) == 1 else {
return Data()
}
var result = Data(capacity: (cString.count - 1) / 2)
for i in stride(from: 0, to: (cString.count - 1), by: 2) {
guard let l = hexCharToByte(cString[i]), let r = hexCharToByte(cString[i+1]) else {
return Data()
}
var value: UInt8 = (l << 4) | r
result.append(&value, count: MemoryLayout.size(ofValue: value))
}
return result
}
fileprivate func hexCharToByte(_ c: CChar) -> UInt8? {
if c >= 48 && c <= 57 { // 0 - 9
return UInt8(c - 48)
}
if c >= 97 && c <= 102 { // a - f
return 10 + UInt8(c - 97)
}
if c >= 65 && c <= 70 { // A - F
return 10 + UInt8(c - 65)
}
return nil
}
}
private let HexDigits: [String] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]
extension Data {
public var hexEncodedString: String {
var result = String()
result.reserveCapacity(count * 2)
withUnsafeBytes { (p: UnsafePointer<UInt8>) in
for i in 0..<count {
result.append(HexDigits[Int((p[i] & 0xf0) >> 4)])
result.append(HexDigits[Int(p[i] & 0x0f)])
}
}
return String(result)
}
public static func randomOfLength(_ length: UInt) -> Data? {
let length = Int(length)
var data = Data(count: length)
var result: Int32 = 0
data.withUnsafeMutableBytes { (p: UnsafeMutablePointer<UInt8>) in
result = SecRandomCopyBytes(kSecRandomDefault, length, p)
}
return result == 0 ? data : nil
}
}
extension Data {
public var base64EncodedString: String {
return self.base64EncodedString(options: Data.Base64EncodingOptions())
}
}
| mpl-2.0 | 622dfe9bac211bda7264fb75d585cf5a | 29.857143 | 114 | 0.603704 | 3.26284 | false | false | false | false |
PJayRushton/TeacherTools | TeacherTools/GetICloudUser.swift | 1 | 1219 | //
// GetICloudUser.swift
// Wasatch Transportation
//
// Created by Parker Rushton on 10/18/16.
// Copyright © 2016 PJR. All rights reserved.
//
import Foundation
import CloudKit
struct GetICloudUser: Command {
func execute(state: AppState, core: Core<AppState>) {
let container = CKContainer.default()
container.fetchUserRecordID { recordId, error in
if let recordId = recordId, error == nil {
let iCloudId = recordId.recordName
core.fire(event: ICloudUserIdentified(icloudId: iCloudId))
core.fire(command: GetCurrentUser(iCloudId: iCloudId))
} else {
core.fire(event: ErrorEvent(error: error, message: nil))
core.fire(event: ICloudUserIdentified(icloudId: nil))
self.postErrorNotification()
}
}
}
func postErrorNotification() {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
NotificationCenter.default.post(name: NSNotification.Name.iCloudError, object: nil)
}
}
}
extension NSNotification.Name {
static let iCloudError = NSNotification.Name(rawValue: "iCloudError")
}
| mit | 98a652cfe42f818016842000fe75f74c | 30.230769 | 95 | 0.630542 | 4.445255 | false | false | false | false |
Ramotion/animated-tab-bar | RAMAnimatedTabBarController/Animations/FrameAnimation/RAMFrameItemAnimation.swift | 1 | 4947 | // RAMFrameItemAnimation.swift
//
// Copyright (c) 11/10/14 Ramotion Inc. (http://ramotion.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 QuartzCore
import UIKit
/// The RAMFrameItemAnimation class provides keyframe animation.
open class RAMFrameItemAnimation: RAMItemAnimation {
@nonobjc fileprivate var animationImages: Array<CGImage> = Array()
var selectedImage: UIImage!
/// A Boolean value indicated plaing revers animation when UITabBarItem unselected, if false image change immediately, defalut value true
@IBInspectable open var isDeselectAnimation: Bool = true
/// path to array of image names from plist file
@IBInspectable open var imagesPath: String!
open override func awakeFromNib() {
guard let path = Bundle.main.path(forResource: imagesPath, ofType: "plist") else {
fatalError("don't found plist")
}
guard case let animationImagesName as [String] = NSArray(contentsOfFile: path) else {
fatalError()
}
createImagesArray(animationImagesName)
// selected image
let selectedImageName = animationImagesName[animationImagesName.endIndex - 1]
selectedImage = UIImage(named: selectedImageName)
}
func createImagesArray(_ imageNames: Array<String>) {
for name: String in imageNames {
if let image = UIImage(named: name)?.cgImage {
animationImages.append(image)
}
}
}
// MARK: public
/**
Set images for keyframe animation
- parameter images: images for keyframe animation
*/
open func setAnimationImages(_ images: Array<UIImage>) {
var animationImages = Array<CGImage>()
for image in images {
if let cgImage = image.cgImage {
animationImages.append(cgImage)
}
}
self.animationImages = animationImages
}
// MARK: RAMItemAnimationProtocol
/**
Start animation, method call when UITabBarItem is selected
- parameter icon: animating UITabBarItem icon
- parameter textLabel: animating UITabBarItem textLabel
*/
open override func playAnimation(_ icon: UIImageView, textLabel: UILabel) {
playFrameAnimation(icon, images: animationImages)
textLabel.textColor = textSelectedColor
}
/**
Start animation, method call when UITabBarItem is unselected
- parameter icon: animating UITabBarItem icon
- parameter textLabel: animating UITabBarItem textLabel
- parameter defaultTextColor: default UITabBarItem text color
- parameter defaultIconColor: default UITabBarItem icon color
*/
open override func deselectAnimation(_ icon: UIImageView, textLabel: UILabel, defaultTextColor: UIColor, defaultIconColor _: UIColor) {
if isDeselectAnimation {
playFrameAnimation(icon, images: animationImages.reversed())
}
textLabel.textColor = defaultTextColor
}
/**
Method call when TabBarController did load
- parameter icon: animating UITabBarItem icon
- parameter textLabel: animating UITabBarItem textLabel
*/
open override func selectedState(_ icon: UIImageView, textLabel: UILabel) {
icon.image = selectedImage
textLabel.textColor = textSelectedColor
}
@nonobjc func playFrameAnimation(_ icon: UIImageView, images: Array<CGImage>) {
let frameAnimation = CAKeyframeAnimation(keyPath: Constants.AnimationKeys.keyFrame)
frameAnimation.calculationMode = CAAnimationCalculationMode.discrete
frameAnimation.duration = TimeInterval(duration)
frameAnimation.values = images
frameAnimation.repeatCount = 1
frameAnimation.isRemovedOnCompletion = false
frameAnimation.fillMode = CAMediaTimingFillMode.forwards
icon.layer.add(frameAnimation, forKey: nil)
}
}
| mit | 5a47a6b801588292fc6fa6993ead8823 | 36.477273 | 141 | 0.703861 | 5.394766 | false | false | false | false |
PjGeeroms/IOSRecipeDB | YummlyProject/Service/Service.swift | 1 | 3988 | //
// Service.swift
// YummlyProject
//
// Created by Pieter-Jan Geeroms on 21/12/2016.
// Copyright © 2016 Pieter-Jan Geeroms. All rights reserved.
//
import Foundation
import SwiftyJSON
import Alamofire
class Service {
// Singleton of service
static let shared = Service();
// Create a sessionmanager with config ephemeral
let sessionManager = Alamofire.SessionManager(configuration: URLSessionConfiguration.ephemeral)
// Api url
let baseApi = "http://recipedb.pw/api/"
let user = User()
}
/**
* Object Serializable
*/
protocol ResponseObjectSerializable {
init?(response: HTTPURLResponse, representation: Any)
}
extension DataRequest {
func responseObject<T: ResponseObjectSerializable>(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DataResponse<T>) -> Void)
-> Self
{
let responseSerializer = DataResponseSerializer<T> { request, response, data, error in
guard error == nil else { return .failure(BackendError.network(error: error!)) }
let jsonResponseSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments)
let result = jsonResponseSerializer.serializeResponse(request, response, data, nil)
guard case let .success(jsonObject) = result else {
return .failure(BackendError.jsonSerialization(error: result.error!))
}
guard let response = response, let responseObject = T(response: response, representation: jsonObject) else {
return .failure(BackendError.objectSerialization(reason: "JSON could not be serialized: \(jsonObject)"))
}
return .success(responseObject)
}
return response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
}
}
/**
* Collection Serializable
*/
protocol ResponseCollectionSerializable {
static func collection(from response: HTTPURLResponse, withRepresentation representation: Any) -> [Self]
}
extension ResponseCollectionSerializable where Self: ResponseObjectSerializable {
static func collection(from response: HTTPURLResponse, withRepresentation representation: Any) -> [Self] {
var collection: [Self] = []
if let representation = representation as? [[String: Any]] {
for itemRepresentation in representation {
if let item = Self(response: response, representation: itemRepresentation) {
collection.append(item)
}
}
}
return collection
}
}
extension DataRequest {
@discardableResult
func responseCollection<T: ResponseCollectionSerializable>(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DataResponse<[T]>) -> Void) -> Self
{
let responseSerializer = DataResponseSerializer<[T]> { request, response, data, error in
guard error == nil else { return .failure(BackendError.network(error: error!)) }
let jsonSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments)
let result = jsonSerializer.serializeResponse(request, response, data, nil)
guard case let .success(jsonObject) = result else {
return .failure(BackendError.jsonSerialization(error: result.error!))
}
guard let response = response else {
let reason = "Response collection could not be serialized due to nil response."
return .failure(BackendError.objectSerialization(reason: reason))
}
return .success(T.collection(from: response, withRepresentation: jsonObject))
}
return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
}
}
| mit | ef75492607b6ea871be0ffc82a550a28 | 33.669565 | 120 | 0.647103 | 5.568436 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Post/PostEditorNavigationBarManager.swift | 1 | 7608 | import Gridicons
protocol PostEditorNavigationBarManagerDelegate: AnyObject {
var publishButtonText: String { get }
var isPublishButtonEnabled: Bool { get }
var uploadingButtonSize: CGSize { get }
var savingDraftButtonSize: CGSize { get }
func navigationBarManager(_ manager: PostEditorNavigationBarManager, closeWasPressed sender: UIButton)
func navigationBarManager(_ manager: PostEditorNavigationBarManager, moreWasPressed sender: UIButton)
func navigationBarManager(_ manager: PostEditorNavigationBarManager, blogPickerWasPressed sender: UIButton)
func navigationBarManager(_ manager: PostEditorNavigationBarManager, publishButtonWasPressed sender: UIButton)
func navigationBarManager(_ manager: PostEditorNavigationBarManager, displayCancelMediaUploads sender: UIButton)
func navigationBarManager(_ manager: PostEditorNavigationBarManager, reloadTitleView view: UIView)
}
// A class to share the navigation bar UI of the Post Editor.
// Currenly shared between Aztec and Gutenberg
//
class PostEditorNavigationBarManager {
weak var delegate: PostEditorNavigationBarManagerDelegate?
// MARK: - Buttons
/// Dismiss Button
///
lazy var closeButton: WPButtonForNavigationBar = {
let cancelButton = WPStyleGuide.buttonForBar(with: Assets.closeButtonModalImage, target: self, selector: #selector(closeWasPressed))
cancelButton.leftSpacing = Constants.cancelButtonPadding.left
cancelButton.rightSpacing = Constants.cancelButtonPadding.right
cancelButton.setContentHuggingPriority(.required, for: .horizontal)
cancelButton.accessibilityIdentifier = "editor-close-button"
return cancelButton
}()
private lazy var moreButton: UIButton = {
let image = UIImage.gridicon(.ellipsis)
let button = UIButton(type: .system)
button.setImage(image, for: .normal)
button.frame = CGRect(origin: .zero, size: image.size)
button.accessibilityLabel = NSLocalizedString("More Options", comment: "Action button to display more available options")
button.accessibilityIdentifier = "more_post_options"
button.addTarget(self, action: #selector(moreWasPressed), for: .touchUpInside)
button.setContentHuggingPriority(.required, for: .horizontal)
return button
}()
/// Blog Picker's Button
///
lazy var blogPickerButton: WPBlogSelectorButton = {
let button = WPBlogSelectorButton(frame: .zero, buttonStyle: .typeSingleLine)
button.addTarget(self, action: #selector(blogPickerWasPressed), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
button.setContentHuggingPriority(.defaultLow, for: .horizontal)
return button
}()
/// Blog TitleView Label
lazy var blogTitleViewLabel: UILabel = {
let label = UILabel()
label.textColor = .appBarText
label.font = Fonts.blogTitle
return label
}()
/// Publish Button
private(set) lazy var publishButton: UIButton = {
let button = UIButton(type: .system)
button.addTarget(self, action: #selector(publishButtonTapped(sender:)), for: .touchUpInside)
button.setTitle(delegate?.publishButtonText ?? "", for: .normal)
button.sizeToFit()
button.isEnabled = delegate?.isPublishButtonEnabled ?? false
button.setContentHuggingPriority(.required, for: .horizontal)
return button
}()
/// Media Uploading Button
///
private lazy var mediaUploadingButton: WPUploadStatusButton = {
let button = WPUploadStatusButton(frame: CGRect(origin: .zero, size: delegate?.uploadingButtonSize ?? .zero))
button.setTitle(NSLocalizedString("Media Uploading", comment: "Message to indicate progress of uploading media to server"), for: .normal)
button.addTarget(self, action: #selector(displayCancelMediaUploads), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
button.setContentHuggingPriority(.defaultLow, for: .horizontal)
return button
}()
/// Preview Generating Button
///
private lazy var previewGeneratingView: LoadingStatusView = {
let view = LoadingStatusView(title: NSLocalizedString("Generating Preview", comment: "Message to indicate progress of generating preview"))
return view
}()
// MARK: - Bar button items
/// Negative Offset BarButtonItem: Used to fine tune navigationBar Items
///
internal lazy var separatorButtonItem: UIBarButtonItem = {
let separator = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
return separator
}()
/// NavigationBar's Close Button
///
lazy var closeBarButtonItem: UIBarButtonItem = {
let cancelItem = UIBarButtonItem(customView: self.closeButton)
cancelItem.accessibilityLabel = NSLocalizedString("Close", comment: "Action button to close edior and cancel changes or insertion of post")
cancelItem.accessibilityIdentifier = "Close"
return cancelItem
}()
/// Publish Button
private(set) lazy var publishBarButtonItem: UIBarButtonItem = {
let button = UIBarButtonItem(customView: self.publishButton)
return button
}()
/// NavigationBar's More Button
///
lazy var moreBarButtonItem: UIBarButtonItem = {
let moreItem = UIBarButtonItem(customView: self.moreButton)
return moreItem
}()
// MARK: - Selectors
@objc private func closeWasPressed(sender: UIButton) {
delegate?.navigationBarManager(self, closeWasPressed: sender)
}
@objc private func moreWasPressed(sender: UIButton) {
delegate?.navigationBarManager(self, moreWasPressed: sender)
}
@objc private func blogPickerWasPressed(sender: UIButton) {
delegate?.navigationBarManager(self, blogPickerWasPressed: sender)
}
@objc private func publishButtonTapped(sender: UIButton) {
delegate?.navigationBarManager(self, publishButtonWasPressed: sender)
}
@objc private func displayCancelMediaUploads(sender: UIButton) {
delegate?.navigationBarManager(self, displayCancelMediaUploads: sender)
}
// MARK: - Public
var leftBarButtonItems: [UIBarButtonItem] {
return [separatorButtonItem, closeBarButtonItem]
}
var uploadingMediaTitleView: UIView {
mediaUploadingButton
}
var generatingPreviewTitleView: UIView {
previewGeneratingView
}
var rightBarButtonItems: [UIBarButtonItem] {
return [moreBarButtonItem, publishBarButtonItem, separatorButtonItem]
}
func reloadPublishButton() {
publishButton.setTitle(delegate?.publishButtonText ?? "", for: .normal)
publishButton.sizeToFit()
publishButton.isEnabled = delegate?.isPublishButtonEnabled ?? true
}
func reloadBlogTitleView(text: String) {
blogTitleViewLabel.text = text
}
func reloadTitleView(_ view: UIView) {
delegate?.navigationBarManager(self, reloadTitleView: view)
}
}
extension PostEditorNavigationBarManager {
private enum Constants {
static let cancelButtonPadding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 5)
}
private enum Fonts {
static let semiBold = WPFontManager.systemSemiBoldFont(ofSize: 16)
static var blogTitle: UIFont {
WPStyleGuide.navigationBarStandardFont
}
}
private enum Assets {
static let closeButtonModalImage = UIImage.gridicon(.cross)
}
}
| gpl-2.0 | 4191abc4e693c8b4cc95e709f29c7b42 | 37.424242 | 147 | 0.709648 | 5.29805 | false | false | false | false |
StephenVinouze/ios-charts | ChartsRealm/Classes/Data/RealmScatterDataSet.swift | 2 | 1603 | //
// RealmScatterDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import Charts
import Realm
import Realm.Dynamic
public class RealmScatterDataSet: RealmLineScatterCandleRadarDataSet, IScatterChartDataSet
{
// The size the scatter shape will have
public var scatterShapeSize = CGFloat(15.0)
// The type of shape that is set to be drawn where the values are at
// **default**: .Square
public var scatterShape = ScatterChartDataSet.ScatterShape.Square
// The radius of the hole in the shape (applies to Square, Circle and Triangle)
// **default**: 0.0
public var scatterShapeHoleRadius: CGFloat = 0.0
// Color for the hole in the shape. Setting to `nil` will behave as transparent.
// **default**: nil
public var scatterShapeHoleColor: NSUIColor? = nil
// Custom path object to draw where the values are at.
// This is used when shape is set to Custom.
public var customScatterShape: CGPath?
public override func initialize()
{
}
// MARK: NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
let copy = super.copyWithZone(zone) as! RealmScatterDataSet
copy.scatterShapeSize = scatterShapeSize
copy.scatterShape = scatterShape
copy.customScatterShape = customScatterShape
return copy
}
} | apache-2.0 | b3acac20832f7ce7558cf1238e5be7e0 | 26.655172 | 90 | 0.686837 | 4.70088 | false | false | false | false |
flashspys/FWSlideMenu | FWSlideMenuDemoApp/FWSlideMenuDemoApp/SlideMenu.swift | 1 | 3734 | //
// ViewController.swift
// FWSlideOverDemoApp
//
// Created by Felix Wehnert on 18.01.16.
// Copyright © 2016 Felix Wehnert. All rights reserved.
//
import UIKit
import FWSlideMenu
class SlideMenu: UIViewController, FWSlideMenuViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var topConst: NSLayoutConstraint!
var backgroundView: UIView?
let menu = ["Vertretungsplan", "Klausuren", "Einstellungen", "Termine", "Lehrerliste", "Abmelden"]
var slideController: FWSlideMenuController?
func setController(_ controller: FWSlideMenuController) {
self.slideController = controller
}
override func viewDidLoad() {
self.backgroundView = UIView(frame: self.view.frame)
self.backgroundView?.frame.size.width += 50
self.backgroundView?.frame.origin.x -= 50
self.backgroundView?.backgroundColor = UIColor(patternImage: UIImage(named: "pattern")!)
//self.backgroundView?.layer.zPosition = -1
self.view.addSubview(self.backgroundView!)
self.view.sendSubview(toBack: self.backgroundView!)
self.view.clipsToBounds = true
self.imageView.image = UIImage(named: "woman")!
self.label.text = "Felix Wehnert"
self.tableView.backgroundColor = UIColor.clear
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menu.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell?
cell = tableView.dequeueReusableCell(withIdentifier: "identifier")
if menu[(indexPath as NSIndexPath).row] == "Abmelden" {
cell?.backgroundColor = UIColor(red: 255/255, green: 82/255, blue: 82/255, alpha: 0.4)
}
cell?.textLabel?.text = menu[(indexPath as NSIndexPath).row]
cell?.selectionStyle = .blue
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tableView.deselectRow(at: indexPath, animated: false)
self.slideController?.displayViewController(index: (indexPath as NSIndexPath).row)
}
func progressChanged(_ progress: CGFloat) {
self.imageView.alpha = 1-progress
self.label.alpha = 1-progress
self.tableView.alpha = 1-progress
self.topConst.constant = -50*progress + 15
self.backgroundView?.frame.origin.x = 50*progress
self.view.layoutIfNeeded()
}
func progressFinished(_ state: SlideState) {
UIView.animate(withDuration: 0.3, animations: { () -> Void in
if state == .opened {
self.imageView.alpha = 1
self.label.alpha = 1
self.tableView.alpha = 1
self.topConst.constant = 15
self.backgroundView?.frame.origin.x = 0
self.view.layoutIfNeeded()
} else {
self.imageView.alpha = 0
self.tableView.alpha = 0
self.label.alpha = 0
self.topConst.constant = -35
self.backgroundView?.frame.origin.x = 50
self.view.layoutIfNeeded()
}
})
}
}
| mit | 59775ba902150de8d920087e56aabb13 | 33.247706 | 106 | 0.627645 | 4.70744 | false | false | false | false |
fousa/trackkit | Example/Tests/Tests/LOC/LOCWaypointSpecs.swift | 1 | 4010 | //
// LOCWaypointSpecs.swift
// TrackKit
//
// Created by Jelle Vandebeeck on 30/12/2016.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Quick
import Nimble
import TrackKit
class LOCWaypointSpecs: QuickSpec {
override func spec() {
describe("waypoints") {
it("should not have waypoints") {
let content = "<loc version='1.0'></loc>"
let data = content.data(using: .utf8)
let file = try! TrackParser(data: data, type: .loc).parse()
expect(file.waypoints).to(beNil())
}
it("should not have waypoints without a coordinate") {
let content = "<loc version='1.0'>"
+ "<waypoint></waypoint>"
+ "</loc>"
let data = content.data(using: .utf8)
let file = try! TrackParser(data: data, type: .loc).parse()
expect(file.waypoints).to(beNil())
}
it("should have waypoints") {
let content = "<loc version='1.0'>"
+ "<waypoint>"
+ "<coord lat='51.16215' lon='4.456933'/>"
+ "</waypoint>"
+ "</loc>"
let data = content.data(using: .utf8)
let file = try! TrackParser(data: data, type: .loc).parse()
expect(file.waypoints?.count) == 1
}
}
describe("waypoint data") {
var point: Point!
beforeEach {
let content = "<loc version='1.0'>"
+ "<waypoint>"
+ "<name id='GC54AMF'><![CDATA[Mortsel]]></name>"
+ "<coord lat='51.16215' lon='4.456933'/>"
+ "<type>Geocache</type>"
+ "<link text='Details'>http://www.geocaching.com</link>"
+ "</waypoint>"
+ "</loc>"
let data = content.data(using: .utf8)
let file = try! TrackParser(data: data, type: .loc).parse()
point = file.waypoints?.first!
}
it("should have a coordinate") {
expect(point.coordinate?.latitude) == 51.16215
expect(point.coordinate?.longitude) == 4.456933
}
it("should have a name") {
expect(point.name) == "GC54AMF"
}
it("should have a description") {
expect(point.description) == "Mortsel"
}
it("should have a link") {
expect(point.link?.link) == "http://www.geocaching.com"
expect(point.link?.text) == "Details"
}
it("should have a type") {
expect(point.type) == "Geocache"
}
}
describe("empty waypoint") {
var point: Point!
beforeEach {
let content = "<loc version='1.0'>"
+ "<waypoint>"
+ "<coord lat='51.16215' lon='4.456933'/>"
+ "</waypoint>"
+ "</loc>"
let data = content.data(using: .utf8)
let file = try! TrackParser(data: data, type: .loc).parse()
point = file.waypoints?.first!
}
it("should not have a name") {
expect(point.name).to(beNil())
}
it("should not have a description") {
expect(point.description).to(beNil())
}
it("should not have a link") {
expect(point.link).to(beNil())
}
it("should not have a type") {
expect(point.type).to(beNil())
}
}
}
}
| mit | 027f2283e92f7ae648c172131f8e94fb | 32.408333 | 93 | 0.418808 | 4.688889 | false | false | false | false |
borglab/SwiftFusion | Sources/SwiftFusion/Inference/FactorsStorage.swift | 1 | 12459 | // Copyright 2020 The SwiftFusion Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// Contiguous storage for factors of statically unknown type.
import _Differentiation
import PenguinParallel
import PenguinStructures
// MARK: - Algorithms on arrays of `Factor`s.
extension ArrayStorage where Element: Factor {
/// Returns the errors, at `x`, of the factors.
func errors(at x: VariableAssignments) -> [Double] {
Element.Variables.withBufferBaseAddresses(x) { varsBufs in
Array<Double>(unsafeUninitializedCapacity: self.count) { (b, resultCount) in
ComputeThreadPools.local.parallelFor(n: self.count) { (i, _) in
let f = self[i]
b[i] = f.error(at: Element.Variables(at: f.edges, in: varsBufs))
}
resultCount = self.count
}
}
}
}
// MARK: - Algorithms on arrays of `VectorFactor`s.
extension ArrayStorage where Element: VectorFactor {
/// Returns the error vectors, at `x`, of the factors.
func errorVectors(at x: VariableAssignments) -> ArrayBuffer<Element.ErrorVector> {
Element.Variables.withBufferBaseAddresses(x) { varsBufs in
.init(
self.lazy.map { f in
f.errorVector(at: Element.Variables(at: f.edges, in: varsBufs)) })
}
}
/// Increments `result` by the gradients of `self`'s errors at `x`.
func accumulateErrorGradient(
at x: VariableAssignments,
into result: inout AllVectors
) {
typealias Variables = Element.Variables
typealias LVariables = Element.LinearizableComponent.Variables
typealias GradVariables = LVariables.TangentVector
Variables.withBufferBaseAddresses(x) { varsBufs in
GradVariables.withMutableBufferBaseAddresses(&result) { gradBufs in
for factor in self {
let vars = Variables(at: factor.edges, in: varsBufs)
let (lFactor, lVars) = factor.linearizableComponent(at: vars)
let gradIndices = LVariables.linearized(lFactor.edges)
let grads = GradVariables(at: gradIndices, in: GradVariables.withoutMutation(gradBufs))
let newGrads = grads + gradient(at: lVars) { lFactor.errorVector(at: $0).squaredNorm }
newGrads.assign(into: gradIndices, in: gradBufs)
}
}
}
}
}
// MARK: - Algorithms on arrays of `GaussianFactor`s.
extension ArrayStorage where Element: GaussianFactor {
/// Returns the error vectors, at `x`, of the factors.
func errorVectors(at x: VariableAssignments) -> ArrayBuffer<Element.ErrorVector> {
Element.Variables.withBufferBaseAddresses(x) { varsBufs in
.init(
lazy.map { f in
f.errorVector(at: Element.Variables(at: f.edges, in: varsBufs))
})
}
}
/// Returns the linear component of `errorVectors` at `x`.
func errorVectors_linearComponent(_ x: VariableAssignments) -> ArrayBuffer<Element.ErrorVector> {
Element.Variables.withBufferBaseAddresses(x) { varsBufs in
// Optimized version of
//
// ```
// .init(lazy.map { f in
// f.errorVector_linearComponent(Element.Variables(varsBufs, indices: f.edges))
// })
// ```
//
// I belive the main reason this speeds things up is that it makes it easier for the
// optimizer to see that we call `Element.Variables(varsBufs, indices: f.edges)` multiple
// times, which encourages it to destructure the `varsBufs` tuple once before the loop
// instead of once per iteration.
withUnsafeMutableBufferPointer { fs in
.init(count: fs.count, minimumCapacity: fs.count) { baseAddress in
for i in 0..<fs.count {
(baseAddress + i).initialize(
to: fs[i].errorVector_linearComponent(
Element.Variables(at: fs[i].edges, in: varsBufs)))
}
}
}
}
}
/// Accumulates the adjoint (aka "transpose" or "dual") of `errorVectors` at `y` into `result`.
///
/// - Requires: `result` contains elements at all of `self`'s elements' inputs.
func errorVectors_linearComponent_adjoint(
_ y: ArrayBuffer<Element.ErrorVector>,
into result: inout VariableAssignments
) {
typealias Variables = Element.Variables
Variables.withMutableBufferBaseAddresses(&result) { varsBufs in
withUnsafeMutableBufferPointer { fs in
y.withUnsafeBufferPointer { es in
assert(fs.count == es.count)
for i in 0..<es.count {
let vars = Variables(at: fs[i].edges, in: Variables.withoutMutation(varsBufs))
let newVars = vars + fs[i].errorVector_linearComponent_adjoint(es[i])
newVars.assign(into: fs[i].edges, in: varsBufs)
}
}
}
}
}
}
// MARK: - Type-erased arrays of `Factor`s.
typealias AnyFactorArrayBuffer = AnyArrayBuffer<FactorArrayDispatch>
/// An `AnyArrayBuffer` dispatcher that provides algorithm implementations for `Factor`
/// elements.
public class FactorArrayDispatch {
/// The notional `Self` type of the methods in the dispatch table
typealias Self_ = AnyArrayBuffer<AnyObject>
/// A function returning the errors, at `x`, of the factors in `storage`.
///
/// - Requires: `storage` is the address of an `ArrayStorage` whose `Element` has a
/// subclass-specific `VectorFactor` type.
final let errors: (_ self_: Self_, _ x: VariableAssignments) -> [Double]
/// Creates an instance for elements of type `Element`.
init<Element: Factor>(_ e: Type<Element>) {
errors = {
self_, x in self_[unsafelyAssumingElementType: e].storage.errors(at: x)
}
}
}
extension AnyArrayBuffer where Dispatch == FactorArrayDispatch {
/// Creates an instance from a typed buffer of `Element`
init<Dispatch: Factor>(_ src: ArrayBuffer<Dispatch>) {
self.init(
storage: src.storage,
dispatch: FactorArrayDispatch(Type<Dispatch>()))
}
}
extension AnyArrayBuffer where Dispatch: FactorArrayDispatch {
/// Returns the errors, at `x`, of the factors.
func errors(at x: VariableAssignments) -> [Double] {
dispatch.errors(self.upcast, x)
}
}
// MARK: - Type-erased arrays of `VectorFactor`s.
typealias AnyVectorFactorArrayBuffer = AnyArrayBuffer<VectorFactorArrayDispatch>
/// An `AnyArrayBuffer` dispatcher that provides algorithm implementations for `VectorFactor`
/// elements.
public class VectorFactorArrayDispatch: FactorArrayDispatch {
/// A function returning the error vectors, at `x`, of the factors in `storage`.
///
/// - Requires: `storage` is the address of an `ArrayStorage` whose `Element` has a
/// subclass-specific `VectorFactor` type.
final let errorVectors:
(_ self_: Self_, _ x: VariableAssignments) -> AnyVectorArrayBuffer
/// A function returning the linearizations, at `x`, of the factors in `storage`.
///
/// - Requires: `storage` is the address of an `ArrayStorage` whose `Element` has a
/// subclass-specific `VectorFactor` type.
final let linearized:
(_ self_: Self_, _ x: VariableAssignments) -> AnyGaussianFactorArrayBuffer
/// A function incrementing `result` by the gradients of `storage`'s factors' errors at `x`.
///
/// - Requires: `storage` is the address of an `ArrayStorage` whose `Element` has a
/// subclass-specific `VectorFactor` type.
final let accumulateErrorGradient:
(_ self_: Self_, _ x: VariableAssignments, _ result: inout AllVectors) -> ()
/// Creates an instance for elements of type `Element`.
///
/// The `_` argument is so that the compiler doesn't think we're trying to override the
/// superclass init with the similar signature.
init<Element: VectorFactor>(_ e: Type<Element>, _: () = ()) {
errorVectors = { self_, x in
.init(self_[unsafelyAssumingElementType: e].storage.errorVectors(at: x))
}
linearized = { self_, x in
Element.linearized(self_[unsafelyAssumingElementType: e].storage, at: x)
}
accumulateErrorGradient = { self_, x, result in
self_[unsafelyAssumingElementType: e].storage.accumulateErrorGradient(at: x, into: &result)
}
super.init(e)
}
}
extension AnyArrayBuffer where Dispatch == VectorFactorArrayDispatch {
/// Creates an instance from a typed buffer of `Element`
init<Element: VectorFactor>(_ src: ArrayBuffer<Element>) {
self.init(
storage: src.storage,
dispatch: VectorFactorArrayDispatch(Type<Element>()))
}
}
extension AnyArrayBuffer where Dispatch: VectorFactorArrayDispatch {
/// Returns the error vectors, at `x`, of the factors.
func errorVectors(at x: VariableAssignments) -> AnyVectorArrayBuffer {
dispatch.errorVectors(self.upcast, x)
}
/// Returns the linearizations, at `x`, of the factors.
func linearized(at x: VariableAssignments) -> AnyGaussianFactorArrayBuffer {
dispatch.linearized(self.upcast, x)
}
/// Increments `result` by the gradients of `self`'s errors at `x`.
func accumulateErrorGradient(
at x: VariableAssignments,
into result: inout AllVectors
) {
dispatch.accumulateErrorGradient(self.upcast, x, &result)
}
}
// MARK: - Type-erased arrays of `GaussianFactor`s.
public typealias AnyGaussianFactorArrayBuffer = AnyArrayBuffer<GaussianFactorArrayDispatch>
/// An `AnyArrayBuffer` dispatcher that provides algorithm implementations for `GaussianFactor`
/// elements.
public class GaussianFactorArrayDispatch: VectorFactorArrayDispatch {
/// A function returning the linear component of `errorVectors` at `x`.
///
/// - Requires: `storage` is the address of an `ArrayStorage` whose `Element` has a
/// subclass-specific `GaussianFactor` type.
final let errorVectors_linearComponent:
(_ self_: Self_,_ x: VariableAssignments) -> AnyVectorArrayBuffer
/// A function that accumulates the adjoint (aka "transpose" or "dual") of `errorVectors` at `y`
/// into `result`.
///
/// - Requires: `storage` is the address of an `ArrayStorage` whose `Element` has a
/// subclass-specific `GaussianFactor` type.
/// - Requires: `y.elementType == Element.ErrorVector.self`.
/// - Requires: `result` contains elements at all of `self`'s elements' inputs.
final let errorVectors_linearComponent_adjoint: (
_ self_: Self_, _ y: AnyElementArrayBuffer,
_ result: inout VariableAssignments
) -> Void
/// Creates an instance for elements of type `Element`.
init<Element: GaussianFactor>(_ e: Type<Element>)
{
errorVectors_linearComponent = { self_, x in
.init(self_[unsafelyAssumingElementType: e].storage.errorVectors_linearComponent(x))
}
errorVectors_linearComponent_adjoint = { self_, y, result in
self_[unsafelyAssumingElementType: e].storage.errorVectors_linearComponent_adjoint(
.init(unsafelyDowncasting: y), into: &result)
}
super.init(e)
}
}
extension AnyArrayBuffer where Dispatch == GaussianFactorArrayDispatch {
/// Creates an instance from a typed buffer of `Element`
public init<Element: GaussianFactor>(_ src: ArrayBuffer<Element>) {
self.init(
storage: src.storage,
dispatch: GaussianFactorArrayDispatch(Type<Element>()))
}
}
extension AnyArrayBuffer where Dispatch: GaussianFactorArrayDispatch {
/// Returns the error vectors, at `x`, of the factors.
func errorVectors(at x: VariableAssignments) -> AnyVectorArrayBuffer {
dispatch.errorVectors(self.upcast, x)
}
/// Returns the linear component of `errorVectors` at `x`.
func errorVectors_linearComponent(_ x: VariableAssignments) -> AnyVectorArrayBuffer {
dispatch.errorVectors_linearComponent(self.upcast, x)
}
/// Accumulates the adjoint (aka "transpose" or "dual") of `errorVectors` at `y` into `result`.
///
/// - Requires: `y.elementType == Element.ErrorVector.self`.
/// - Requires: `result` contains elements at all of `self`'s elements' inputs.
func errorVectors_linearComponent_adjoint(
_ y: AnyElementArrayBuffer,
into result: inout VariableAssignments
) {
dispatch.errorVectors_linearComponent_adjoint(self.upcast, y, &result)
}
}
| apache-2.0 | 400ea95f53db8bfe925eb7a4fca1bd57 | 37.813084 | 99 | 0.692511 | 4.079568 | false | false | false | false |
tiennth/TNSlider | TNSlider/Sources/TNTrackLayer.swift | 1 | 1284 | //
// TNTrackLayer.swift
// TNThumbValueSlider
//
// Created by Tien on 6/9/16.
// Copyright © 2016 tiennth. All rights reserved.
//
import UIKit
class TNTrackLayer: CALayer {
var trackMinColor: UIColor = TNConstants.trackMinColor
var trackMaxColor: UIColor = TNConstants.trackMaxColor
var value: Float = 0
var minimumValue: Float = 0
var maximumValue: Float = 1
override func draw(in ctx: CGContext) {
let cornerRadius = bounds.height * 1/2
let range = maximumValue - minimumValue
let thresholdX = bounds.size.width * CGFloat((value - minimumValue) / range)
let trackMinRect = CGRect(x: 0, y: 0, width: thresholdX, height: bounds.size.height)
let trackMinPath = UIBezierPath(roundedRect: trackMinRect, cornerRadius: cornerRadius)
ctx.setFillColor(trackMinColor.cgColor)
ctx.addPath(trackMinPath.cgPath)
ctx.fillPath()
let trackMaxRect = CGRect(x: thresholdX, y: 0, width: bounds.size.width - thresholdX, height: bounds.size.height)
let trackMaxPath = UIBezierPath(roundedRect: trackMaxRect, cornerRadius: cornerRadius)
ctx.setFillColor(trackMaxColor.cgColor)
ctx.addPath(trackMaxPath.cgPath)
ctx.fillPath()
}
}
| mit | 9bbaddb14569ddff082a813bf3b6851a | 33.675676 | 121 | 0.676539 | 3.959877 | false | false | false | false |
themonki/onebusaway-iphone | OneBusAway Today/TodayRowView.swift | 1 | 5429 | //
// TodayRowView.swift
// OneBusAway Today
//
// Created by Aaron Brethorst on 3/1/18.
// Copyright © 2018 OneBusAway. All rights reserved.
//
import UIKit
import OBAKit
enum TodayRowViewState {
case loading
case error
case complete
}
class TodayRowView: UIView {
// MARK: - State
var loadingState: TodayRowViewState = .loading
var departures: [OBAArrivalAndDepartureV2]? {
didSet {
updateDepartures()
}
}
public var bookmark: OBABookmarkV2? {
didSet {
titleLabel.text = bookmark?.title
}
}
// MARK: - UI
private lazy var hairline: UIView = {
let view = UIView.oba_autolayoutNew()
view.backgroundColor = UIColor.init(white: 1.0, alpha: 0.25)
view.snp.makeConstraints { (make) in
make.height.equalTo(0.5)
}
return view
}()
private lazy var outerStack: UIStackView = {
let stack = UIStackView.init(arrangedSubviews: [hairline, outerLabelStack])
stack.axis = .vertical
return stack
}()
private lazy var outerLabelStack: UIStackView = {
let leftStackWrapper = titleLabelStack.oba_embedInWrapper()
let departuresStackWrapper = departuresStack.oba_embedInWrapper()
let stack = UIStackView.init(arrangedSubviews: [leftStackWrapper, departuresStackWrapper])
stack.axis = .horizontal
stack.spacing = OBATheme.compactPadding
return stack
}()
// MARK: - Title Info Labels
private lazy var titleLabelStack: UIStackView = {
let stack = UIStackView.init(arrangedSubviews: [titleLabel, nextDepartureLabel])
stack.axis = .vertical
stack.spacing = OBATheme.minimalPadding
return stack
}()
private lazy var titleLabel: UILabel = {
let label = TodayRowView.buildInfoLabel(font: OBATheme.boldFootnoteFont)
return label
}()
private lazy var nextDepartureLabel: UILabel = {
let label = TodayRowView.buildInfoLabel(font: OBATheme.footnoteFont)
label.text = NSLocalizedString("today_screen.tap_for_more_information", comment: "Tap for more information subheading on Today view")
return label
}()
// MARK: - Departure Labels
private let leadingDepartureLabel = TodayRowView.buildDepartureLabel()
private let middleDepartureLabel = TodayRowView.buildDepartureLabel()
private let trailingDepartureLabel = TodayRowView.buildDepartureLabel()
private lazy var departuresStack: UIStackView = {
let stack = UIStackView.init(arrangedSubviews: [leadingDepartureLabel, middleDepartureLabel, trailingDepartureLabel])
stack.axis = .horizontal
stack.spacing = OBATheme.compactPadding
stack.isUserInteractionEnabled = false
return stack
}()
// MARK: - Init
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(outerStack)
outerStack.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
}
required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
}
// MARK: - Private Helpers
extension TodayRowView {
private static func buildInfoLabel(font: UIFont) -> UILabel {
let label = UILabel.oba_autolayoutNew()
label.setContentCompressionResistancePriority(.defaultHigh, for: .vertical)
label.setContentHuggingPriority(.defaultHigh, for: .vertical)
label.font = font
label.minimumScaleFactor = 0.8
return label
}
private static func buildDepartureLabel() -> UILabel {
let label = UILabel.oba_autolayoutNew()
label.setContentHuggingPriority(.required, for: .horizontal)
label.setContentCompressionResistancePriority(.required, for: .vertical)
label.font = OBATheme.boldFootnoteFont
return label
}
}
// MARK: - Departures
extension TodayRowView {
fileprivate func updateDepartures() {
let formatString = NSLocalizedString("stops.no_departures_in_next_n_minutes_format", comment: "No departures in the next {MINUTES} minutes")
let nextDepartureText = String.init(format: formatString, String(kMinutes))
nextDepartureLabel.text = nextDepartureText
leadingDepartureLabel.text = nil
middleDepartureLabel.text = nil
trailingDepartureLabel.text = nil
guard let departures = departures else {
return
}
if departures.isEmpty {
return
}
nextDepartureLabel.text = OBADepartureCellHelpers.statusText(forArrivalAndDeparture: departures[0])
applyUpcomingDeparture(at: 0, to: leadingDepartureLabel)
applyUpcomingDeparture(at: 1, to: middleDepartureLabel)
applyUpcomingDeparture(at: 2, to: trailingDepartureLabel)
}
private func applyUpcomingDeparture(at index: Int, to label: UILabel) {
guard let departures = departures else {
return
}
if departures.count <= index {
return
}
let dep = departures[index]
label.accessibilityLabel = OBADateHelpers.formatAccessibilityLabelMinutes(until: dep.bestArrivalDepartureDate)
label.text = OBADateHelpers.formatMinutes(until: dep.bestArrivalDepartureDate)
label.textColor = OBADepartureCellHelpers.color(for: dep.departureStatus)
}
}
| apache-2.0 | d4af645f4bc9dd34f20b2e9155247360 | 30.55814 | 148 | 0.67336 | 4.736475 | false | false | false | false |
ivanbruel/MarkdownKit | MarkdownKit/Sources/Common/Extensions/String+UTF16.swift | 1 | 1051 | //
// String+UTF16.swift
// Pods
//
// Created by Ivan Bruel on 19/07/16.
//
//
import Foundation
extension String {
/// Converts each character to its UTF16 form in hexadecimal value (e.g. "H" -> "0048")
func escapeUTF16() -> String {
return Array(utf16).map {
String(format: "%04x", $0)
}.reduce("") {
return $0 + $1
}
}
/// Converts each 4 digit characters to its String form (e.g. "0048" -> "H")
func unescapeUTF16() -> String? {
//This is an hot fix for the crash when a regular string is passed here.
guard count % 4 == 0 else {
return self
}
var utf16Array = [UInt16]()
stride(from: 0, to: count, by: 4).forEach {
let startIndex = index(self.startIndex, offsetBy: $0)
let endIndex = index(self.startIndex, offsetBy: $0 + 4)
let hex4 = String(self[startIndex..<endIndex])
if let utf16 = UInt16(hex4, radix: 16) {
utf16Array.append(utf16)
}
}
return String(utf16CodeUnits: utf16Array, count: utf16Array.count)
}
}
| mit | 350d710cfac3d472c67d4221e4226da4 | 24.634146 | 89 | 0.597526 | 3.423453 | false | false | false | false |
ivanbruel/MarkdownKit | MarkdownKit/Sources/Common/Elements/Bold/MarkdownBold.swift | 1 | 478 | //
// MarkdownBold.swift
// Pods
//
// Created by Ivan Bruel on 18/07/16.
//
//
import Foundation
open class MarkdownBold: MarkdownCommonElement {
fileprivate static let regex = "(.?|^)(\\*\\*|__)(.+?)(\\2)"
open var font: MarkdownFont?
open var color: MarkdownColor?
open var regex: String {
return MarkdownBold.regex
}
public init(font: MarkdownFont? = nil, color: MarkdownColor? = nil) {
self.font = font?.bold()
self.color = color
}
}
| mit | b91004c399f4b394390933a3d9511d3c | 18.916667 | 71 | 0.627615 | 3.463768 | false | false | false | false |
linusnyberg/RepoList | Repo List/TokenKeychain.swift | 1 | 1345 | //
// TokenKeychain.swift
// Repo List
//
// Created by Linus Nyberg on 2017-05-15.
// Copyright © 2017 Linus Nyberg. All rights reserved.
//
import Foundation
import KeychainSwift
/// Utility that saves and loads oauth tokens from the keychain.
class TokenKeychain {
static let keyChainOAuthTokenKey = "RepoListOauthToken"
static let keyChainOAuthTokenSecretKey = "RepoListOauthTokenSecret"
func saveToKeychain(oauthToken: String, oauthTokenSecret: String) {
print("Storing token in keychain")
let keychain = KeychainSwift()
keychain.set(oauthToken, forKey: TokenKeychain.keyChainOAuthTokenKey)
keychain.set(oauthTokenSecret, forKey: TokenKeychain.keyChainOAuthTokenSecretKey)
}
func readCredentialsFromKeychain(useValues: (_ oauthToken: String, _ oauthTokenSecret: String) -> Void) -> Bool {
print("Reading token from keychain")
let keychain = KeychainSwift()
guard let oauthToken = keychain.get(TokenKeychain.keyChainOAuthTokenKey), let oauthTokenSecret = keychain.get(TokenKeychain.keyChainOAuthTokenSecretKey) else {
return false
}
useValues(oauthToken, oauthTokenSecret)
return true
}
func clearCredentials() {
print("Clearing keychain")
let keychain = KeychainSwift()
keychain.delete(TokenKeychain.keyChainOAuthTokenKey)
keychain.delete(TokenKeychain.keyChainOAuthTokenSecretKey)
}
}
| mit | 69b8dd1c6cb45d7adc10d5df1ad37bf0 | 28.866667 | 161 | 0.779762 | 4.160991 | false | false | false | false |
qoncept/TensorSwift | Tests/TensorSwiftTests/TensorNNTests.swift | 1 | 3854 | import XCTest
@testable import TensorSwift
class TensorNNTests: XCTestCase {
func testMaxPool() {
do {
let a = Tensor(shape: [2,3,1], elements: [0,1,2,3,4,5])
let r = a.maxPool(kernelSize: [1,3,1], strides: [1,1,1])
XCTAssertEqual(r, Tensor(shape: [2,3,1], elements: [1,2,2,4,5,5]))
}
do {
let a = Tensor(shape: [2,2,2], elements: [0,1,2,3,4,5,6,7])
do {
let r = a.maxPool(kernelSize:[1,2,1], strides: [1,1,1])
XCTAssertEqual(r, Tensor(shape: [2,2,2], elements: [2, 3, 2, 3, 6, 7, 6, 7]))
}
do {
let r = a.maxPool(kernelSize:[1,2,1], strides: [1,2,1])
XCTAssertEqual(r, Tensor(shape: [2,1,2], elements: [2, 3, 6, 7]))
}
}
}
func testConv2d() {
do {
let a = Tensor(shape: [2,4,1], elements: [1,2,3,4,5,6,7,8])
do {
let filter = Tensor(shape: [2,1,1,2], elements: [1,2,1,2])
let result = a.conv2d(filter: filter, strides: [1,1,1])
XCTAssertEqual(result, Tensor(shape: [2,4,2], elements: [6,12,8,16,10,20,12,24,5,10,6,12,7,14,8,16]))
}
do {
let filter = Tensor(shape: [1,1,1,5], elements: [1,2,1,2,3])
let result = a.conv2d(filter: filter, strides: [1,1,1])
XCTAssertEqual(result, Tensor(shape: [2,4,5], elements: [1,2,1,2,3,2,4,2,4,6,3,6,3,6,9,4,8,4,8,12,5,10,5,10,15,6,12,6,12,18,7,14,7,14,21,8,16,8,16,24]))
}
}
do {
let a = Tensor(shape: [2,2,4], elements: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])
let filter = Tensor(shape: [1,1,4,2], elements: [1,2,1,2,3,2,1,1])
let result = a.conv2d(filter: filter, strides: [1,1,1])
XCTAssertEqual(result, Tensor(shape: [2,2,2], elements: [16, 16, 40, 44, 64, 72, 88, 100]))
}
do {
let a = Tensor(shape: [4,2,2], elements: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])
let filter = Tensor(shape: [2,2,2,1], elements: [1,2,1,2,3,2,1,1])
let result = a.conv2d(filter: filter, strides: [2,2,1])
XCTAssertEqual(result, Tensor(shape: [2,1,1], elements: [58,162]))
}
do {
let a = Tensor(shape: [4,4,1], elements: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])
let filter = Tensor(shape: [3,3,1,1], elements: [1,2,1,2,3,2,1,1,1])
let result = a.conv2d(filter: filter, strides: [3,3,1])
XCTAssertEqual(result, Tensor(shape: [2,2,1], elements: [18,33,95,113]))
}
do {
let a = Tensor(shape: [1,3,1], elements: [1,2,3])
let filter = Tensor(shape: [1,3,1,2], elements: [1,1,2,2,3,3])
let result = a.conv2d(filter: filter, strides: [1,1,1])
XCTAssertEqual(result, Tensor(shape: [1,3,2], elements: [8, 8, 14, 14, 8, 8]))
}
}
func testMaxPoolPerformance(){
let image = Tensor(shape: [28,28,3], element: 0.1)
measure{
_ = image.maxPool(kernelSize: [2,2,1], strides: [2,2,1])
}
}
func testConv2dPerformance(){
let image = Tensor(shape: [28,28,1], element: 0.1)
let filter = Tensor(shape: [5,5,1,16], element: 0.1)
measure{
_ = image.conv2d(filter: filter, strides: [1,1,1])
}
}
static var allTests : [(String, (TensorNNTests) -> () throws -> Void)] {
return [
("testMaxPool", testMaxPool),
("testConv2d", testConv2d),
("testMaxPoolPerformance", testMaxPoolPerformance),
("testConv2dPerformance", testConv2dPerformance),
]
}
}
| mit | 8694e30d67a281f6d894a4e7c8381085 | 39.145833 | 168 | 0.484951 | 2.827586 | false | true | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceApplication/Sources/EurofurenceApplication/Application/Components/News/View/CompositionalTableViewDataSource.swift | 1 | 6434 | import UIKit
public protocol TableViewMediatorDelegate: AnyObject {
func dataSourceContentsDidChange(_ dataSource: TableViewMediator)
}
public protocol TableViewMediator: UITableViewDataSource, UITableViewDelegate {
/* weak */ var delegate: TableViewMediatorDelegate? { get set }
func registerReusableViews(into tableView: UITableView)
}
@objcMembers
public class CompositionalTableViewDataSource: NSObject {
private let tableView: UITableView
private let missingNumeric = UITableView.automaticDimension
private var mediators = [TableViewMediator]()
private var delegates = [ReloadSectionWhenDataSourceChanges]()
public init(tableView: UITableView) {
self.tableView = tableView
super.init()
tableView.dataSource = self
tableView.delegate = self
tableView.reloadData()
}
public func append(_ dataSource: TableViewMediator) {
insertNewSection(dataSource)
registerReloadSectionWhenDataSourceChangesHandler(dataSource)
}
private func isSectionEmpty(_ section: Int) -> Bool {
self.tableView(tableView, numberOfRowsInSection: section) == 0
}
private func insertNewSection(_ dataSource: TableViewMediator) {
tableView.beginUpdates()
mediators.append(dataSource)
dataSource.registerReusableViews(into: tableView)
tableView.insertSections([mediators.count - 1], with: .automatic)
tableView.endUpdates()
}
private func registerReloadSectionWhenDataSourceChangesHandler(_ dataSource: TableViewMediator) {
let reloadSectionHandler = ReloadSectionWhenDataSourceChanges { [weak self] (dataSource) in
if let index = self?.mediators.firstIndex(where: { $0 === dataSource }) {
self?.tableView.reloadSections([index], with: .automatic)
}
}
delegates.append(reloadSectionHandler)
dataSource.delegate = reloadSectionHandler
}
private class ReloadSectionWhenDataSourceChanges: TableViewMediatorDelegate {
private let reloadSectionHandler: (TableViewMediator) -> Void
init(reloadSectionHandler: @escaping (TableViewMediator) -> Void) {
self.reloadSectionHandler = reloadSectionHandler
}
func dataSourceContentsDidChange(_ dataSource: TableViewMediator) {
reloadSectionHandler(dataSource)
}
}
}
// MARK: - CompositionalTableViewDataSource + UITableViewDataSource
extension CompositionalTableViewDataSource: UITableViewDataSource {
public func numberOfSections(in tableView: UITableView) -> Int {
mediators.count
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let mediator = mediators[section]
return mediator.tableView(tableView, numberOfRowsInSection: section)
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let mediator = mediators[indexPath.section]
return mediator.tableView(tableView, cellForRowAt: indexPath)
}
}
// MARK: - CompositionalTableViewDataSource + UITableViewDelegate
extension CompositionalTableViewDataSource: UITableViewDelegate {
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let mediator = mediators[indexPath.section]
mediator.tableView?(tableView, didSelectRowAt: indexPath)
}
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard isSectionEmpty(section) == false else { return nil }
let mediator = mediators[section]
return mediator.tableView?(tableView, viewForHeaderInSection: section)
}
public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let mediator = mediators[section]
return mediator.tableView?(tableView, viewForFooterInSection: section)
}
public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
let mediator = mediators[section]
return mediator.tableView?(tableView, heightForFooterInSection: section) ?? 0
}
public func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
guard isSectionEmpty(section) == false else { return 0 }
let mediator = mediators[section]
return mediator.tableView?(tableView, estimatedHeightForHeaderInSection: section) ?? missingNumeric
}
public func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
let mediator = mediators[indexPath.section]
return mediator.tableView?(tableView, estimatedHeightForRowAt: indexPath) ?? missingNumeric
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let mediator = mediators[indexPath.section]
return mediator.tableView?(tableView, heightForRowAt: indexPath) ?? missingNumeric
}
public func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
let mediator = mediators[section]
return mediator.tableView?(tableView, titleForFooterInSection: section)
}
public func tableView(
_ tableView: UITableView,
trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath
) -> UISwipeActionsConfiguration? {
let mediator = mediators[indexPath.section]
return mediator.tableView?(tableView, trailingSwipeActionsConfigurationForRowAt: indexPath)
}
public func tableView(
_ tableView: UITableView,
contextMenuConfigurationForRowAt indexPath: IndexPath,
point: CGPoint
) -> UIContextMenuConfiguration? {
let mediator = mediators[indexPath.section]
return mediator.tableView?(tableView, contextMenuConfigurationForRowAt: indexPath, point: point)
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
for mediator in mediators {
mediator.scrollViewDidEndDragging?(scrollView, willDecelerate: decelerate)
}
}
}
| mit | 1ad4ff0a7390d89accc35fcf2168be30 | 37.071006 | 112 | 0.699409 | 5.806859 | false | false | false | false |
ethan-fang/Alamofire | Source/MultipartFormData.swift | 9 | 25116 | // MultipartFormData.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
#if os(iOS)
import MobileCoreServices
#elseif os(OSX)
import CoreServices
#endif
/**
Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode
multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead
to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the
data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for
larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset.
For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well
and the w3 form documentation.
- http://www.ietf.org/rfc/rfc2388.txt
- http://www.ietf.org/rfc/rfc2045.txt
- http://www.w3.org/TR/html401/interact/forms.html#h-17.13
*/
public class MultipartFormData {
// MARK: - Helper Types
/**
Used to specify whether encoding was successful.
*/
public enum EncodingResult {
case Success(NSData)
case Failure(NSError)
}
struct EncodingCharacters {
static let CRLF = "\r\n"
}
struct BoundaryGenerator {
enum BoundaryType {
case Initial, Encapsulated, Final
}
static func randomBoundary() -> String {
return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random())
}
static func boundaryData(#boundaryType: BoundaryType, boundary: String) -> NSData {
let boundaryText: String
switch boundaryType {
case .Initial:
boundaryText = "--\(boundary)\(EncodingCharacters.CRLF)"
case .Encapsulated:
boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)\(EncodingCharacters.CRLF)"
case .Final:
boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)--\(EncodingCharacters.CRLF)"
}
return boundaryText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
}
}
class BodyPart {
let headers: [String: String]
let bodyStream: NSInputStream
let bodyContentLength: UInt64
var hasInitialBoundary = false
var hasFinalBoundary = false
init(headers: [String: String], bodyStream: NSInputStream, bodyContentLength: UInt64) {
self.headers = headers
self.bodyStream = bodyStream
self.bodyContentLength = bodyContentLength
}
}
// MARK: - Properties
/// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`.
public var contentType: String { return "multipart/form-data; boundary=\(self.boundary)" }
/// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries.
public var contentLength: UInt64 { return self.bodyParts.reduce(0) { $0 + $1.bodyContentLength } }
/// The boundary used to separate the body parts in the encoded form data.
public let boundary: String
private var bodyParts: [BodyPart]
private let streamBufferSize: Int
// MARK: - Lifecycle
/**
Creates a multipart form data object.
:returns: The multipart form data object.
*/
public init() {
self.boundary = BoundaryGenerator.randomBoundary()
self.bodyParts = []
/**
* The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more
* information, please refer to the following article:
* - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html
*/
self.streamBufferSize = 1024
}
// MARK: - Body Parts
/**
Creates a body part from the file and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header)
- `Content-Type: #{generated mimeType}` (HTTP Header)
- Encoded file data
- Multipart form boundary
The filename in the `Content-Disposition` HTTP header is generated from the last path component of the
`fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the
system associated MIME type.
:param: URL The URL of the file whose content will be encoded into the multipart form data.
:param: name The name to associate with the file content in the `Content-Disposition` HTTP header.
:returns: An `NSError` if an error occurred, `nil` otherwise.
*/
public func appendBodyPart(fileURL URL: NSURL, name: String) -> NSError? {
if let
fileName = URL.lastPathComponent,
pathExtension = URL.pathExtension
{
let mimeType = mimeTypeForPathExtension(pathExtension)
return appendBodyPart(fileURL: URL, name: name, fileName: fileName, mimeType: mimeType)
}
let failureReason = "Failed to extract the fileName of the provided URL: \(URL)"
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
return NSError(domain: AlamofireErrorDomain, code: NSURLErrorBadURL, userInfo: userInfo)
}
/**
Creates a body part from the file and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
- Content-Type: #{mimeType} (HTTP Header)
- Encoded file data
- Multipart form boundary
:param: URL The URL of the file whose content will be encoded into the multipart form data.
:param: name The name to associate with the file content in the `Content-Disposition` HTTP header.
:param: fileName The filename to associate with the file content in the `Content-Disposition` HTTP header.
:param: mimeType The MIME type to associate with the file content in the `Content-Type` HTTP header.
:returns: An `NSError` if an error occurred, `nil` otherwise.
*/
public func appendBodyPart(fileURL URL: NSURL, name: String, fileName: String, mimeType: String) -> NSError? {
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
var isDirectory: ObjCBool = false
if !URL.fileURL {
return errorWithCode(NSURLErrorBadURL, failureReason: "The URL does not point to a file URL: \(URL)")
} else if !URL.checkResourceIsReachableAndReturnError(nil) {
return errorWithCode(NSURLErrorBadURL, failureReason: "The URL is not reachable: \(URL)")
} else if NSFileManager.defaultManager().fileExistsAtPath(URL.path!, isDirectory: &isDirectory) && isDirectory {
return errorWithCode(NSURLErrorBadURL, failureReason: "The URL is a directory, not a file: \(URL)")
}
let bodyContentLength: UInt64
var fileAttributesError: NSError?
if let
path = URL.path,
attributes = NSFileManager.defaultManager().attributesOfItemAtPath(path, error: &fileAttributesError),
fileSize = (attributes[NSFileSize] as? NSNumber)?.unsignedLongLongValue
{
bodyContentLength = fileSize
} else {
return errorWithCode(NSURLErrorBadURL, failureReason: "Could not fetch attributes from the URL: \(URL)")
}
if let bodyStream = NSInputStream(URL: URL) {
let bodyPart = BodyPart(headers: headers, bodyStream: bodyStream, bodyContentLength: bodyContentLength)
self.bodyParts.append(bodyPart)
} else {
let failureReason = "Failed to create an input stream from the URL: \(URL)"
return errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason)
}
return nil
}
/**
Creates a body part from the data and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
- `Content-Type: #{mimeType}` (HTTP Header)
- Encoded file data
- Multipart form boundary
:param: data The data to encode into the multipart form data.
:param: name The name to associate with the data in the `Content-Disposition` HTTP header.
:param: fileName The filename to associate with the data in the `Content-Disposition` HTTP header.
:param: mimeType The MIME type to associate with the data in the `Content-Type` HTTP header.
*/
public func appendBodyPart(fileData data: NSData, name: String, fileName: String, mimeType: String) {
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
let bodyStream = NSInputStream(data: data)
let bodyContentLength = UInt64(data.length)
let bodyPart = BodyPart(headers: headers, bodyStream: bodyStream, bodyContentLength: bodyContentLength)
self.bodyParts.append(bodyPart)
}
/**
Creates a body part from the data and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}` (HTTP Header)
- Encoded file data
- Multipart form boundary
:param: data The data to encode into the multipart form data.
:param: name The name to associate with the data in the `Content-Disposition` HTTP header.
*/
public func appendBodyPart(#data: NSData, name: String) {
let headers = contentHeaders(name: name)
let bodyStream = NSInputStream(data: data)
let bodyContentLength = UInt64(data.length)
let bodyPart = BodyPart(headers: headers, bodyStream: bodyStream, bodyContentLength: bodyContentLength)
self.bodyParts.append(bodyPart)
}
/**
Creates a body part from the stream and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
- `Content-Type: #{mimeType}` (HTTP Header)
- Encoded file data
- Multipart form boundary
:param: stream The input stream to encode in the multipart form data.
:param: name The name to associate with the stream content in the `Content-Disposition` HTTP header.
:param: fileName The filename to associate with the stream content in the `Content-Disposition` HTTP header.
:param: mimeType The MIME type to associate with the stream content in the `Content-Type` HTTP header.
*/
public func appendBodyPart(#stream: NSInputStream, name: String, fileName: String, length: UInt64, mimeType: String) {
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length)
self.bodyParts.append(bodyPart)
}
// MARK: - Data Extraction
/**
Encodes all the appended body parts into a single `NSData` object.
It is important to note that this method will load all the appended body parts into memory all at the same
time. This method should only be used when the encoded data will have a small memory footprint. For large data
cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method.
:returns: EncodingResult containing an `NSData` object if the encoding succeeded, an `NSError` otherwise.
*/
public func encode() -> EncodingResult {
var encoded = NSMutableData()
self.bodyParts.first?.hasInitialBoundary = true
self.bodyParts.last?.hasFinalBoundary = true
for bodyPart in self.bodyParts {
let encodedDataResult = encodeBodyPart(bodyPart)
switch encodedDataResult {
case .Failure:
return encodedDataResult
case let .Success(data):
encoded.appendData(data)
}
}
return .Success(encoded)
}
/**
Writes the appended body parts into the given file URL asynchronously and calls the `completionHandler`
when finished.
This process is facilitated by reading and writing with input and output streams, respectively. Thus,
this approach is very memory efficient and should be used for large body part data.
:param: fileURL The file URL to write the multipart form data into.
:param: completionHandler A closure to be executed when writing is finished.
*/
public func writeEncodedDataToDisk(fileURL: NSURL, completionHandler: (NSError?) -> Void) {
var error: NSError?
if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) {
let failureReason = "A file already exists at the given file URL: \(fileURL)"
error = errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
} else if !fileURL.fileURL {
let failureReason = "The URL does not point to a valid file: \(fileURL)"
error = errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
}
if let error = error {
completionHandler(error)
return
}
let outputStream: NSOutputStream
if let possibleOutputStream = NSOutputStream(URL: fileURL, append: false) {
outputStream = possibleOutputStream
} else {
let failureReason = "Failed to create an output stream with the given URL: \(fileURL)"
let error = errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason)
completionHandler(error)
return
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
outputStream.open()
self.bodyParts.first?.hasInitialBoundary = true
self.bodyParts.last?.hasFinalBoundary = true
var error: NSError?
for bodyPart in self.bodyParts {
if let writeError = self.writeBodyPart(bodyPart, toOutputStream: outputStream) {
error = writeError
break
}
}
outputStream.close()
outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
dispatch_async(dispatch_get_main_queue()) {
completionHandler(error)
}
}
}
// MARK: - Private - Body Part Encoding
private func encodeBodyPart(bodyPart: BodyPart) -> EncodingResult {
let encoded = NSMutableData()
let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
encoded.appendData(initialData)
let headerData = encodeHeaderDataForBodyPart(bodyPart)
encoded.appendData(headerData)
let bodyStreamResult = encodeBodyStreamDataForBodyPart(bodyPart)
switch bodyStreamResult {
case .Failure:
return bodyStreamResult
case let .Success(data):
encoded.appendData(data)
}
if bodyPart.hasFinalBoundary {
encoded.appendData(finalBoundaryData())
}
return .Success(encoded)
}
private func encodeHeaderDataForBodyPart(bodyPart: BodyPart) -> NSData {
var headerText = ""
for (key, value) in bodyPart.headers {
headerText += "\(key): \(value)\(EncodingCharacters.CRLF)"
}
headerText += EncodingCharacters.CRLF
return headerText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
}
private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) -> EncodingResult {
let inputStream = bodyPart.bodyStream
inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream.open()
var error: NSError?
let encoded = NSMutableData()
while inputStream.hasBytesAvailable {
var buffer = [UInt8](count: self.streamBufferSize, repeatedValue: 0)
let bytesRead = inputStream.read(&buffer, maxLength: self.streamBufferSize)
if inputStream.streamError != nil {
error = inputStream.streamError
break
}
if bytesRead > 0 {
encoded.appendBytes(buffer, length: bytesRead)
} else if bytesRead < 0 {
let failureReason = "Failed to read from input stream: \(inputStream)"
error = errorWithCode(AlamofireInputStreamReadFailed, failureReason: failureReason)
break
} else {
break
}
}
inputStream.close()
inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
if let error = error {
return .Failure(error)
}
return .Success(encoded)
}
// MARK: - Private - Writing Body Part to Output Stream
private func writeBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? {
if let error = writeInitialBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) {
return error
}
if let error = writeHeaderDataForBodyPart(bodyPart, toOutputStream: outputStream) {
return error
}
if let error = writeBodyStreamForBodyPart(bodyPart, toOutputStream: outputStream) {
return error
}
if let error = writeFinalBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream) {
return error
}
return nil
}
private func writeInitialBoundaryDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? {
let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
return writeData(initialData, toOutputStream: outputStream)
}
private func writeHeaderDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? {
let headerData = encodeHeaderDataForBodyPart(bodyPart)
return writeData(headerData, toOutputStream: outputStream)
}
private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? {
var error: NSError?
let inputStream = bodyPart.bodyStream
inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream.open()
while inputStream.hasBytesAvailable {
var buffer = [UInt8](count: self.streamBufferSize, repeatedValue: 0)
let bytesRead = inputStream.read(&buffer, maxLength: self.streamBufferSize)
if inputStream.streamError != nil {
error = inputStream.streamError
break
}
if bytesRead > 0 {
if buffer.count != bytesRead {
buffer = Array(buffer[0..<bytesRead])
}
if let writeError = writeBuffer(&buffer, toOutputStream: outputStream) {
error = writeError
break
}
} else if bytesRead < 0 {
let failureReason = "Failed to read from input stream: \(inputStream)"
error = errorWithCode(AlamofireInputStreamReadFailed, failureReason: failureReason)
break
} else {
break
}
}
inputStream.close()
inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
return error
}
private func writeFinalBoundaryDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) -> NSError? {
if bodyPart.hasFinalBoundary {
return writeData(finalBoundaryData(), toOutputStream: outputStream)
}
return nil
}
// MARK: - Private - Writing Buffered Data to Output Stream
private func writeData(data: NSData, toOutputStream outputStream: NSOutputStream) -> NSError? {
var buffer = [UInt8](count: data.length, repeatedValue: 0)
data.getBytes(&buffer, length: data.length)
return writeBuffer(&buffer, toOutputStream: outputStream)
}
private func writeBuffer(inout buffer: [UInt8], toOutputStream outputStream: NSOutputStream) -> NSError? {
var error: NSError?
var bytesToWrite = buffer.count
while bytesToWrite > 0 {
if outputStream.hasSpaceAvailable {
let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite)
if outputStream.streamError != nil {
error = outputStream.streamError
break
}
if bytesWritten < 0 {
let failureReason = "Failed to write to output stream: \(outputStream)"
error = errorWithCode(AlamofireOutputStreamWriteFailed, failureReason: failureReason)
break
}
bytesToWrite -= bytesWritten
if bytesToWrite > 0 {
buffer = Array(buffer[bytesWritten..<buffer.count])
}
} else if outputStream.streamError != nil {
error = outputStream.streamError
break
}
}
return error
}
// MARK: - Private - Mime Type
private func mimeTypeForPathExtension(pathExtension: String) -> String {
let identifier = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil).takeRetainedValue()
if let contentType = UTTypeCopyPreferredTagWithClass(identifier, kUTTagClassMIMEType) {
return contentType.takeRetainedValue() as String
}
return "application/octet-stream"
}
// MARK: - Private - Content Headers
private func contentHeaders(#name: String) -> [String: String] {
return ["Content-Disposition": "form-data; name=\"\(name)\""]
}
private func contentHeaders(#name: String, fileName: String, mimeType: String) -> [String: String] {
return [
"Content-Disposition": "form-data; name=\"\(name)\"; filename=\"\(fileName)\"",
"Content-Type": "\(mimeType)"
]
}
// MARK: - Private - Boundary Encoding
private func initialBoundaryData() -> NSData {
return BoundaryGenerator.boundaryData(boundaryType: .Initial, boundary: self.boundary)
}
private func encapsulatedBoundaryData() -> NSData {
return BoundaryGenerator.boundaryData(boundaryType: .Encapsulated, boundary: self.boundary)
}
private func finalBoundaryData() -> NSData {
return BoundaryGenerator.boundaryData(boundaryType: .Final, boundary: self.boundary)
}
// MARK: - Private - Errors
private func errorWithCode(code: Int, failureReason: String) -> NSError {
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
return NSError(domain: AlamofireErrorDomain, code: code, userInfo: userInfo)
}
}
| mit | e572bc169f607d90fd3e7fd9d26b4a3b | 38.990446 | 132 | 0.656367 | 5.147366 | false | false | false | false |
XBeg9/UnderKeyboard | UnderKeyboard/UnderKeyboardLayoutConstraint.swift | 1 | 3172 | import UIKit
/**
Adjusts the length (constant value) of the bottom layout constraint when keyboard shows and hides.
*/
@objc public class UnderKeyboardLayoutConstraint: NSObject {
private weak var bottomLayoutConstraint: NSLayoutConstraint?
private weak var bottomLayoutGuide: UILayoutSupport?
private var keyboardObserver = UnderKeyboardObserver()
private var initialConstraintConstant: CGFloat = 0
private var minMargin: CGFloat = 10
private var viewToAnimate: UIView?
public override init() {
super.init()
keyboardObserver.willAnimateKeyboard = keyboardWillAnimate
keyboardObserver.animateKeyboard = animateKeyboard
keyboardObserver.start()
}
deinit {
stop()
}
/// Stop listening for keyboard notifications.
public func stop() {
keyboardObserver.stop()
}
/**
Supply a bottom Auto Layout constraint. Its constant value will be adjusted by the height of the keyboard when it appears and hides.
- parameter bottomLayoutConstraint: Supply a bottom layout constraint. Its constant value will be adjusted when keyboard is shown and hidden.
- parameter view: Supply a view that will be used to animate the constraint. It is usually the superview containing the view with the constraint.
- parameter minMargin: Specify the minimum margin between the keyboard and the bottom of the view the constraint is attached to. Default: 10.
- parameter bottomLayoutGuide: Supply an optional bottom layout guide (like a tab bar) that will be taken into account during height calculations.
*/
public func setup(bottomLayoutConstraint: NSLayoutConstraint,
view: UIView, minMargin: CGFloat = 10,
bottomLayoutGuide: UILayoutSupport? = nil) {
initialConstraintConstant = bottomLayoutConstraint.constant
self.bottomLayoutConstraint = bottomLayoutConstraint
self.minMargin = minMargin
self.bottomLayoutGuide = bottomLayoutGuide
self.viewToAnimate = view
// Keyboard is already open when setup is called
if let currentKeyboardHeight = keyboardObserver.currentKeyboardHeight
where currentKeyboardHeight > 0 {
keyboardWillAnimate(currentKeyboardHeight)
}
}
func keyboardWillAnimate(height: CGFloat) {
guard let bottomLayoutConstraint = bottomLayoutConstraint else { return }
let layoutGuideHeight = bottomLayoutGuide?.length ?? 0
let correctedHeight = height - layoutGuideHeight
if height > 0 {
let newConstantValue = correctedHeight + minMargin
if newConstantValue > initialConstraintConstant {
// Keyboard height is bigger than the initial constraint length.
// Increase constraint length.
bottomLayoutConstraint.constant = newConstantValue
} else {
// Keyboard height is NOT bigger than the initial constraint length.
// Show the initial constraint length.
bottomLayoutConstraint.constant = initialConstraintConstant
}
} else {
bottomLayoutConstraint.constant = initialConstraintConstant
}
}
func animateKeyboard(height: CGFloat) {
viewToAnimate?.layoutIfNeeded()
}
} | mit | cb6ed30b8f9ea1eb85ea7e98b31c5acb | 33.11828 | 148 | 0.734237 | 6.111753 | false | false | false | false |
kkolli/MathGame | client/Libs/Alamofire/Example/AppDelegate.swift | 8 | 2455 | // AppDelegate.swift
//
// Copyright (c) 2014–2015 Alamofire (http://alamofire.org)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
// MARK: - UIApplicationDelegate
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
let splitViewController = self.window!.rootViewController as UISplitViewController
let navigationController = splitViewController.viewControllers.last as UINavigationController
navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
return true
}
// MARK: - UISplitViewControllerDelegate
func splitViewController(splitViewController: UISplitViewController!, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool {
if let secondaryAsNavController = secondaryViewController as? UINavigationController {
if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController {
return topAsDetailController.request == nil
}
}
return false
}
}
| gpl-2.0 | f1fdc3acd9872b57e4d6d6a3ba850527 | 44.425926 | 225 | 0.766816 | 5.939467 | false | false | false | false |
BiuroCo/mega | examples/Swift/MEGA/MEGA/Offline/OfflineTableViewController.swift | 1 | 4275 | /**
* @file OfflineTableViewController.swift
* @brief View controller that show offline files
*
* (c) 2013-2015 by Mega Limited, Auckland, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK 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.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
import UIKit
class OfflineTableViewController: UITableViewController, MEGATransferDelegate {
var offlineDocuments = [MEGANode]()
let megaapi : MEGASdk! = (UIApplication.sharedApplication().delegate as! AppDelegate).megaapi
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
reloadUI()
megaapi.addMEGATransferDelegate(self)
megaapi.retryPendingConnections()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
megaapi.removeMEGATransferDelegate(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func reloadUI() {
offlineDocuments = [MEGANode]()
let documentDirectory = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
if let directoryContent : Array = try? NSFileManager.defaultManager().contentsOfDirectoryAtPath(documentDirectory) {
var i = 0
for i = 0; i < directoryContent.count; i++ {
let filename: String = String(directoryContent[i] as NSString)
let filePath = (documentDirectory as NSString).stringByAppendingPathComponent(filename)
if !((filename.lowercaseString as NSString).pathExtension == "mega") {
if let node = megaapi.nodeForHandle(MEGASdk.handleForBase64Handle(filename)) {
offlineDocuments.append(node)
}
}
}
}
tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return offlineDocuments.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("nodeCell", forIndexPath: indexPath) as! NodeTableViewCell
let node = offlineDocuments[indexPath.row]
cell.nameLabel.text = node.name
let thumbnailFilePath = Helper.pathForNode(node, path:NSSearchPathDirectory.CachesDirectory, directory: "thumbs")
let fileExists = NSFileManager.defaultManager().fileExistsAtPath(thumbnailFilePath)
if !fileExists {
cell.thumbnailImageView.image = Helper.imageForNode(node)
} else {
cell.thumbnailImageView.image = UIImage(named: thumbnailFilePath)
}
if node.isFile() {
cell.subtitleLabel.text = NSByteCountFormatter().stringFromByteCount(node.size.longLongValue)
} else {
let files = megaapi.numberChildFilesForParent(node)
let folders = megaapi.numberChildFoldersForParent(node)
cell.subtitleLabel.text = "\(folders) folders, \(files) files"
cell.thumbnailImageView.image = UIImage(named: "folder")
}
return cell
}
// MARK: - MEGA Transfer delegate
func onTransferFinish(api: MEGASdk!, transfer: MEGATransfer!, error: MEGAError!) {
reloadUI()
}
}
| bsd-2-clause | 9d5af5359a4d1e7ec772793711b07b8c | 34.330579 | 157 | 0.652865 | 5.150602 | false | false | false | false |
huonw/swift | test/NameBinding/scope_map.swift | 5 | 28801 | // Note: test of the scope map. All of these tests are line- and
// column-sensitive, so any additions should go at the end.
struct S0 {
class InnerC0 { }
}
extension S0 {
}
class C0 {
}
enum E0 {
case C0
case C1(Int, Int)
}
struct GenericS0<T, U> {
}
func genericFunc0<T, U>(t: T, u: U, i: Int = 10) {
}
class ContainsGenerics0 {
init<T, U>(t: T, u: U) {
}
deinit {
}
}
typealias GenericAlias0<T> = [T]
#if arch(unknown)
struct UnknownArchStruct { }
#else
struct OtherArchStruct { }
#endif
func functionBodies1(a: Int, b: Int?) {
let (x1, x2) = (a, b),
(y1, y2) = (b, a)
let (z1, z2) = (a, a)
do {
let a1 = a
let a2 = a
do {
let b1 = b
let b2 = b
}
}
do {
let b1 = b
let b2 = b
}
func f(_ i: Int) -> Int { return i }
let f2 = f(_:)
struct S7 { }
typealias S7Alias = S7
if let b1 = b, let b2 = b {
let c1 = b
} else {
let c2 = b
}
guard let b1 = b, { $0 > 5 }(b1), let b2 = b else {
let c = 5
return
}
while let b3 = b, let b4 = b {
let c = 5
}
repeat { } while true;
for (x, y) in [(1, "hello"), (2, "world")] where x % 2 == 0 {
}
do {
try throwing()
} catch let mine as MyError where mine.value == 17 {
} catch {
}
switch MyEnum.second(1) {
case .second(let x) where x == 17:
break;
case .first:
break;
default:
break;
}
for (var i = 0; i != 10; i += 1) { }
}
func throwing() throws { }
struct MyError : Error {
var value: Int
}
enum MyEnum {
case first
case second(Int)
case third
}
struct StructContainsAbstractStorageDecls {
subscript (i: Int, j: Int) -> Int {
set {
}
get {
return i + j
}
}
var computed: Int {
get {
return 0
}
set {
}
}
}
class ClassWithComputedProperties {
var willSetProperty: Int = 0 {
willSet { }
}
var didSetProperty: Int = 0 {
didSet { }
}
}
func funcWithComputedProperties(i: Int) {
var computed: Int {
set {
}
get {
return 0
}
}, var (stored1, stored2) = (1, 2),
var alsoComputed: Int {
return 17
}
do { }
}
func closures() {
{ x, y in
return { $0 + $1 }(x, y)
}(1, 2) +
{ a, b in a * b }(3, 4)
}
{ closures() }()
func defaultArguments(i: Int = 1,
j: Int = { $0 + $1 }(1, 2)) {
func localWithDefaults(i: Int = 1,
j: Int = { $0 + $1 }(1, 2)) {
}
let a = i + j
{ $0 }(a)
}
struct PatternInitializers {
var (a, b) = (1, 2),
(c, d) = (1.5, 2.5)
}
protocol ProtoWithSubscript {
subscript(native: Int) -> Int { get set }
}
func localPatternsWithSharedType() {
let i, j, k: Int
}
class LazyProperties {
var value: Int = 17
lazy var prop: Int = self.value
}
// RUN: not %target-swift-frontend -dump-scope-maps expanded %s 2> %t.expanded
// RUN: %FileCheck -check-prefix CHECK-EXPANDED %s < %t.expanded
// CHECK-EXPANDED: SourceFile{{.*}}scope_map.swift{{.*}}expanded
// CHECK-EXPANDED-NEXT: TypeDecl {{.*}} S0 [4:1 - 6:1] expanded
// CHECK-EXPANDED-NEXT: TypeOrExtensionBody {{.*}} 'S0' [4:11 - 6:1] expanded
// CHECK-EXPANDED-NEXT: -TypeDecl {{.*}} InnerC0 [5:3 - 5:19] expanded
// CHECK-EXPANDED-NEXT: `-TypeOrExtensionBody {{.*}} 'InnerC0' [5:17 - 5:19] expanded
// CHECK-EXPANDED-NEXT: -ExtensionGenericParams {{.*}} extension of 'S0' [8:14 - 9:1] expanded
// CHECK-EXPANDED-NEXT: -TypeOrExtensionBody {{.*}} extension of 'S0' [8:14 - 9:1] expanded
// CHECK-EXPANDED-NEXT: TypeDecl {{.*}} C0 [11:1 - 12:1] expanded
// CHECK-EXPANDED-NEXT: -TypeOrExtensionBody {{.*}} 'C0' [11:10 - 12:1] expanded
// CHECK-EXPANDED-NEXT: TypeDecl {{.*}} E0 [14:1 - 17:1] expanded
// CHECK-EXPANDED-NEXT: -TypeOrExtensionBody {{.*}} 'E0' [14:9 - 17:1] expanded
// CHECK-EXPANDED-NEXT: TypeDecl {{.*}} GenericS0 [19:1 - 20:1] expanded
// CHECK-EXPANDED-NEXT: -GenericParams {{.*}} param 0 [19:18 - 20:1] expanded
// CHECK-EXPANDED-NEXT: -GenericParams {{.*}} param 1 [19:21 - 20:1] expanded
// CHECK-EXPANDED-NEXT: -TypeOrExtensionBody {{.*}} 'GenericS0' [19:24 - 20:1] expanded
// CHECK-EXPANDED-NEXT:-AbstractFunctionDecl {{.*}} genericFunc0(t:u:i:) [22:1 - 23:1] expanded
// CHECK-EXPANDED-NEXT: -GenericParams {{.*}} param 0 [22:19 - 23:1] expanded
// CHECK-EXPANDED-NEXT: -GenericParams {{.*}} param 1 [22:22 - 23:1] expanded
// CHECK-EXPANDED-NEXT: -AbstractFunctionParams {{.*}} genericFunc0(t:u:i:) param 0:0 [22:28 - 23:1] expanded
// CHECK-EXPANDED-NEXT: -AbstractFunctionParams {{.*}} genericFunc0(t:u:i:) param 0:1 [22:34 - 23:1] expanded
// CHECK-EXPANDED: |-DefaultArgument {{.*}} [22:46 - 22:46] expanded
// CHECK-EXPANDED: `-AbstractFunctionParams {{.*}} genericFunc0(t:u:i:) param 0:2 [22:46 - 23:1] expanded
// CHECK-EXPANDED-NEXT: `-AbstractFunctionBody {{.*}} genericFunc0(t:u:i:) [22:50 - 23:1] expanded
// CHECK-EXPANDED-NEXT: -BraceStmt {{.*}} [22:50 - 23:1] expanded
// CHECK-EXPANDED-NEXT: TypeDecl {{.*}} ContainsGenerics0 [25:1 - 31:1] expanded
// CHECK-EXPANDED-NEXT: -TypeOrExtensionBody {{.*}} 'ContainsGenerics0' [25:25 - 31:1] expanded
// CHECK-EXPANDED-NEXT: -AbstractFunctionDecl {{.*}} init(t:u:) [26:3 - 27:3] expanded
// CHECK-EXPANDED-NEXT: -GenericParams {{.*}} param 0 [26:8 - 27:3] expanded
// CHECK-EXPANDED-NEXT: -GenericParams {{.*}} param 1 [26:11 - 27:3] expanded
// CHECK-EXPANDED-NEXT: -AbstractFunctionParams {{.*}} init(t:u:) param 0:0 [26:13 - 27:3] expanded
// CHECK-EXPANDED-NEXT: -AbstractFunctionParams {{.*}} init(t:u:) param 1:0 [26:17 - 27:3] expanded
// CHECK-EXPANDED-NEXT: -AbstractFunctionParams {{.*}} init(t:u:) param 1:1 [26:23 - 27:3] expanded
// CHECK-EXPANDED-NEXT: `-AbstractFunctionBody {{.*}} init(t:u:) [26:26 - 27:3] expanded
// CHECK-EXPANDED-NEXT: -BraceStmt {{.*}} [26:26 - 27:3] expanded
// CHECK-EXPANDED-NEXT: -AbstractFunctionDecl {{.*}} deinit
// CHECK-EXPANDED-NEXT: -AbstractFunctionParams {{.*}} deinit param 0:0 [29:3 - 30:3] expanded
// CHECK-EXPANDED-NEXT: `-AbstractFunctionBody {{.*}} deinit [29:10 - 30:3] expanded
// CHECK-EXPANDED-NEXT: -BraceStmt {{.*}} [29:10 - 30:3] expanded
// CHECK-EXPANDED-NEXT: TypeDecl {{.*}} GenericAlias0 [33:1 - 33:32] expanded
// CHECK-EXPANDED-NEXT: -GenericParams {{.*}} param 0 [33:25 - 33:32] expanded
// CHECK-EXPANDED-NEXT: TypeDecl {{.*}} {{.*}}ArchStruct [{{.*}}] expanded
// CHECK-EXPANDED-NEXT: TypeOrExtensionBody {{.*}} '{{.*}}ArchStruct' [{{.*}}] expanded
// CHECK-EXPANDED-NEXT: {{^}}|-AbstractFunctionDecl {{.*}} functionBodies1(a:b:) [41:1 - 100:1] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} functionBodies1(a:b:) param 0:0 [41:25 - 100:1] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} functionBodies1(a:b:) param 0:1 [41:36 - 100:1] expanded
// CHECK-EXPANDED-NEXT: `-AbstractFunctionBody {{.*}} functionBodies1(a:b:) [41:39 - 100:1] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [41:39 - 100:1] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-PatternBinding {{.*}} entry 0 [42:7 - 100:1] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-PatternInitializer {{.*}} entry 0 [42:18 - 42:23] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AfterPatternBinding {{.*}} entry 0 [42:23 - 100:1] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-PatternBinding {{.*}} entry 1 [43:7 - 100:1] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-PatternInitializer {{.*}} entry 1 [43:18 - 43:23] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AfterPatternBinding {{.*}} entry 1 [43:23 - 100:1] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-PatternBinding {{.*}} entry 0 [44:7 - 100:1] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-PatternInitializer {{.*}} entry 0 [44:18 - 44:23] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AfterPatternBinding {{.*}} entry 0 [44:23 - 100:1] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-BraceStmt {{.*}} [45:6 - 52:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-PatternBinding {{.*}} entry 0 [46:9 - 52:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-PatternInitializer {{.*}} entry 0 [46:14 - 46:14] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AfterPatternBinding {{.*}} entry 0 [46:14 - 52:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-PatternBinding {{.*}} entry 0 [47:9 - 52:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-PatternInitializer {{.*}} entry 0 [47:14 - 47:14] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AfterPatternBinding {{.*}} entry 0 [47:14 - 52:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [48:8 - 51:5] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-PatternBinding {{.*}} entry 0 [49:11 - 51:5] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-PatternInitializer {{.*}} entry 0 [49:16 - 49:16] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AfterPatternBinding {{.*}} entry 0 [49:16 - 51:5] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-PatternBinding {{.*}} entry 0 [50:11 - 51:5] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-PatternInitializer {{.*}} entry 0 [50:16 - 50:16] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AfterPatternBinding {{.*}} entry 0 [50:16 - 51:5] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-BraceStmt {{.*}} [53:6 - 56:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-PatternBinding {{.*}} entry 0 [54:9 - 56:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-PatternInitializer {{.*}} entry 0 [54:14 - 54:14] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AfterPatternBinding {{.*}} entry 0 [54:14 - 56:3] expanded
// CHECK-EXPANDED: {{^}} `-AfterPatternBinding {{.*}} entry 0 [55:14 - 56:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-AbstractFunctionDecl {{.*}} f(_:) [57:3 - 57:38] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} f(_:) param 0:0 [57:15 - 57:38] expanded
// CHECK-EXPANDED-NEXT: `-AbstractFunctionBody {{.*}} f(_:) [57:27 - 57:38] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [57:27 - 57:38] expanded
// CHECK-EXPANDED: {{^}} `-AfterPatternBinding {{.*}} entry 0 [58:16 - 100:1] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-TypeDecl {{.*}} S7 [59:3 - 59:15] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-TypeOrExtensionBody {{.*}} 'S7' [59:13 - 59:15] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-TypeDecl {{.*}} S7Alias [60:3 - 60:23] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-IfStmt {{.*}} [62:3 - 66:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-ConditionalClause {{.*}} index 0 [62:18 - 64:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-ConditionalClause {{.*}} index 1 [62:29 - 64:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [62:29 - 64:3] expanded
// CHECK-EXPANDED: {{^}} `-AfterPatternBinding {{.*}} entry 0 [63:14 - 64:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [64:10 - 66:3] expanded
// CHECK-EXPANDED: {{^}} `-AfterPatternBinding {{.*}} entry 0 [65:14 - 66:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-GuardStmt {{.*}} [68:3 - 100:1] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-ConditionalClause {{.*}} index 0 [68:21 - 68:53] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-ConditionalClause {{.*}} index 1 [68:21 - 68:53] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-Closure {{.*}} [68:21 - 68:30] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [68:21 - 68:30] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-ConditionalClause {{.*}} index 2 [68:53 - 68:53] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-BraceStmt {{.*}} [68:53 - 71:3] expanded
// CHECK-EXPANDED: {{^}} `-AfterPatternBinding {{.*}} entry 0 [69:13 - 71:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-ConditionalClause {{.*}} index 0 guard-continuation [71:3 - 100:1] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-ConditionalClause {{.*}} index 1 guard-continuation [71:3 - 100:1] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-ConditionalClause {{.*}} index 2 guard-continuation [71:3 - 100:1] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-ConditionalClause {{.*}} index 0 [73:21 - 75:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-ConditionalClause {{.*}} index 1 [73:32 - 75:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [73:32 - 75:3] expanded
// CHECK-EXPANDED: {{^}} `-AfterPatternBinding {{.*}} entry 0 [74:13 - 75:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-RepeatWhileStmt {{.*}} [77:3 - 77:20] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [77:10 - 77:12] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-ForEachStmt {{.*}} [79:3 - 81:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-ForEachPattern {{.*}} [79:52 - 81:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [79:63 - 81:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-DoCatchStmt {{.*}} [83:3 - 87:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-BraceStmt {{.*}} [83:6 - 85:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-CatchStmt {{.*}} [85:31 - 86:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [85:54 - 86:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-CatchStmt {{.*}} [86:11 - 87:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [86:11 - 87:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-SwitchStmt {{.*}} [89:3 - 98:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-CaseStmt {{.*}} [90:29 - 91:10] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [91:5 - 91:10] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-CaseStmt {{.*}} [94:5 - 94:10] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [94:5 - 94:10] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-CaseStmt {{.*}} [97:5 - 97:10] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [97:5 - 97:10] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-ForEachStmt {{.*}} [99:3 - 99:38] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-ForEachPattern {{.*}} [99:36 - 99:38] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [99:36 - 99:38] expanded
// CHECK-EXPANDED: TypeDecl {{.*}} StructContainsAbstractStorageDecls [114:1 - 130:1] expanded
// CHECK-EXPANDED-NEXT: `-TypeOrExtensionBody {{.*}} 'StructContainsAbstractStorageDecls' [114:43 - 130:1] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-Accessors {{.*}} scope_map.(file).StructContainsAbstractStorageDecls.subscript@{{.*}}scope_map.swift:115:3 [115:37 - 121:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-AbstractFunctionDecl {{.*}} _ [116:5 - 117:5] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 0:0 [116:5 - 117:5] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 1:0 [116:5 - 117:5] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 1:1 [116:5 - 117:5] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 1:2 [116:5 - 117:5] expanded
// CHECK-EXPANDED-NEXT: `-AbstractFunctionBody {{.*}} _ [116:9 - 117:5] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [116:9 - 117:5] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionDecl {{.*}} _ [118:5 - 120:5] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 0:0 [118:5 - 120:5] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 1:0 [118:5 - 120:5] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 1:1 [118:5 - 120:5] expanded
// CHECK-EXPANDED-NEXT: `-AbstractFunctionBody {{.*}} _ [118:9 - 120:5] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [118:9 - 120:5] expanded
// CHECK-EXPANDED: {{^}} `-Accessors {{.*}} scope_map.(file).StructContainsAbstractStorageDecls.computed@{{.*}}scope_map.swift:123:7 [123:21 - 129:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-AbstractFunctionDecl {{.*}} _ [124:5 - 126:5] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 0:0 [124:5 - 126:5] expanded
// CHECK-EXPANDED-NEXT: `-AbstractFunctionBody {{.*}} _ [124:9 - 126:5] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [124:9 - 126:5] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionDecl {{.*}} _ [127:5 - 128:5] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 0:0 [127:5 - 128:5] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 1:0 [127:5 - 128:5] expanded
// CHECK-EXPANDED-NEXT: `-AbstractFunctionBody {{.*}} _ [127:9 - 128:5] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [127:9 - 128:5] expanded
// CHECK-EXPANDED: TypeDecl {{.*}} ClassWithComputedProperties [132:1 - 140:1] expanded
// CHECK-EXPANDED-NEXT: -TypeOrExtensionBody {{.*}} 'ClassWithComputedProperties' [132:35 - 140:1] expanded
// CHECK-EXPANDED: {{^}} `-Accessors {{.*}} scope_map.(file).ClassWithComputedProperties.willSetProperty@{{.*}}scope_map.swift:133:7 [133:32 - 135:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionDecl {{.*}} _ [134:5 - 134:15] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 0:0 [134:5 - 134:15] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 1:0 [134:5 - 134:15] expanded
// CHECK-EXPANDED: {{^}} `-BraceStmt {{.*}} [134:13 - 134:15] expanded
// CHECK-EXPANDED: {{^}} `-Accessors {{.*}} scope_map.(file).ClassWithComputedProperties.didSetProperty@{{.*}}scope_map.swift:137:7 [137:31 - 139:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionDecl {{.*}} _ [138:5 - 138:14] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 0:0 [138:5 - 138:14] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 1:0 [138:5 - 138:14] expanded
// CHECK-EXPANDED: {{^}} `-BraceStmt {{.*}} [138:12 - 138:14] expanded
// CHECK-EXPANDED: {{^}} `-AbstractFunctionParams {{.*}} funcWithComputedProperties(i:) param 0:0 [142:36 - 155:1] expanded
// CHECK-EXPANDED: {{^}} `-BraceStmt {{.*}} [142:41 - 155:1] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-PatternBinding {{.*}} entry 0 [143:7 - 155:1] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AfterPatternBinding {{.*}} entry 0 [143:17 - 155:1] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-Accessors {{.*}} scope_map.(file).funcWithComputedProperties(i:).computed@{{.*}}scope_map.swift:143:7 [143:21 - 149:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-AbstractFunctionDecl {{.*}} _ [144:5 - 145:5] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 0:0 [144:5 - 145:5] expanded
// CHECK-EXPANDED: {{^}} `-BraceStmt {{.*}} [144:9 - 145:5] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionDecl {{.*}} _ [146:5 - 148:5] expanded
// CHECK-EXPANDED: {{^}} `-BraceStmt {{.*}} [146:9 - 148:5] expanded
// CHECK-EXPANDED: {{^}} `-AfterPatternBinding {{.*}} entry 1 [149:36 - 155:1] expanded
// CHECK-EXPANDED: {{^}} `-AfterPatternBinding {{.*}} entry 2 [150:21 - 155:1] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-Accessors {{.*}} [150:25 - 152:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionDecl {{.*}} _ [150:25 - 152:3] expanded
// CHECK-EXPANDED: {{^}} `-BraceStmt {{.*}} [150:25 - 152:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [154:6 - 154:8] expanded
// CHECK-EXPANDED: |-AbstractFunctionDecl {{.*}} closures() [157:1 - 162:1] expanded
// CHECK-EXPANDED: {{^}} `-BraceStmt {{.*}} [157:17 - 162:1] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-Preexpanded {{.*}} [158:10 - 161:19] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-Closure {{.*}} [158:10 - 160:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [158:10 - 160:3] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-Closure {{.*}} [159:12 - 159:22] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [159:12 - 159:22] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-Closure {{.*}} [161:10 - 161:19] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [161:10 - 161:19] expanded
// CHECK-EXPANDED: `-TopLevelCode {{.*}} [164:1 - [[EOF:[0-9]+:[0-9]+]]] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [164:1 - [[EOF]]] expanded
// CHECK-EXPANDED-NEXT: {{^}} |-Closure {{.*}} [164:1 - 164:14] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [164:1 - 164:14] expanded
// CHECK-EXPANDED: -AbstractFunctionDecl {{.*}} defaultArguments(i:j:) [166:1 - 175:1] expanded
// CHECK-EXPANDED: {{^}} |-DefaultArgument {{.*}} [166:32 - 166:32] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} defaultArguments(i:j:) param 0:0 [166:32 - 175:1] expanded
// CHECK-EXPANDED: {{^}} |-DefaultArgument {{.*}} [167:32 - 167:48] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-Closure {{.*}} [167:32 - 167:42] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [167:32 - 167:42] expanded
// CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} defaultArguments(i:j:) param 0:1 [167:48 - 175:1] expanded
// CHECK-EXPANDED: -Accessors {{.*}} scope_map.(file).ProtoWithSubscript.subscript@{{.*}}scope_map.swift:183:3 [183:33 - 183:43] expanded
// CHECK-EXPANDED-NEXT: |-AbstractFunctionDecl {{.*}} _ [183:35 - 183:35] expanded
// CHECK-EXPANDED-NEXT: `-AbstractFunctionParams {{.*}} _ param 0:0 [183:35 - 183:35] expanded
// CHECK-EXPANDED-NEXT: `-AbstractFunctionParams {{.*}} _ param 1:0 [183:35 - 183:35] expanded
// CHECK-EXPANDED-NEXT: `-AbstractFunctionDecl {{.*}} _ [183:39 - 183:39] expanded
// CHECK-EXPANDED-NEXT: `-AbstractFunctionParams {{.*}} _ param 0:0 [183:39 - 183:39] expanded
// CHECK-EXPANDED-NEXT: `-AbstractFunctionParams {{.*}} _ param 1:0 [183:39 - 183:39] expanded
// CHECK-EXPANDED-NEXT: `-AbstractFunctionParams {{.*}} _ param 1:1 [183:39 - 183:39] expanded
// CHECK-EXPANDED: -AbstractFunctionDecl {{.*}} localPatternsWithSharedType() [186:1 - 188:1] expanded
// CHECK-EXPANDED: `-BraceStmt {{.*}} [186:36 - 188:1] expanded
// CHECK-EXPANDED-NEXT: `-PatternBinding {{.*}} entry 0 [187:7 - 188:1] expanded
// CHECK-EXPANDED-NEXT: `-AfterPatternBinding {{.*}} entry 0 [187:7 - 188:1] expanded
// CHECK-EXPANDED-NEXT: `-PatternBinding {{.*}} entry 1 [187:10 - 188:1] expanded
// CHECK-EXPANDED-NEXT: `-AfterPatternBinding {{.*}} entry 1 [187:10 - 188:1] expanded
// CHECK-EXPANDED-NEXT: `-PatternBinding {{.*}} entry 2 [187:13 - 188:1] expanded
// CHECK-EXPANDED-NEXT: `-AfterPatternBinding {{.*}} entry 2 [187:16 - 188:1] expanded
// RUN: not %target-swift-frontend -dump-scope-maps 70:8,26:20,5:18,166:32,179:18,193:26 %s 2> %t.searches
// RUN: %FileCheck -check-prefix CHECK-SEARCHES %s < %t.searches
// CHECK-SEARCHES-LABEL: ***Scope at 70:8***
// CHECK-SEARCHES-NEXT: AfterPatternBinding {{.*}} entry 0 [69:13 - 71:3] expanded
// CHECK-SEARCHES-NEXT: Local bindings: c
// CHECK-SEARCHES-LABEL: ***Scope at 26:20***
// CHECK-SEARCHES-NEXT: AbstractFunctionParams {{.*}} init(t:u:) param 1:0 [26:17 - 27:3] expanded
// CHECK-SEARCHES-NEXT: Local bindings: t
// CHECK-SEARCHES-LABEL: ***Scope at 5:18***
// CHECK-SEARCHES-NEXT: TypeOrExtensionBody {{.*}} 'InnerC0' [5:17 - 5:19] expanded
// CHECK-SEARCHES-NEXT: Module name=scope_map
// CHECK-SEARCHES-NEXT: FileUnit file="{{.*}}scope_map.swift"
// CHECK-SEARCHES-NEXT: StructDecl name=S0
// CHECK-SEARCHES-NEXT: ClassDecl name=InnerC0
// CHECK-SEARCHES-LABEL: ***Scope at 166:32***
// CHECK-SEARCHES-NEXT: DefaultArgument {{.*}} [166:32 - 166:32] expanded
// CHECK-SEARCHES-NEXT: Module name=scope_map
// CHECK-SEARCHES-NEXT: FileUnit file="{{.*}}scope_map.swift"
// CHECK-SEARCHES-NEXT: AbstractFunctionDecl name=defaultArguments(i:j:) : (Int, Int) -> ()
// CHECK-SEARCHES-NEXT: {{.*}} Initializer DefaultArgument index=0
// CHECK-SEARCHES-LABEL: ***Scope at 179:18***
// CHECK-SEARCHES-NEXT: PatternInitializer {{.*}} entry 1 [179:16 - 179:25] expanded
// CHECK-SEARCHES-NEXT: {{.*}} Module name=scope_map
// CHECK-SEARCHES-NEXT: {{.*}} FileUnit file="{{.*}}scope_map.swift"
// CHECK-SEARCHES-NEXT: {{.*}} StructDecl name=PatternInitializers
// CHECK-SEARCHES-NEXT: {{.*}} Initializer PatternBinding {{.*}} #1
// CHECK-SEARCHES-LABEL: ***Scope at 193:26***
// CHECK-SEARCHES-NEXT: PatternInitializer {{.*}} entry 0 [193:24 - 193:29] expanded
// CHECK-SEARCHES-NEXT: name=scope_map
// CHECK-SEARCHES-NEXT: FileUnit file="{{.*}}scope_map.swift"
// CHECK-SEARCHES-NEXT: ClassDecl name=LazyProperties
// CHECK-SEARCHES-NEXT: Initializer PatternBinding {{.*}} #0
// CHECK-SEARCHES-NEXT: Local bindings: self
// CHECK-SEARCHES-LABEL: ***Complete scope map***
// CHECK-SEARCHES-NEXT: SourceFile {{.*}} '{{.*}}scope_map.swift' [1:1 - [[EOF:[0-9]+:[0-9]+]]] unexpanded
// CHECK-SEARCHES: TypeOrExtensionBody {{.*}} 'S0' [4:11 - 6:1] expanded
// CHECK-SEARCHES: -TypeOrExtensionBody {{.*}} 'InnerC0' [5:17 - 5:19] expanded
// CHECK-SEARCHES-NOT: {{ expanded}}
// CHECK-SEARCHES: -TypeDecl {{.*}} ContainsGenerics0 [25:1 - 31:1] expanded
// CHECK-SEARCHES-NEXT: `-TypeOrExtensionBody {{.*}} 'ContainsGenerics0' [25:25 - 31:1] expanded
// CHECK-SEARCHES-NEXT: |-AbstractFunctionDecl {{.*}} init(t:u:) [26:3 - 27:3] expanded
// CHECK-SEARCHES-NEXT: `-GenericParams {{.*}} param 0 [26:8 - 27:3] expanded
// CHECK-SEARCHES-NEXT: `-GenericParams {{.*}} param 1 [26:11 - 27:3] expanded
// CHECK-SEARCHES-NEXT: `-AbstractFunctionParams {{.*}} init(t:u:) param 0:0 [26:13 - 27:3] expanded
// CHECK-SEARCHES-NEXT: `-AbstractFunctionParams {{.*}} init(t:u:) param 1:0 [26:17 - 27:3] expanded
// CHECK-SEARCHES-NEXT: `-AbstractFunctionParams {{.*}} init(t:u:) param 1:1 [26:23 - 27:3] unexpanded
// CHECK-SEARCHES-NOT: {{ expanded}}
// CHECK-SEARCHES: |-AbstractFunctionDecl {{.*}} functionBodies1(a:b:) [41:1 - 100:1] expanded
// CHECK-SEARCHES: `-AbstractFunctionParams {{.*}} functionBodies1(a:b:) param 0:0 [41:25 - 100:1] expanded
// CHECK-SEARCHES: |-AbstractFunctionDecl {{.*}} throwing() [102:1 - 102:26] unexpanded
// CHECK-SEARCHES: -AbstractFunctionDecl {{.*}} defaultArguments(i:j:) [166:1 - 175:1] expanded
// CHECK-SEARCHES: DefaultArgument {{.*}} [166:32 - 166:32] expanded
// CHECK-SEARCHES-NOT: {{ expanded}}
// CHECK-SEARCHES: |-TypeDecl {{.*}} PatternInitializers [177:1 - 180:1] expanded
// CHECK-SEARCHES: -TypeOrExtensionBody {{.*}} 'PatternInitializers' [177:28 - 180:1] expanded
// CHECK-SEARCHES: |-PatternBinding {{.*}} entry 0 [178:7 - 178:21] unexpanded
// CHECK-SEARCHES: `-PatternBinding {{.*}} entry 1 [179:7 - 179:25] expanded
// CHECK-SEARCHES: `-PatternInitializer {{.*}} entry 1 [179:16 - 179:25] expanded
// CHECK-SEARCHES-NOT: {{ expanded}}
// CHECK-SEARCHES: |-TypeDecl {{.*}} ProtoWithSubscript [182:1 - 184:1] unexpanded
// CHECK-SEARCHES-NOT: {{ expanded}}
// CHECK-SEARCHES: |-AbstractFunctionDecl {{.*}} localPatternsWithSharedType() [186:1 - 188:1] unexpanded
// CHECK-SEARCHES: `-TypeDecl {{.*}} LazyProperties [190:1 - 194:1] expanded
// CHECK-SEARCHES: -TypeOrExtensionBody {{.*}} 'LazyProperties' [190:22 - 194:1] expanded
// CHECK-SEARCHES-NEXT: |-PatternBinding {{.*}} entry 0 [191:7 - 191:20] unexpanded
// CHECK-SEARCHES-NEXT: `-PatternBinding {{.*}} entry 0 [193:12 - 193:29] expanded
// CHECK-SEARCHES-NEXT: `-PatternInitializer {{.*}} entry 0 [193:24 - 193:29] expanded
// CHECK-SEARCHES-NOT: {{ expanded}}
| apache-2.0 | c7b8904115f8ebc3bf7c0f9a09c9afd6 | 56.602 | 165 | 0.575049 | 3.537772 | false | false | false | false |
SnowdogApps/DateKit | DateKitTests/Specs/DKOperationSpec.swift | 1 | 9059 | import Quick
import Nimble
class DKOperationSpec: QuickSpec {
override func spec() {
describe("Operation") {
let today = NSDate()
describe("initialized with arguments") {
let value = 5
let unit = NSCalendarUnit.CalendarUnitDay
var operation: Operation! = Operation(value: value, date: today, unit: unit)
it("should not be nil") {
expect(operation).notTo(beNil())
}
itBehavesLike("operation properties tests") {
[
"operation": operation!,
"value": value,
"date": today,
"unit": unit.rawValue
]
}
}
describe("mathematical operation") {
let testDate = (today.day(1) as Operation).date
let operation = Operation(value: 1, date: testDate, unit: .CalendarUnitDay)
let sharedExampleName = "math operation"
describe("addition") {
itBehavesLike(sharedExampleName) {
[
"operation": operation,
"operator": "add",
"value": 5
]
}
}
describe("substraction") {
itBehavesLike(sharedExampleName) {
[
"operation": operation,
"operator": "substract",
"value": 5
]
}
}
}
describe("getter and setter") {
let value = 5
let sharedExampleName = "operation getters setters"
describe("seconds") {
let operation: Operation = today.second(value)
itBehavesLike(sharedExampleName) {
[
"operation": operation,
"value": value,
"getter": "seconds"
]
}
}
describe("minutes") {
let value = 5
let operation: Operation = today.minute(value)
itBehavesLike(sharedExampleName) {
[
"operation": operation,
"value": value,
"getter": "minutes"
]
}
}
describe("hours") {
let operation: Operation = today.hour(value)
itBehavesLike(sharedExampleName) {
[
"operation": operation,
"value": value,
"getter": "hours"
]
}
}
describe("days") {
let operation: Operation = today.day(value)
itBehavesLike(sharedExampleName) {
[
"operation": operation,
"value": value,
"getter": "days"
]
}
}
describe("months") {
let operation: Operation = today.month(value)
itBehavesLike(sharedExampleName) {
[
"operation": operation,
"value": value,
"getter": "months"
]
}
}
describe("years") {
let operation: Operation = today.year(value)
itBehavesLike(sharedExampleName) {
[
"operation": operation,
"value": value,
"getter": "years"
]
}
}
describe("eras") {
let operation: Operation = today.era(.BC)
itBehavesLike(sharedExampleName) {
[
"operation": operation,
"value": 0,
"getter": "eras"
]
}
}
}
describe("helper") {
let operationHelperExample = "operation helper"
describe("first") {
describe("year") {
var operation = Operation(value: 0, date: today, unit: .CalendarUnitYear)
var resultDate = operation.first
var referenceDate: NSDate = today.setComponent(.CalendarUnitYear, value: 0)
it("should not be nil") {
expect(resultDate).notTo(beNil())
}
it("should be equal to reference date") {
expect(resultDate == referenceDate).to(beTrue())
}
}
}
describe(operationHelperExample) {
itBehavesLike("operation helper") {
[
"helper": "last",
"date": today
]
}
}
}
describe("unit length") {
describe("seconds") {
itBehavesLike("unit length") {
[
"date": today,
"unit": NSCalendarUnit.CalendarUnitSecond.rawValue,
"length": NSNumber(integer: 1000)
]
}
}
describe("minutes") {
itBehavesLike("unit length") {
[
"date": today,
"unit": NSCalendarUnit.CalendarUnitMinute.rawValue,
"length": NSNumber(integer: 60)
]
}
}
describe("hours") {
itBehavesLike("unit length") {
[
"date": today,
"unit": NSCalendarUnit.CalendarUnitHour.rawValue,
"length": NSNumber(integer: 60)
]
}
}
describe("days") {
var length = NSCalendar.currentCalendar().rangeOfUnit(.CalendarUnitHour, inUnit: .CalendarUnitDay, forDate: today).length
itBehavesLike("unit length") {
[
"date": today,
"unit": NSCalendarUnit.CalendarUnitDay.rawValue,
"length": NSNumber(integer: length)
]
}
}
describe("months") {
var length: Int = NSCalendar.currentCalendar().rangeOfUnit(.CalendarUnitDay, inUnit: .CalendarUnitMonth , forDate: today).length
itBehavesLike("unit length") {
[
"date": today,
"unit": NSCalendarUnit.CalendarUnitMonth.rawValue,
"length": NSNumber(integer: length)
]
}
}
describe("years") {
var length: Int = NSCalendar.currentCalendar().rangeOfUnit(.CalendarUnitMonth, inUnit: NSCalendarUnit.CalendarUnitYear, forDate: today).length
itBehavesLike("unit length") {
[
"date": today,
"unit": NSCalendarUnit.CalendarUnitYear.rawValue,
"length": NSNumber(integer: length)
]
}
}
}
}
}
}
| mit | 6ec50f7d77b4fbef2a9665e9895e9755 | 36.433884 | 162 | 0.334253 | 7.437603 | false | false | false | false |
yrchen/edx-app-ios | Source/CourseCardView.swift | 1 | 8892 | //
// CourseCardView.swift
// edX
//
// Created by Jianfeng Qiu on 13/05/2015.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
@IBDesignable
class CourseCardView: UIView {
private let arrowHeight = 15.0
private let verticalMargin = 10
var course: OEXCourse?
private let coverImage = UIImageView()
private let container = UIView()
private let titleLabel = UILabel()
private let detailLabel = UILabel()
private let bottomLine = UIView()
private let bannerLabel = OEXBannerLabel()
private let bottomTrailingLabel = UILabel()
private var titleTextStyle : OEXTextStyle {
return OEXTextStyle(weight : .Normal, size: .Large, color: OEXStyles.sharedStyles().neutralBlack())
}
private var detailTextStyle : OEXTextStyle {
return OEXTextStyle(weight : .Normal, size: .XXXSmall, color: OEXStyles.sharedStyles().neutralXDark())
}
private var bannerTextStyle : OEXTextStyle {
return OEXTextStyle(weight : .Normal, size: .XXXSmall, color: UIColor.whiteColor())
}
private func setup() {
configureViews()
accessibilityTraits = UIAccessibilityTraitStaticText
accessibilityHint = Strings.accessibilityShowsCourseContent
NSNotificationCenter.defaultCenter().oex_addObserver(self, name: OEXImageDownloadCompleteNotification) { (notification, observer, _) -> Void in
observer.setImageForImageView(notification)
}
}
override init(frame : CGRect) {
super.init(frame : frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
@available(iOS 8.0, *)
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
let bundle = NSBundle(forClass: self.dynamicType)
coverImage.image = UIImage(named:"Splash_map", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection)
titleLabel.attributedText = titleTextStyle.attributedStringWithText("Demo Course")
detailLabel.attributedText = detailTextStyle.attributedStringWithText("edx | DemoX")
bottomTrailingLabel.attributedText = detailTextStyle.attributedStringWithText("X Videos, 1.23 MB")
bannerLabel.attributedText = bannerTextStyle.attributedStringWithText("ENDED - SEPTEMBER 24")
bannerLabel.hidden = false
}
func configureViews() {
self.backgroundColor = OEXStyles.sharedStyles().neutralXLight()
self.clipsToBounds = true
self.bottomLine.backgroundColor = OEXStyles.sharedStyles().neutralXLight()
self.container.backgroundColor = OEXStyles.sharedStyles().neutralWhite().colorWithAlphaComponent(0.85)
self.coverImage.backgroundColor = OEXStyles.sharedStyles().neutralWhiteT()
self.coverImage.contentMode = UIViewContentMode.ScaleAspectFill
self.coverImage.clipsToBounds = true
self.container.accessibilityIdentifier = "Title Bar"
self.container.addSubview(titleLabel)
self.container.addSubview(detailLabel)
self.container.addSubview(bannerLabel)
self.container.addSubview(bottomTrailingLabel)
self.addSubview(coverImage)
self.addSubview(container)
self.insertSubview(bottomLine, aboveSubview: coverImage)
bannerLabel.hidden = true
bannerLabel.adjustsFontSizeToFitWidth = true
coverImage.setContentCompressionResistancePriority(UILayoutPriorityDefaultLow, forAxis: .Horizontal)
detailLabel.setContentHuggingPriority(UILayoutPriorityDefaultLow, forAxis: UILayoutConstraintAxis.Horizontal)
detailLabel.setContentCompressionResistancePriority(UILayoutPriorityDefaultHigh, forAxis: UILayoutConstraintAxis.Horizontal)
self.container.snp_makeConstraints { make -> Void in
make.leading.equalTo(self)
make.trailing.equalTo(self).priorityRequired()
make.bottom.equalTo(self).offset(-OEXStyles.dividerSize())
}
self.coverImage.snp_makeConstraints { (make) -> Void in
make.top.equalTo(self)
make.leading.equalTo(self)
make.trailing.equalTo(self)
make.height.equalTo(self.coverImage.snp_width).multipliedBy(0.533).priorityLow()
make.bottom.equalTo(self)
}
self.titleLabel.snp_makeConstraints { (make) -> Void in
make.leading.equalTo(self.container).offset(StandardHorizontalMargin)
make.trailing.lessThanOrEqualTo(self.container).offset(-StandardHorizontalMargin)
make.top.equalTo(self.container).offset(verticalMargin)
}
self.detailLabel.snp_makeConstraints { (make) -> Void in
make.leading.equalTo(self.container).offset(StandardHorizontalMargin)
make.top.equalTo(self.titleLabel.snp_bottom)
make.bottom.equalTo(self.container).offset(-verticalMargin)
}
self.bannerLabel.snp_makeConstraints { (make) -> Void in
make.leading.greaterThanOrEqualTo(self.detailLabel.snp_trailing).offset(StandardHorizontalMargin)
make.trailing.equalTo(self.container).offset(-StandardHorizontalMargin).priorityHigh()
make.centerY.equalTo(self.detailLabel)
make.height.equalTo(arrowHeight)
}
self.bottomLine.snp_makeConstraints { (make) -> Void in
make.leading.equalTo(self)
make.trailing.equalTo(self)
make.bottom.equalTo(self)
make.top.equalTo(self.container.snp_bottom)
}
self.bottomTrailingLabel.snp_makeConstraints { (make) -> Void in
make.centerY.equalTo(detailLabel)
make.trailing.equalTo(self.container).offset(-StandardHorizontalMargin)
}
}
var titleText : String? {
get {
return self.titleLabel.text
}
set {
self.titleLabel.attributedText = titleTextStyle.attributedStringWithText(newValue)
updateAcessibilityLabel()
}
}
var detailText : String? {
get {
return self.detailLabel.text
}
set {
self.detailLabel.attributedText = detailTextStyle.attributedStringWithText(newValue)
updateAcessibilityLabel()
}
}
var bannerText : String? {
get {
return self.bannerLabel.text
}
set {
self.bannerLabel.attributedText = bannerTextStyle.attributedStringWithText(newValue)
self.bannerLabel.hidden = !(newValue != nil && !newValue!.isEmpty)
updateAcessibilityLabel()
}
}
var bottomTrailingText : String? {
get {
return self.bottomTrailingLabel.text
}
set {
self.bottomTrailingLabel.attributedText = detailTextStyle.attributedStringWithText(newValue)
self.bottomTrailingLabel.hidden = !(newValue != nil && !newValue!.isEmpty)
updateAcessibilityLabel()
}
}
private func updateAcessibilityLabel() {
accessibilityLabel = "\(titleText),\(detailText),\(bannerText ?? bottomTrailingText)"
}
private func imageURL() -> String? {
if let courseInCell = self.course, relativeURLString = courseInCell.course_image_url {
let baseURL = NSURL(string:OEXConfig.sharedConfig().apiHostURL() ?? "")
return NSURL(string: relativeURLString, relativeToURL: baseURL)?.absoluteString
}
return nil
}
func setCoverImage() {
setImage(UIImage(named: "Splash_map"))
if let imageURL = imageURL() where !imageURL.isEmpty {
OEXImageCache.sharedInstance().getImage(imageURL)
}
}
private func setImage(image: UIImage?) {
coverImage.image = image
if let image = image {
let ar = image.size.height / image.size.width
coverImage.snp_remakeConstraints { (make) -> Void in
make.top.equalTo(self)
make.leading.equalTo(self)
make.trailing.equalTo(self)
make.height.equalTo(self.coverImage.snp_width).multipliedBy(ar).priorityLow()
make.bottom.equalTo(self)
}
}
}
func setImageForImageView(notification: NSNotification) {
let dictObj = notification.object as! NSDictionary
let image: UIImage? = dictObj.objectForKey("image") as? UIImage
let downloadImageUrl: String? = dictObj.objectForKey("image_url") as? String
if let downloadedImage = image, imageURL = imageURL() {
if imageURL == downloadImageUrl {
setImage(downloadedImage)
}
}
}
}
| apache-2.0 | 8f88c7bd250c4aa2b441ed672f746b16 | 38.345133 | 151 | 0.651035 | 5.252215 | false | false | false | false |
netguru/inbbbox-ios | Inbbbox/Source Files/Views/Custom/ShotsCollectionBackgroundView.swift | 1 | 7782 | //
// Copyright (c) 2016 Netguru Sp. z o.o. All rights reserved.
//
import PureLayout
import UIKit
struct ShotsCollectionBackgroundViewSpacing {
static let logoDefaultVerticalInset = CGFloat(60)
static let logoAnimationVerticalInset = CGFloat(200)
static let logoHeight = CGFloat(30)
static let labelDefaultHeight = CGFloat(21)
static let showingYouDefaultVerticalSpacing = CGFloat(45)
static let showingYouHiddenVerticalSpacing = CGFloat(60)
static let containerDefaultVerticalSpacing = CGFloat(70)
static let skipButtonBottomInset = CGFloat(119)
}
class ShotsCollectionSourceItem {
let label: UILabel
var heightConstraint: NSLayoutConstraint?
var verticalSpacingConstraint: NSLayoutConstraint?
var visible: Bool {
didSet {
heightConstraint?.constant = visible ? ShotsCollectionBackgroundViewSpacing.labelDefaultHeight : 0
}
}
init() {
label = UILabel()
heightConstraint = nil
verticalSpacingConstraint = nil
visible = false
}
}
class ShotsCollectionBackgroundView: UIView {
fileprivate var didSetConstraints = false
let logoImageView = UIImageView(image: UIImage(named: ColorModeProvider.current().logoImageName))
let containerView = UIView()
let arrowImageView = UIImageView(image: UIImage(named: "ic-arrow"))
let showingYouLabel = UILabel()
let followingItem = ShotsCollectionSourceItem()
let newTodayItem = ShotsCollectionSourceItem()
let popularTodayItem = ShotsCollectionSourceItem()
let debutsItem = ShotsCollectionSourceItem()
var showingYouVerticalConstraint: NSLayoutConstraint?
var logoVerticalConstraint: NSLayoutConstraint?
let skipButton = UIButton()
// MARK: - Life cycle
convenience init() {
self.init(frame: CGRect.zero)
logoImageView.configureForAutoLayout()
addSubview(logoImageView)
addSubview(arrowImageView)
arrowImageView.alpha = 0
setupItems()
setupShowingYouLabel()
setupSkipButton()
showingYouLabel.text = Localized("BackgroundView.ShowingYou", comment: "Showing You title")
showingYouLabel.font = UIFont.systemFont(ofSize: 15, weight: UIFontWeightRegular)
showingYouLabel.textColor = UIColor.RGBA(98, 109, 104, 0.9)
showingYouLabel.alpha = 0
addSubview(showingYouLabel)
}
// MARK: - UIView
override class var requiresConstraintBasedLayout: Bool {
return true
}
override func updateConstraints() {
if !didSetConstraints {
logoVerticalConstraint = logoImageView.autoPinEdge(toSuperviewEdge: .top, withInset: ShotsCollectionBackgroundViewSpacing.logoDefaultVerticalInset)
logoImageView.autoAlignAxis(toSuperviewAxis: .vertical)
arrowImageView.autoPinEdge(.left, to: .right, of: logoImageView, withOffset: 12)
arrowImageView.autoAlignAxis(.horizontal, toSameAxisOf: logoImageView)
showingYouVerticalConstraint = showingYouLabel.autoPinEdge(toSuperviewEdge: .top, withInset: ShotsCollectionBackgroundViewSpacing.showingYouHiddenVerticalSpacing)
showingYouLabel.autoAlignAxis(toSuperviewAxis: .vertical)
showingYouLabel.autoSetDimension(.height, toSize: 29)
containerView.autoPinEdge(toSuperviewEdge: .top, withInset: ShotsCollectionBackgroundViewSpacing.containerDefaultVerticalSpacing)
containerView.autoAlignAxis(toSuperviewAxis: .vertical)
containerView.autoSetDimensions(to: CGSize(width: 150, height: 4 * ShotsCollectionBackgroundViewSpacing.labelDefaultHeight))
let items = [followingItem, newTodayItem, popularTodayItem, debutsItem]
for (index, item) in items.enumerated() {
item.heightConstraint = item.label.autoSetDimension(.height, toSize: 0)
item.label.autoSetDimension(.width, toSize: 150)
item.label.autoAlignAxis(toSuperviewAxis: .vertical)
if (index == 0) {
item.verticalSpacingConstraint = item.label.autoPinEdge(toSuperviewEdge: .top, withInset: -5)
} else {
item.verticalSpacingConstraint = item.label.autoPinEdge(.top, to: .bottom, of: items[index - 1].label, withOffset: -5)
}
}
skipButton.autoAlignAxis(toSuperviewAxis: .vertical)
skipButton.autoPinEdge(toSuperviewEdge: .bottom, withInset: ShotsCollectionBackgroundViewSpacing.skipButtonBottomInset)
didSetConstraints = true
}
super.updateConstraints()
}
}
// Animatable header
extension ShotsCollectionBackgroundView {
func prepareAnimatableContent() {
followingItem.visible = Settings.StreamSource.SelectedStreamSource == .mySet ? Settings.StreamSource.Following : Settings.StreamSource.SelectedStreamSource == .following
newTodayItem.visible = Settings.StreamSource.SelectedStreamSource == .mySet ? Settings.StreamSource.NewToday : Settings.StreamSource.SelectedStreamSource == .newToday
popularTodayItem.visible = Settings.StreamSource.SelectedStreamSource == .mySet ? Settings.StreamSource.PopularToday : Settings.StreamSource.SelectedStreamSource == .popularToday
debutsItem.visible = Settings.StreamSource.SelectedStreamSource == .mySet ? Settings.StreamSource.Debuts : Settings.StreamSource.SelectedStreamSource == .debuts
for item in [followingItem, newTodayItem, popularTodayItem, debutsItem] {
item.verticalSpacingConstraint?.constant = 0
}
}
func availableItems() -> [ShotsCollectionSourceItem] {
var items = [ShotsCollectionSourceItem]()
for item in [followingItem, newTodayItem, popularTodayItem, debutsItem] {
if (item.visible) {
items.append(item)
}
}
return items
}
}
fileprivate extension ShotsCollectionBackgroundView {
func setupItems() {
followingItem.label.text = Localized("SettingsViewModel.Following", comment: "User settings, enable following")
newTodayItem.label.text = Localized("SettingsViewModel.NewToday", comment: "User settings, enable new today")
popularTodayItem.label.text = Localized("SettingsViewModel.Popular", comment: "User settings, enable popular")
debutsItem.label.text = Localized("SettingsViewModel.Debuts", comment: "User settings, enable debuts")
for item in [followingItem, newTodayItem, popularTodayItem, debutsItem] {
item.label.textAlignment = .center
item.label.font = UIFont.systemFont(ofSize: 15, weight: UIFontWeightLight)
item.label.textColor = UIColor.RGBA(143, 142, 148, 1)
item.label.alpha = 0
containerView.addSubview(item.label)
}
addSubview(containerView)
}
func setupShowingYouLabel() {
showingYouLabel.text = Localized("BackgroundView.ShowingYou", comment: "Showing You title")
showingYouLabel.font = UIFont.systemFont(ofSize: 15, weight: UIFontWeightRegular)
showingYouLabel.textColor = UIColor.RGBA(98, 109, 104, 0.9)
showingYouLabel.alpha = 0
addSubview(showingYouLabel)
}
func setupSkipButton() {
skipButton.setTitle(Localized("ShotsOnboardingStateHandler.Skip", comment: "Onboarding user is skipping step"), for: .normal)
skipButton.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFontWeightLight)
skipButton.setTitleColor(UIColor.black, for: .normal)
skipButton.isHidden = true
skipButton.alpha = 0
addSubview(skipButton)
}
}
| gpl-3.0 | fb7571958147108094d8568ed197d94a | 41.758242 | 186 | 0.695965 | 5.05653 | false | false | false | false |
breadwallet/breadwallet-ios | breadwallet/src/Views/HomeScreenCell.swift | 1 | 8818 | //
// HomeScreenCell.swift
// breadwallet
//
// Created by Adrian Corscadden on 2017-11-28.
// Copyright © 2017-2019 Breadwinner AG. All rights reserved.
//
import UIKit
protocol HighlightableCell {
func highlight()
func unhighlight()
}
enum HomeScreenCellIds: String {
case regularCell = "CurrencyCell"
case highlightableCell = "HighlightableCurrencyCell"
}
class Background: UIView, GradientDrawable {
var currency: Currency?
override func layoutSubviews() {
super.layoutSubviews()
let maskLayer = CAShapeLayer()
let corners: UIRectCorner = .allCorners
maskLayer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners,
cornerRadii: CGSize(width: C.Sizes.homeCellCornerRadius,
height: C.Sizes.homeCellCornerRadius)).cgPath
layer.mask = maskLayer
}
override func draw(_ rect: CGRect) {
guard let currency = currency else { return }
let colors = currency.isSupported ? currency.colors : (UIColor.disabledCellBackground, UIColor.disabledCellBackground)
drawGradient(start: colors.0, end: colors.1, rect)
}
}
class HomeScreenCell: UITableViewCell, Subscriber {
private let iconContainer = UIView(color: .transparentIconBackground)
private let icon = UIImageView()
private let currencyName = UILabel(font: Theme.body1Accent, color: Theme.primaryText)
private let price = UILabel(font: Theme.body3, color: Theme.secondaryText)
private let fiatBalance = UILabel(font: Theme.body1Accent, color: Theme.primaryText)
private let tokenBalance = UILabel(font: Theme.body3, color: Theme.secondaryText)
private let syncIndicator = SyncingIndicator(style: .home)
private let priceChangeView = PriceChangeView(style: .percentOnly)
let container = Background() // not private for inheritance
private var isSyncIndicatorVisible: Bool = false {
didSet {
UIView.crossfade(tokenBalance, syncIndicator, toRight: isSyncIndicatorVisible, duration: isSyncIndicatorVisible == oldValue ? 0.0 : 0.3)
fiatBalance.textColor = (isSyncIndicatorVisible || !(container.currency?.isSupported ?? false)) ? .disabledWhiteText : .white
}
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupViews()
}
static func cellIdentifier() -> String {
return "CurrencyCell"
}
func set(viewModel: HomeScreenAssetViewModel) {
accessibilityIdentifier = viewModel.currency.name
container.currency = viewModel.currency
icon.image = viewModel.currency.imageNoBackground
icon.tintColor = viewModel.currency.isSupported ? .white : .disabledBackground
iconContainer.layer.cornerRadius = C.Sizes.homeCellCornerRadius
currencyName.text = viewModel.currency.name
currencyName.textColor = viewModel.currency.isSupported ? .white : .disabledWhiteText
price.text = viewModel.exchangeRate
fiatBalance.text = viewModel.fiatBalance
fiatBalance.textColor = viewModel.currency.isSupported ? .white : .disabledWhiteText
tokenBalance.text = viewModel.tokenBalance
priceChangeView.isHidden = false
priceChangeView.currency = viewModel.currency
container.setNeedsDisplay()
Store.subscribe(self, selector: { $0[viewModel.currency]?.syncState != $1[viewModel.currency]?.syncState },
callback: { state in
if viewModel.currency.isHBAR && (Store.state.requiresCreation(viewModel.currency)) {
self.isSyncIndicatorVisible = false
return
}
guard let syncState = state[viewModel.currency]?.syncState else { return }
self.syncIndicator.syncState = syncState
switch syncState {
case .connecting, .failed, .syncing:
self.isSyncIndicatorVisible = true
case .success:
self.isSyncIndicatorVisible = false
}
})
Store.subscribe(self, selector: { $0[viewModel.currency]?.syncProgress != $1[viewModel.currency]?.syncProgress },
callback: { state in
if let progress = state[viewModel.currency]?.syncProgress {
self.syncIndicator.progress = progress
}
})
}
func setupViews() {
addSubviews()
addConstraints()
setupStyle()
}
private func addSubviews() {
contentView.addSubview(container)
container.addSubview(iconContainer)
iconContainer.addSubview(icon)
container.addSubview(currencyName)
container.addSubview(price)
container.addSubview(fiatBalance)
container.addSubview(tokenBalance)
container.addSubview(syncIndicator)
container.addSubview(priceChangeView)
syncIndicator.isHidden = true
}
private func addConstraints() {
let containerPadding = C.padding[1]
container.constrain(toSuperviewEdges: UIEdgeInsets(top: 0,
left: containerPadding,
bottom: -C.padding[1],
right: -containerPadding))
iconContainer.constrain([
iconContainer.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: containerPadding),
iconContainer.centerYAnchor.constraint(equalTo: container.centerYAnchor),
iconContainer.heightAnchor.constraint(equalToConstant: 40),
iconContainer.widthAnchor.constraint(equalTo: iconContainer.heightAnchor)])
icon.constrain(toSuperviewEdges: .zero)
currencyName.constrain([
currencyName.leadingAnchor.constraint(equalTo: iconContainer.trailingAnchor, constant: containerPadding),
currencyName.bottomAnchor.constraint(equalTo: icon.centerYAnchor, constant: 0.0)])
price.constrain([
price.leadingAnchor.constraint(equalTo: currencyName.leadingAnchor),
price.topAnchor.constraint(equalTo: currencyName.bottomAnchor)])
priceChangeView.constrain([
priceChangeView.leadingAnchor.constraint(equalTo: price.trailingAnchor),
priceChangeView.centerYAnchor.constraint(equalTo: price.centerYAnchor),
priceChangeView.heightAnchor.constraint(equalToConstant: 24)])
fiatBalance.constrain([
fiatBalance.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -containerPadding),
fiatBalance.leadingAnchor.constraint(greaterThanOrEqualTo: currencyName.trailingAnchor, constant: C.padding[1]),
fiatBalance.topAnchor.constraint(equalTo: currencyName.topAnchor)])
tokenBalance.constrain([
tokenBalance.trailingAnchor.constraint(equalTo: fiatBalance.trailingAnchor),
tokenBalance.leadingAnchor.constraint(greaterThanOrEqualTo: priceChangeView.trailingAnchor, constant: C.padding[1]),
tokenBalance.bottomAnchor.constraint(equalTo: price.bottomAnchor)])
tokenBalance.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
fiatBalance.setContentCompressionResistancePriority(.required, for: .vertical)
fiatBalance.setContentCompressionResistancePriority(.required, for: .horizontal)
syncIndicator.constrain([
syncIndicator.trailingAnchor.constraint(equalTo: fiatBalance.trailingAnchor),
syncIndicator.leadingAnchor.constraint(greaterThanOrEqualTo: priceChangeView.trailingAnchor, constant: C.padding[1]),
syncIndicator.bottomAnchor.constraint(equalTo: tokenBalance.bottomAnchor, constant: 0.0)])
syncIndicator.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
layoutIfNeeded()
}
private func setupStyle() {
selectionStyle = .none
backgroundColor = .clear
iconContainer.layer.cornerRadius = 6.0
iconContainer.clipsToBounds = true
icon.tintColor = .white
}
override func prepareForReuse() {
Store.unsubscribe(self)
}
deinit {
Store.unsubscribe(self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 1bf3e7610069da8c43b81b7b5e71f732 | 45.405263 | 148 | 0.651582 | 5.469603 | false | false | false | false |
netguru/inbbbox-ios | Inbbbox/Source Files/Views/Custom/CustomTabBarItemView.swift | 1 | 1664 | //
// Copyright (c) 2016 Netguru Sp. z o.o. All rights reserved.
//
import UIKit
class CustomTabBarItemView: UIView {
fileprivate var didSetConstraints = false
let nameLabel = UILabel.newAutoLayout()
let iconImageView = UIImageView.newAutoLayout()
// MARK: - Life cycle
init(name: String? = nil, icon: UIImage?) {
super.init(frame: CGRect.zero)
nameLabel.font = UIFont.systemFont(ofSize: 10)
nameLabel.textColor = ColorModeProvider.current().tabBarNormalItemTextColor
nameLabel.text = name
addSubview(nameLabel)
iconImageView.image = icon?.withRenderingMode(.alwaysOriginal)
addSubview(iconImageView)
}
@available(*, unavailable, message: "Use init(name:icon:) instead")
override init(frame: CGRect) {
fatalError("init(coder:) has not been implemented")
}
@available(*, unavailable, message: "Use init(name:icon:) instead")
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - UIView
override class var requiresConstraintBasedLayout: Bool {
return true
}
override func updateConstraints() {
if !didSetConstraints {
iconImageView.autoPinEdge(toSuperviewEdge: .top)
iconImageView.autoAlignAxis(toSuperviewAxis: .vertical)
nameLabel.autoPinEdge(.top, to: .bottom, of: iconImageView, withOffset: 2.0)
nameLabel.autoPinEdge(toSuperviewEdge: .bottom)
nameLabel.autoAlignAxis(toSuperviewAxis: .vertical)
didSetConstraints = true
}
super.updateConstraints()
}
}
| gpl-3.0 | 83f6373aff4502a12f2a675a77a8df5b | 28.714286 | 88 | 0.66226 | 4.851312 | false | false | false | false |
midoks/Swift-Learning | GitHubStar/GitHubStar/GitHubStar/Controllers/common/events/GsEventsCell.swift | 1 | 4590 | //
// GsEventsCell.swift
// GitHubStar
//
// Created by midoks on 16/5/23.
// Copyright © 2016年 midoks. All rights reserved.
//
import UIKit
import SwiftyJSON
class GsEventsCell: UITableViewCell,TTTAttributedLabelDelegate {
var eventIcon = UIImageView()
var eventTime = UILabel()
var authorIcon = UIImageView()
var actionContent = TTTAttributedLabel(frame: CGRect.zero)
var fixHeight:CGFloat = 65.0
var nextList = Array<UILabel>()
var nextContent:UILabel {
get {
return UILabel()
}
set {
newValue.font = UIFont.systemFont(ofSize: 12)
newValue.numberOfLines = 0
newValue.lineBreakMode = .byTruncatingTail
newValue.frame = CGRect(x: 50, y: fixHeight, width: self.getWinWidth() - 60, height: 0)
let size = self.getSize(label: newValue)
newValue.frame.size.height = size.height
//newValue.backgroundColor = UIColor.randomColor()
self.contentView.addSubview(newValue)
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.initView()
}
//初始化视图
func initView(){
let w = self.getWinWidth()
eventIcon.image = UIImage(named: "repo_file")
eventIcon.frame = CGRect(x: 25, y: 7.5, width: 15, height: 15)
eventIcon.backgroundColor = UIColor.white
self.contentView.addSubview(eventIcon)
eventTime.frame = CGRect(x: 50, y: 5, width: w - 50, height: 20)
eventTime.text = "30分钟前"
eventTime.textAlignment = .left
eventTime.font = UIFont.systemFont(ofSize: 10)
self.contentView.addSubview(eventTime)
authorIcon.image = UIImage(named: "avatar_default")
authorIcon.layer.cornerRadius = 17.5
authorIcon.frame = CGRect(x: 10, y: 25, width: 35, height: 35)
authorIcon.clipsToBounds = true
authorIcon.backgroundColor = UIColor.white
self.contentView.addSubview(authorIcon)
actionContent.frame = CGRect(x: 50, y: 25, width: w-60, height: 40)
actionContent.font = UIFont.systemFont(ofSize: 14)
actionContent.numberOfLines = 0
actionContent.lineBreakMode = .byTruncatingTail
actionContent.delegate = self
actionContent.linkAttributes = [kCTUnderlineStyleAttributeName as AnyHashable : false,
kCTUnderlineColorAttributeName as AnyHashable:true]
self.contentView.addSubview(actionContent)
}
func getSize(label:UILabel) -> CGSize {
let size = label.text!.textSizeWithFont(font: label.font,
constrainedToSize: CGSize(width: label.frame.width, height: CGFloat(MAXFLOAT)))
return size
}
func getListHeight() -> CGSize {
var size = CGSize.zero
for i in nextList {
//print(i.text)
i.font = UIFont.systemFont(ofSize: 12)
i.numberOfLines = 0
i.lineBreakMode = .byCharWrapping
i.frame = CGRect(x: 50, y: 0, width: self.getWinWidth() - 60, height:
0)
let s = self.getSize(label: i)
//print(s.height)
size.height += s.height
}
//print("count:",size)
return size
}
func showList(){
for i in 0 ..< nextList.count {
let v = nextList[i]
v.frame = CGRect(x: 50, y: fixHeight + CGFloat(i*15), width: self.getWinWidth() - 60, height: 15)
v.font = UIFont.systemFont(ofSize: 12)
v.numberOfLines = 0
v.lineBreakMode = .byTruncatingTail
//v.backgroundColor = UIColor.randomColor()
contentView.addSubview(v)
}
}
func attributedLabel(_ label: TTTAttributedLabel!, didSelectLinkWith url: URL!) {
print(url)
}
override func layoutSubviews() {
super.layoutSubviews()
}
}
| apache-2.0 | 47940355a14a40415ed3950ef230b224 | 29.885135 | 127 | 0.57646 | 4.664286 | false | false | false | false |
brentdax/swift | test/SILGen/objc_bridging.swift | 1 | 36247 |
// RUN: %empty-directory(%t)
// RUN: %build-silgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-module -o %t -I %S/../Inputs/ObjCBridging %S/../Inputs/ObjCBridging/Appliances.swift
// RUN: %target-swift-emit-silgen(mock-sdk: -sdk %S/Inputs -I %t) -module-name objc_bridging -I %S/../Inputs/ObjCBridging -Xllvm -sil-full-demangle %s -enable-sil-ownership | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-cpu --check-prefix=CHECK-%target-os-%target-cpu
// REQUIRES: objc_interop
import Foundation
import Appliances
func getDescription(_ o: NSObject) -> String {
return o.description
}
// CHECK-LABEL: sil hidden @$s13objc_bridging14getDescription{{.*}}F
// CHECK: bb0([[ARG:%.*]] : @guaranteed $NSObject):
// CHECK: [[DESCRIPTION:%.*]] = objc_method [[ARG]] : $NSObject, #NSObject.description!getter.1.foreign
// CHECK: [[OPT_BRIDGED:%.*]] = apply [[DESCRIPTION]]([[ARG]])
// CHECK: switch_enum [[OPT_BRIDGED]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]]([[BRIDGED:%.*]] : @owned $NSString):
// CHECK-NOT: unchecked_enum_data
// CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @$sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
// CHECK: [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]]
// CHECK: [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]],
// CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]]
// CHECK: br [[CONT_BB:bb[0-9]+]]([[OPT_NATIVE]] : $Optional<String>)
//
// CHECK: [[NONE_BB]]:
// CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.none!enumelt
// CHECK: br [[CONT_BB]]([[OPT_NATIVE]] : $Optional<String>)
//
// CHECK: [[CONT_BB]]([[OPT_NATIVE:%.*]] : @owned $Optional<String>):
// CHECK: switch_enum [[OPT_NATIVE]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: [[NONE_BB]]:
// CHECK: unreachable
//
// CHECK: [[SOME_BB]]([[NATIVE:%.*]] : @owned $String):
// CHECK-NOT: destroy_value [[ARG]]
// CHECK: return [[NATIVE]]
// CHECK:}
func getUppercaseString(_ s: NSString) -> String {
return s.uppercase()
}
// CHECK-LABEL: sil hidden @$s13objc_bridging18getUppercaseString{{.*}}F
// CHECK: bb0([[ARG:%.*]] : @guaranteed $NSString):
// -- The 'self' argument of NSString methods doesn't bridge.
// CHECK-NOT: function_ref @$sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
// CHECK-NOT: function_ref @swift_StringToNSString
// CHECK: [[UPPERCASE_STRING:%.*]] = objc_method [[ARG]] : $NSString, #NSString.uppercase!1.foreign
// CHECK: [[OPT_BRIDGED:%.*]] = apply [[UPPERCASE_STRING]]([[ARG]]) : $@convention(objc_method) (NSString) -> @autoreleased Optional<NSString>
// CHECK: switch_enum [[OPT_BRIDGED]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
//
// CHECK: [[SOME_BB]]([[BRIDGED:%.*]] :
// CHECK-NOT: unchecked_enum_data
// CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @$sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
// CHECK: [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]]
// CHECK: [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]]
// CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]]
// CHECK: br [[CONT_BB:bb[0-9]+]]([[OPT_NATIVE]] : $Optional<String>)
//
// CHECK: [[NONE_BB]]:
// CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.none!enumelt
// CHECK: br [[CONT_BB]]([[OPT_NATIVE]] : $Optional<String>)
//
// CHECK: [[CONT_BB]]([[OPT_NATIVE:%.*]] : @owned $Optional<String>):
// CHECK: switch_enum [[OPT_NATIVE]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: [[NONE_BB]]:
// CHECK: unreachable
//
// CHECK: [[SOME_BB]]([[NATIVE:%.*]] : @owned $String):
// CHECK: return [[NATIVE]]
// CHECK: }
// @interface Foo -(void) setFoo: (NSString*)s; @end
func setFoo(_ f: Foo, s: String) {
var s = s
f.setFoo(s)
}
// CHECK-LABEL: sil hidden @$s13objc_bridging6setFoo{{.*}}F
// CHECK: bb0([[ARG0:%.*]] : @guaranteed $Foo, {{%.*}} : @guaranteed $String):
// CHECK: [[NATIVE:%.*]] = load
// CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @$sSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BORROWED_NATIVE:%.*]] = begin_borrow [[NATIVE]]
// CHECK: [[BRIDGED:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_NATIVE]])
// CHECK: [[OPT_BRIDGED:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]]
// CHECK: [[SET_FOO:%.*]] = objc_method [[ARG0]] : $Foo, #Foo.setFoo!1.foreign
// CHECK: apply [[SET_FOO]]([[OPT_BRIDGED]], [[ARG0]]) : $@convention(objc_method) (Optional<NSString>, Foo) -> ()
// CHECK: destroy_value [[OPT_BRIDGED]]
// CHECK-NOT: destroy_value [[ARG0]]
// CHECK: }
// @interface Foo -(BOOL) zim; @end
func getZim(_ f: Foo) -> Bool {
return f.zim()
}
// CHECK-ios-i386-LABEL: sil hidden @$s13objc_bridging6getZim{{.*}}F
// CHECK-ios-i386: bb0([[SELF:%.*]] : @guaranteed $Foo):
// CHECK-ios-i386: [[METHOD:%.*]] = objc_method [[SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Bool
// CHECK-ios-i386: [[OBJC_BOOL:%.*]] = apply [[METHOD]]([[SELF]]) : $@convention(objc_method) (Foo) -> ObjCBool
// CHECK-ios-i386: [[CONVERT:%.*]] = function_ref @swift_ObjCBoolToBool : $@convention(thin) (ObjCBool) -> Bool
// CHECK-ios-i386: [[SWIFT_BOOL:%.*]] = apply [[CONVERT]]([[OBJC_BOOL]]) : $@convention(thin) (ObjCBool) -> Bool
// CHECK-ios-i386: return [[SWIFT_BOOL]] : $Bool
// CHECK-ios-i386: }
// CHECK-watchos-i386-LABEL: sil hidden @$s13objc_bridging6getZim{{.*}}F
// CHECK-watchos-i386: bb0([[SELF:%.*]] : @guaranteed $Foo):
// CHECK-watchos-i386: [[METHOD:%.*]] = objc_method [[SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Boo
// CHECK-watchos-i386: [[BOOL:%.*]] = apply [[METHOD]]([[SELF]]) : $@convention(objc_method) (Foo) -> Bool
// CHECK-watchos-i386: return [[BOOL]] : $Bool
// CHECK-watchos-i386: }
// CHECK-macosx-x86_64-LABEL: sil hidden @$s13objc_bridging6getZim{{.*}}F
// CHECK-macosx-x86_64: bb0([[SELF:%.*]] : @guaranteed $Foo):
// CHECK-macosx-x86_64: [[METHOD:%.*]] = objc_method [[SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Bool
// CHECK-macosx-x86_64: [[OBJC_BOOL:%.*]] = apply [[METHOD]]([[SELF]]) : $@convention(objc_method) (Foo) -> ObjCBool
// CHECK-macosx-x86_64: [[CONVERT:%.*]] = function_ref @swift_ObjCBoolToBool : $@convention(thin) (ObjCBool) -> Bool
// CHECK-macosx-x86_64: [[SWIFT_BOOL:%.*]] = apply [[CONVERT]]([[OBJC_BOOL]]) : $@convention(thin) (ObjCBool) -> Bool
// CHECK-macosx-x86_64: return [[SWIFT_BOOL]] : $Bool
// CHECK-macosx-x86_64: }
// CHECK-ios-x86_64-LABEL: sil hidden @$s13objc_bridging6getZim{{.*}}F
// CHECK-ios-x86_64: bb0([[SELF:%.*]] : @guaranteed $Foo):
// CHECK-ios-x86_64: [[METHOD:%.*]] = objc_method [[SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Boo
// CHECK-ios-x86_64: [[BOOL:%.*]] = apply [[METHOD]]([[SELF]]) : $@convention(objc_method) (Foo) -> Bool
// CHECK-ios-x86_64: return [[BOOL]] : $Bool
// CHECK-ios-x86_64: }
// CHECK-arm64-LABEL: sil hidden @$s13objc_bridging6getZim{{.*}}F
// CHECK-arm64: bb0([[SELF:%.*]] : @guaranteed $Foo):
// CHECK-arm64: [[METHOD:%.*]] = objc_method [[SELF]] : $Foo, #Foo.zim!1.foreign : (Foo) -> () -> Boo
// CHECK-arm64: [[BOOL:%.*]] = apply [[METHOD]]([[SELF]]) : $@convention(objc_method) (Foo) -> Bool
// CHECK-arm64: return [[BOOL]] : $Bool
// CHECK-arm64: }
// @interface Foo -(void) setZim: (BOOL)b; @end
func setZim(_ f: Foo, b: Bool) {
f.setZim(b)
}
// CHECK-ios-i386-LABEL: sil hidden @$s13objc_bridging6setZim{{.*}}F
// CHECK-ios-i386: bb0([[ARG0:%.*]] : @guaranteed $Foo, [[ARG1:%.*]] : @trivial $Bool):
// CHECK-ios-i386: [[CONVERT:%.*]] = function_ref @swift_BoolToObjCBool : $@convention(thin) (Bool) -> ObjCBool
// CHECK-ios-i386: [[OBJC_BOOL:%.*]] = apply [[CONVERT]]([[ARG1]]) : $@convention(thin) (Bool) -> ObjCBool
// CHECK-ios-i386: [[METHOD:%.*]] = objc_method [[ARG0]] : $Foo, #Foo.setZim!1.foreign
// CHECK-ios-i386: apply [[METHOD]]([[OBJC_BOOL]], [[ARG0]]) : $@convention(objc_method) (ObjCBool, Foo) -> ()
// CHECK-ios-i386-NOT: destroy_value [[ARG0]]
// CHECK-ios-i386: }
// CHECK-macosx-x86_64-LABEL: sil hidden @$s13objc_bridging6setZim{{.*}}F
// CHECK-macosx-x86_64: bb0([[ARG0:%.*]] : @guaranteed $Foo, [[ARG1:%.*]] : @trivial $Bool):
// CHECK-macosx-x86_64: [[CONVERT:%.*]] = function_ref @swift_BoolToObjCBool : $@convention(thin) (Bool) -> ObjCBool
// CHECK-macosx-x86_64: [[OBJC_BOOL:%.*]] = apply [[CONVERT]]([[ARG1]]) : $@convention(thin) (Bool) -> ObjCBool
// CHECK-macosx-x86_64: [[METHOD:%.*]] = objc_method [[ARG0]] : $Foo, #Foo.setZim!1.foreign
// CHECK-macosx-x86_64: apply [[METHOD]]([[OBJC_BOOL]], [[ARG0]]) : $@convention(objc_method) (ObjCBool, Foo) -> ()
// CHECK-macosx-x86_64-NOT: destroy_value [[ARG0]]
// CHECK-macosx-x86_64: }
// CHECK-ios-x86_64-LABEL: sil hidden @$s13objc_bridging6setZim{{.*}}F
// CHECK-ios-x86_64: bb0([[ARG0:%.*]] : @guaranteed $Foo, [[ARG1:%.*]] : @trivial $Bool):
// CHECK-ios-x86_64: [[METHOD:%.*]] = objc_method [[ARG0]] : $Foo, #Foo.setZim!1.foreign
// CHECK-ios-x86_64: apply [[METHOD]]([[ARG1]], [[ARG0]]) : $@convention(objc_method) (Bool, Foo) -> ()
// CHECK-ios-x86_64-NOT: destroy_value [[ARG0]]
// CHECK-ios-x86_64: }
// CHECK-arm64-LABEL: sil hidden @$s13objc_bridging6setZim{{.*}}F
// CHECK-arm64: bb0([[ARG0:%.*]] : @guaranteed $Foo, [[ARG1:%.*]] : @trivial $Bool):
// CHECK-arm64: [[METHOD:%.*]] = objc_method [[ARG0]] : $Foo, #Foo.setZim!1.foreign
// CHECK-arm64: apply [[METHOD]]([[ARG1]], [[ARG0]]) : $@convention(objc_method) (Bool, Foo) -> ()
// CHECK-arm64-NOT: destroy_value [[ARG0]]
// CHECK-arm64: }
// CHECK-watchos-i386-LABEL: sil hidden @$s13objc_bridging6setZim{{.*}}F
// CHECK-watchos-i386: bb0([[ARG0:%.*]] : @guaranteed $Foo, [[ARG1:%.*]] : @trivial $Bool):
// CHECK-watchos-i386: [[METHOD:%.*]] = objc_method [[ARG0]] : $Foo, #Foo.setZim!1.foreign
// CHECK-watchos-i386: apply [[METHOD]]([[ARG1]], [[ARG0]]) : $@convention(objc_method) (Bool, Foo) -> ()
// CHECK-watchos-i386-NOT: destroy_value [[ARG0]]
// CHECK-watchos-i386: }
// @interface Foo -(_Bool) zang; @end
func getZang(_ f: Foo) -> Bool {
return f.zang()
}
// CHECK-LABEL: sil hidden @$s13objc_bridging7getZangySbSo3FooCF
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Foo)
// CHECK: [[METHOD:%.*]] = objc_method [[ARG]] : $Foo, #Foo.zang!1.foreign
// CHECK: [[BOOL:%.*]] = apply [[METHOD]]([[ARG]]) : $@convention(objc_method) (Foo) -> Bool
// CHECK-NOT: destroy_value [[ARG]]
// CHECK: return [[BOOL]]
// @interface Foo -(void) setZang: (_Bool)b; @end
func setZang(_ f: Foo, _ b: Bool) {
f.setZang(b)
}
// CHECK-LABEL: sil hidden @$s13objc_bridging7setZangyySo3FooC_SbtF
// CHECK: bb0([[ARG0:%.*]] : @guaranteed $Foo, [[ARG1:%.*]] : @trivial $Bool):
// CHECK: [[METHOD:%.*]] = objc_method [[ARG0]] : $Foo, #Foo.setZang!1.foreign
// CHECK: apply [[METHOD]]([[ARG1]], [[ARG0]]) : $@convention(objc_method) (Bool, Foo) -> ()
// CHECK-NOT: destroy_value [[ARG0]]
// CHECK: } // end sil function '$s13objc_bridging7setZangyySo3FooC_SbtF'
// NSString *bar(void);
func callBar() -> String {
return bar()
}
// CHECK-LABEL: sil hidden @$s13objc_bridging7callBar{{.*}}F
// CHECK: bb0:
// CHECK: [[BAR:%.*]] = function_ref @bar
// CHECK: [[OPT_BRIDGED:%.*]] = apply [[BAR]]() : $@convention(c) () -> @autoreleased Optional<NSString>
// CHECK: switch_enum [[OPT_BRIDGED]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_BB]]([[BRIDGED:%.*]] : @owned $NSString):
// CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @$sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
// CHECK: [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]]
// CHECK: [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]]
// CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]]
// CHECK: bb5([[NATIVE:%.*]] : @owned $String):
// CHECK: return [[NATIVE]]
// CHECK: }
// void setBar(NSString *s);
func callSetBar(_ s: String) {
var s = s
setBar(s)
}
// CHECK-LABEL: sil hidden @$s13objc_bridging10callSetBar{{.*}}F
// CHECK: bb0({{%.*}} : @guaranteed $String):
// CHECK: [[NATIVE:%.*]] = load
// CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @$sSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BORROWED_NATIVE:%.*]] = begin_borrow [[NATIVE]]
// CHECK: [[BRIDGED:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_NATIVE]])
// CHECK: [[OPT_BRIDGED:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]]
// CHECK: end_borrow [[BORROWED_NATIVE]]
// CHECK: [[SET_BAR:%.*]] = function_ref @setBar
// CHECK: apply [[SET_BAR]]([[OPT_BRIDGED]])
// CHECK: destroy_value [[OPT_BRIDGED]]
// CHECK: }
var NSS: NSString
// -- NSString methods don't convert 'self'
extension NSString {
@objc var nsstrFakeProp: NSString {
get { return NSS }
set {}
}
// CHECK-LABEL: sil hidden [thunk] @$sSo8NSStringC13objc_bridgingE13nsstrFakePropABvgTo
// CHECK-NOT: swift_StringToNSString
// CHECK-NOT: $sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
// CHECK: }
// CHECK-LABEL: sil hidden [thunk] @$sSo8NSStringC13objc_bridgingE13nsstrFakePropABvsTo
// CHECK-NOT: swift_StringToNSString
// CHECK-NOT: $sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
// CHECK: }
@objc func nsstrResult() -> NSString { return NSS }
// CHECK-LABEL: sil hidden [thunk] @$sSo8NSStringC13objc_bridgingE11nsstrResultAByFTo
// CHECK-NOT: swift_StringToNSString
// CHECK-NOT: $sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
// CHECK: }
@objc func nsstrArg(_ s: NSString) { }
// CHECK-LABEL: sil hidden [thunk] @$sSo8NSStringC13objc_bridgingE8nsstrArgyyABFTo
// CHECK-NOT: swift_StringToNSString
// CHECK-NOT: $sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
// CHECK: }
}
class Bas : NSObject {
// -- Bridging thunks for String properties convert between NSString
@objc var strRealProp: String = "Hello"
// CHECK-LABEL: sil hidden [thunk] @$s13objc_bridging3BasC11strRealPropSSvgTo : $@convention(objc_method) (Bas) -> @autoreleased NSString {
// CHECK: bb0([[THIS:%.*]] : @unowned $Bas):
// CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] : $Bas
// CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK: // function_ref objc_bridging.Bas.strRealProp.getter
// CHECK: [[PROPIMPL:%.*]] = function_ref @$s13objc_bridging3BasC11strRealPropSSvg
// CHECK: [[PROP_COPY:%.*]] = apply [[PROPIMPL]]([[BORROWED_THIS_COPY]]) : $@convention(method) (@guaranteed Bas) -> @owned String
// CHECK: end_borrow [[BORROWED_THIS_COPY]]
// CHECK: destroy_value [[THIS_COPY]]
// CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @$sSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BORROWED_PROP_COPY:%.*]] = begin_borrow [[PROP_COPY]]
// CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_PROP_COPY]])
// CHECK: end_borrow [[BORROWED_PROP_COPY]]
// CHECK: destroy_value [[PROP_COPY]]
// CHECK: return [[NSSTR]]
// CHECK: }
// CHECK-LABEL: sil hidden @$s13objc_bridging3BasC11strRealPropSSvg
// CHECK: [[PROP_ADDR:%.*]] = ref_element_addr %0 : {{.*}}, #Bas.strRealProp
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[PROP_ADDR]] : $*String
// CHECK: [[PROP:%.*]] = load [copy] [[READ]]
// CHECK-LABEL: sil hidden [thunk] @$s13objc_bridging3BasC11strRealPropSSvsTo : $@convention(objc_method) (NSString, Bas) -> () {
// CHECK: bb0([[VALUE:%.*]] : @unowned $NSString, [[THIS:%.*]] : @unowned $Bas):
// CHECK: [[VALUE_COPY:%.*]] = copy_value [[VALUE]]
// CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @$sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
// CHECK: [[VALUE_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[VALUE_COPY]]
// CHECK: [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[VALUE_BOX]]
// CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK: [[SETIMPL:%.*]] = function_ref @$s13objc_bridging3BasC11strRealPropSSvs
// CHECK: apply [[SETIMPL]]([[STR]], [[BORROWED_THIS_COPY]])
// CHECK: end_borrow [[BORROWED_THIS_COPY]]
// CHECK: destroy_value [[THIS_COPY]]
// CHECK: } // end sil function '$s13objc_bridging3BasC11strRealPropSSvsTo'
// CHECK-LABEL: sil hidden @$s13objc_bridging3BasC11strRealPropSSvs
// CHECK: bb0(%0 : @owned $String, %1 : @guaranteed $Bas):
// CHECK: [[STR_ADDR:%.*]] = ref_element_addr %1 : {{.*}}, #Bas.strRealProp
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[STR_ADDR]] : $*String
// CHECK: assign {{.*}} to [[WRITE]]
// CHECK: }
@objc var strFakeProp: String {
get { return "" }
set {}
}
// CHECK-LABEL: sil hidden [thunk] @$s13objc_bridging3BasC11strFakePropSSvgTo : $@convention(objc_method) (Bas) -> @autoreleased NSString {
// CHECK: bb0([[THIS:%.*]] : @unowned $Bas):
// CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK: [[GETTER:%.*]] = function_ref @$s13objc_bridging3BasC11strFakePropSSvg
// CHECK: [[STR:%.*]] = apply [[GETTER]]([[BORROWED_THIS_COPY]])
// CHECK: end_borrow [[BORROWED_THIS_COPY]]
// CHECK: destroy_value [[THIS_COPY]]
// CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @$sSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BORROWED_STR:%.*]] = begin_borrow [[STR]]
// CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_STR]])
// CHECK: end_borrow [[BORROWED_STR]]
// CHECK: destroy_value [[STR]]
// CHECK: return [[NSSTR]]
// CHECK: }
// CHECK-LABEL: sil hidden [thunk] @$s13objc_bridging3BasC11strFakePropSSvsTo : $@convention(objc_method) (NSString, Bas) -> () {
// CHECK: bb0([[NSSTR:%.*]] : @unowned $NSString, [[THIS:%.*]] : @unowned $Bas):
// CHECK: [[NSSTR_COPY:%.*]] = copy_value [[NSSTR]]
// CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @$sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
// CHECK: [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR_COPY]]
// CHECK: [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[NSSTR_BOX]]
// CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK: [[SETTER:%.*]] = function_ref @$s13objc_bridging3BasC11strFakePropSSvs
// CHECK: apply [[SETTER]]([[STR]], [[BORROWED_THIS_COPY]])
// CHECK: end_borrow [[BORROWED_THIS_COPY]]
// CHECK: destroy_value [[THIS_COPY]]
// CHECK: } // end sil function '$s13objc_bridging3BasC11strFakePropSSvsTo'
// -- Bridging thunks for explicitly NSString properties don't convert
@objc var nsstrRealProp: NSString
@objc var nsstrFakeProp: NSString {
get { return NSS }
set {}
}
// CHECK-LABEL: sil hidden [thunk] @$s13objc_bridging3BasC13nsstrRealPropSo8NSStringCvgTo : $@convention(objc_method) (Bas) -> @autoreleased NSString {
// CHECK-NOT: swift_StringToNSString
// CHECK-NOT: $sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
// CHECK: }
// CHECK-LABEL: sil hidden [thunk] @$s13objc_bridging3BasC13nsstrRealPropSo8NSStringCvsTo : $@convention(objc_method) (NSString, Bas) ->
// CHECK-NOT: swift_StringToNSString
// CHECK-NOT: $sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
// CHECK: }
// -- Bridging thunks for String methods convert between NSString
@objc func strResult() -> String { return "" }
// CHECK-LABEL: sil hidden [thunk] @$s13objc_bridging3BasC9strResultSSyFTo
// CHECK: bb0([[THIS:%.*]] : @unowned $Bas):
// CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK: [[METHOD:%.*]] = function_ref @$s13objc_bridging3BasC9strResultSSyF
// CHECK: [[STR:%.*]] = apply [[METHOD]]([[BORROWED_THIS_COPY]])
// CHECK: end_borrow [[BORROWED_THIS_COPY]]
// CHECK: destroy_value [[THIS_COPY]]
// CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @$sSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BORROWED_STR:%.*]] = begin_borrow [[STR]]
// CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_STR]])
// CHECK: end_borrow [[BORROWED_STR]]
// CHECK: destroy_value [[STR]]
// CHECK: return [[NSSTR]]
// CHECK: }
@objc func strArg(_ s: String) { }
// CHECK-LABEL: sil hidden [thunk] @$s13objc_bridging3BasC6strArgyySSFTo
// CHECK: bb0([[NSSTR:%.*]] : @unowned $NSString, [[THIS:%.*]] : @unowned $Bas):
// CHECK: [[NSSTR_COPY:%.*]] = copy_value [[NSSTR]]
// CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]]
// CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @$sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
// CHECK: [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR_COPY]]
// CHECK: [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[NSSTR_BOX]]
// CHECK: [[BORROWED_STR:%.*]] = begin_borrow [[STR]]
// CHECK: [[BORROWED_THIS_COPY:%.*]] = begin_borrow [[THIS_COPY]]
// CHECK: [[METHOD:%.*]] = function_ref @$s13objc_bridging3BasC6strArgyySSF
// CHECK: apply [[METHOD]]([[BORROWED_STR]], [[BORROWED_THIS_COPY]])
// CHECK: end_borrow [[BORROWED_THIS_COPY]]
// CHECK: destroy_value [[THIS_COPY]]
// CHECK: } // end sil function '$s13objc_bridging3BasC6strArgyySSFTo'
// -- Bridging thunks for explicitly NSString properties don't convert
@objc func nsstrResult() -> NSString { return NSS }
// CHECK-LABEL: sil hidden [thunk] @$s13objc_bridging3BasC11nsstrResultSo8NSStringCyFTo
// CHECK-NOT: swift_StringToNSString
// CHECK-NOT: $sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
// CHECK: }
@objc func nsstrArg(_ s: NSString) { }
// CHECK-LABEL: sil hidden @$s13objc_bridging3BasC8nsstrArgyySo8NSStringCF
// CHECK-NOT: swift_StringToNSString
// CHECK-NOT: $sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
// CHECK: }
@objc init(str: NSString) {
nsstrRealProp = str
super.init()
}
// CHECK-LABEL: sil hidden [thunk] @$s13objc_bridging3BasC8arrayArgyySayyXlGFTo : $@convention(objc_method) (NSArray, Bas) -> ()
// CHECK: bb0([[NSARRAY:%[0-9]+]] : @unowned $NSArray, [[SELF:%[0-9]+]] : @unowned $Bas):
// CHECK: [[NSARRAY_COPY:%.*]] = copy_value [[NSARRAY]] : $NSArray
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Bas
// CHECK: [[CONV_FN:%[0-9]+]] = function_ref @$sSa10FoundationE36_unconditionallyBridgeFromObjectiveCySayxGSo7NSArrayCSgFZ
// CHECK: [[OPT_NSARRAY:%[0-9]+]] = enum $Optional<NSArray>, #Optional.some!enumelt.1, [[NSARRAY_COPY]] : $NSArray
// CHECK: [[ARRAY_META:%[0-9]+]] = metatype $@thin Array<AnyObject>.Type
// CHECK: [[ARRAY:%[0-9]+]] = apply [[CONV_FN]]<AnyObject>([[OPT_NSARRAY]], [[ARRAY_META]])
// CHECK: [[BORROWED_ARRAY:%.*]] = begin_borrow [[ARRAY]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @$s13objc_bridging3BasC8arrayArgyySayyXlGF : $@convention(method) (@guaranteed Array<AnyObject>, @guaranteed Bas) -> ()
// CHECK: [[RESULT:%[0-9]+]] = apply [[SWIFT_FN]]([[BORROWED_ARRAY]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@guaranteed Array<AnyObject>, @guaranteed Bas) -> ()
// CHECK: end_borrow [[BORROWED_SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]] : $Bas
// CHECK: return [[RESULT]] : $()
@objc func arrayArg(_ array: [AnyObject]) { }
// CHECK-LABEL: sil hidden [thunk] @$s13objc_bridging3BasC11arrayResultSayyXlGyFTo : $@convention(objc_method) (Bas) -> @autoreleased NSArray
// CHECK: bb0([[SELF:%[0-9]+]] : @unowned $Bas):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Bas
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @$s13objc_bridging3BasC11arrayResultSayyXlGyF : $@convention(method) (@guaranteed Bas) -> @owned Array<AnyObject>
// CHECK: [[ARRAY:%[0-9]+]] = apply [[SWIFT_FN]]([[BORROWED_SELF_COPY]]) : $@convention(method) (@guaranteed Bas) -> @owned Array<AnyObject>
// CHECK: end_borrow [[BORROWED_SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[CONV_FN:%[0-9]+]] = function_ref @$sSa10FoundationE19_bridgeToObjectiveCSo7NSArrayCyF
// CHECK: [[BORROWED_ARRAY:%.*]] = begin_borrow [[ARRAY]]
// CHECK: [[NSARRAY:%[0-9]+]] = apply [[CONV_FN]]<AnyObject>([[BORROWED_ARRAY]]) : $@convention(method) <τ_0_0> (@guaranteed Array<τ_0_0>) -> @owned NSArray
// CHECK: end_borrow [[BORROWED_ARRAY]]
// CHECK: destroy_value [[ARRAY]]
// CHECK: return [[NSARRAY]]
@objc func arrayResult() -> [AnyObject] { return [] }
// CHECK-LABEL: sil hidden [thunk] @$s13objc_bridging3BasC9arrayPropSaySSGvgTo : $@convention(objc_method) (Bas) -> @autoreleased NSArray
// CHECK-LABEL: sil hidden [thunk] @$s13objc_bridging3BasC9arrayPropSaySSGvsTo : $@convention(objc_method) (NSArray, Bas) -> ()
@objc var arrayProp: [String] = []
}
// CHECK-LABEL: sil hidden @$s13objc_bridging16applyStringBlock_1xS3SXB_SStF
func applyStringBlock(_ f: @convention(block) (String) -> String, x: String) -> String {
// CHECK: bb0([[BLOCK:%.*]] : @guaranteed $@convention(block) @noescape (NSString) -> @autoreleased NSString, [[STRING:%.*]] : @guaranteed $String):
// CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]]
// CHECK: [[BORROWED_BLOCK_COPY:%.*]] = begin_borrow [[BLOCK_COPY]]
// CHECK: [[BLOCK_COPY_COPY:%.*]] = copy_value [[BORROWED_BLOCK_COPY]]
// CHECK: [[STRING_COPY:%.*]] = copy_value [[STRING]]
// CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @$sSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BORROWED_STRING_COPY:%.*]] = begin_borrow [[STRING_COPY]]
// CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_STRING_COPY]]) : $@convention(method) (@guaranteed String)
// CHECK: end_borrow [[BORROWED_STRING_COPY]]
// CHECK: destroy_value [[STRING_COPY]]
// CHECK: [[RESULT_NSSTR:%.*]] = apply [[BLOCK_COPY_COPY]]([[NSSTR]]) : $@convention(block) @noescape (NSString) -> @autoreleased NSString
// CHECK: destroy_value [[NSSTR]]
// CHECK: [[FINAL_BRIDGE:%.*]] = function_ref @$sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ
// CHECK: [[OPTIONAL_NSSTR:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[RESULT_NSSTR]]
// CHECK: [[RESULT:%.*]] = apply [[FINAL_BRIDGE]]([[OPTIONAL_NSSTR]], {{.*}}) : $@convention(method) (@guaranteed Optional<NSString>, @thin String.Type) -> @owned String
// CHECK: destroy_value [[BLOCK_COPY_COPY]]
// CHECK-NOT: destroy_value [[STRING]]
// CHECK: destroy_value [[BLOCK_COPY]]
// CHECK-NOT: destroy_value [[BLOCK]]
// CHECK: return [[RESULT]] : $String
return f(x)
}
// CHECK: } // end sil function '$s13objc_bridging16applyStringBlock_1xS3SXB_SStF'
// CHECK-LABEL: sil hidden @$s13objc_bridging15bridgeCFunction{{.*}}F
func bridgeCFunction() -> (String?) -> (String?) {
// CHECK: [[THUNK:%.*]] = function_ref @$sSo18NSStringFromStringySSSgABFTO : $@convention(thin) (@guaranteed Optional<String>) -> @owned Optional<String>
// CHECK: [[THICK:%.*]] = thin_to_thick_function [[THUNK]]
// CHECK: return [[THICK]]
return NSStringFromString
}
func forceNSArrayMembers() -> (NSArray, NSArray) {
let x = NSArray(objects: nil, count: 0)
return (x, x)
}
// Check that the allocating initializer shim for initializers that take pointer
// arguments lifetime-extends the bridged pointer for the right duration.
// <rdar://problem/16738050>
// CHECK-LABEL: sil shared [serializable] @$sSo7NSArrayC7objects5countABSPyyXlSgGSg_s5Int32VtcfC
// CHECK: [[SELF:%.*]] = alloc_ref_dynamic
// CHECK: [[METHOD:%.*]] = function_ref @$sSo7NSArrayC7objects5countABSPyyXlSgGSg_s5Int32VtcfcTO
// CHECK: [[RESULT:%.*]] = apply [[METHOD]]
// CHECK: return [[RESULT]]
// Check that type lowering preserves the bool/BOOL distinction when bridging
// imported C functions.
// CHECK-ios-i386-LABEL: sil hidden @$s13objc_bridging5boolsySb_SbtSbF
// CHECK-ios-i386: function_ref @useBOOL : $@convention(c) (ObjCBool) -> ()
// CHECK-ios-i386: function_ref @useBool : $@convention(c) (Bool) -> ()
// CHECK-ios-i386: function_ref @getBOOL : $@convention(c) () -> ObjCBool
// CHECK-ios-i386: function_ref @getBool : $@convention(c) () -> Bool
// CHECK-macosx-x86_64-LABEL: sil hidden @$s13objc_bridging5boolsySb_SbtSbF
// CHECK-macosx-x86_64: function_ref @useBOOL : $@convention(c) (ObjCBool) -> ()
// CHECK-macosx-x86_64: function_ref @useBool : $@convention(c) (Bool) -> ()
// CHECK-macosx-x86_64: function_ref @getBOOL : $@convention(c) () -> ObjCBool
// CHECK-macosx-x86_64: function_ref @getBool : $@convention(c) () -> Bool
// FIXME: no distinction on x86_64, arm64 or watchos-i386, since SILGen looks
// at the underlying Clang decl of the bridged decl to decide whether it needs
// bridging.
//
// CHECK-watchos-i386-LABEL: sil hidden @$s13objc_bridging5boolsySb_SbtSbF
// CHECK-watchos-i386: function_ref @useBOOL : $@convention(c) (Bool) -> ()
// CHECK-watchos-i386: function_ref @useBool : $@convention(c) (Bool) -> ()
// CHECK-watchos-i386: function_ref @getBOOL : $@convention(c) () -> Bool
// CHECK-watchos-i386: function_ref @getBool : $@convention(c) () -> Bool
// CHECK-ios-x86_64-LABEL: sil hidden @$s13objc_bridging5boolsySb_SbtSbF
// CHECK-ios-x86_64: function_ref @useBOOL : $@convention(c) (Bool) -> ()
// CHECK-ios-x86_64: function_ref @useBool : $@convention(c) (Bool) -> ()
// CHECK-ios-x86_64: function_ref @getBOOL : $@convention(c) () -> Bool
// CHECK-ios-x86_64: function_ref @getBool : $@convention(c) () -> Bool
// CHECK-arm64-LABEL: sil hidden @$s13objc_bridging5boolsySb_SbtSbF
// CHECK-arm64: function_ref @useBOOL : $@convention(c) (Bool) -> ()
// CHECK-arm64: function_ref @useBool : $@convention(c) (Bool) -> ()
// CHECK-arm64: function_ref @getBOOL : $@convention(c) () -> Bool
// CHECK-arm64: function_ref @getBool : $@convention(c) () -> Bool
func bools(_ x: Bool) -> (Bool, Bool) {
useBOOL(x)
useBool(x)
return (getBOOL(), getBool())
}
// CHECK-LABEL: sil hidden @$s13objc_bridging9getFridge{{.*}}F
// CHECK: bb0([[HOME:%[0-9]+]] : @guaranteed $APPHouse):
func getFridge(_ home: APPHouse) -> Refrigerator {
// CHECK: [[GETTER:%[0-9]+]] = objc_method [[HOME]] : $APPHouse, #APPHouse.fridge!getter.1.foreign
// CHECK: [[OBJC_RESULT:%[0-9]+]] = apply [[GETTER]]([[HOME]])
// CHECK: [[BRIDGE_FN:%[0-9]+]] = function_ref @$s10Appliances12RefrigeratorV36_unconditionallyBridgeFromObjectiveCyACSo15APPRefrigeratorCSgFZ
// CHECK: [[REFRIGERATOR_META:%[0-9]+]] = metatype $@thin Refrigerator.Type
// CHECK: [[RESULT:%[0-9]+]] = apply [[BRIDGE_FN]]([[OBJC_RESULT]], [[REFRIGERATOR_META]])
// CHECK-NOT: destroy_value [[HOME]] : $APPHouse
// CHECK: return [[RESULT]] : $Refrigerator
return home.fridge
}
// CHECK-LABEL: sil hidden @$s13objc_bridging16updateFridgeTemp{{.*}}F
// CHECK: bb0([[HOME:%[0-9]+]] : @guaranteed $APPHouse, [[DELTA:%[0-9]+]] : @trivial $Double):
func updateFridgeTemp(_ home: APPHouse, delta: Double) {
// Temporary fridge
// CHECK: [[TEMP_FRIDGE:%[0-9]+]] = alloc_stack $Refrigerator
// Get operation
// CHECK-NEXT: [[GETTER:%[0-9]+]] = objc_method [[HOME]] : $APPHouse, #APPHouse.fridge!getter.1.foreign
// CHECK-NEXT: [[OBJC_FRIDGE:%[0-9]+]] = apply [[GETTER]]([[HOME]])
// CHECK: [[BRIDGE_FROM_FN:%[0-9]+]] = function_ref @$s10Appliances12RefrigeratorV36_unconditionallyBridgeFromObjectiveCyACSo15APPRefrigeratorCSgFZ
// CHECK-NEXT: [[REFRIGERATOR_META:%[0-9]+]] = metatype $@thin Refrigerator.Type
// CHECK-NEXT: [[FRIDGE:%[0-9]+]] = apply [[BRIDGE_FROM_FN]]([[OBJC_FRIDGE]], [[REFRIGERATOR_META]])
// CHECK-NEXT: store [[FRIDGE]] to [trivial] [[TEMP_FRIDGE]]
// Addition
// CHECK-NEXT: [[TEMP:%[0-9]+]] = struct_element_addr [[TEMP_FRIDGE]] : $*Refrigerator, #Refrigerator.temperature
// CHECK: [[PLUS_EQ:%[0-9]+]] = function_ref @$sSd2peoiyySdz_SdtFZ
// CHECK-NEXT: apply [[PLUS_EQ]]([[TEMP]], [[DELTA]], [[METATYPE:%[0-9]+]])
// Setter
// CHECK: [[FRIDGE:%[0-9]+]] = load [trivial] [[TEMP_FRIDGE]] : $*Refrigerator
// CHECK: [[BRIDGE_TO_FN:%[0-9]+]] = function_ref @$s10Appliances12RefrigeratorV19_bridgeToObjectiveCSo15APPRefrigeratorCyF
// CHECK-NEXT: [[OBJC_ARG:%[0-9]+]] = apply [[BRIDGE_TO_FN]]([[FRIDGE]])
// CHECK-NEXT: [[SETTER:%[0-9]+]] = objc_method [[HOME]] : $APPHouse, #APPHouse.fridge!setter.1.foreign
// CHECK-NEXT: apply [[SETTER]]([[OBJC_ARG]], [[HOME]]) : $@convention(objc_method) (APPRefrigerator, APPHouse) -> ()
// CHECK-NEXT: destroy_value [[OBJC_ARG]]
// CHECK-NEXT: destroy_value [[OBJC_FRIDGE]]
// CHECK-NEXT: dealloc_stack [[TEMP_FRIDGE]]
home.fridge.temperature += delta
}
// CHECK-LABEL: sil hidden @$s13objc_bridging20callNonStandardBlock5valueySi_tF
func callNonStandardBlock(value: Int) {
// CHECK: enum $Optional<@convention(block) () -> @owned Optional<AnyObject>>
takesNonStandardBlock { return value }
}
func takeTwoAnys(_ lhs: Any, _ rhs: Any) -> Any { return lhs }
// CHECK-LABEL: sil hidden @$s13objc_bridging22defineNonStandardBlock1xyyp_tF
func defineNonStandardBlock(x: Any) {
// CHECK: function_ref @$s13objc_bridging22defineNonStandardBlock1xyyp_tFypypcfU_
// CHECK: function_ref @$sypypIegnr_yXlyXlIeyBya_TR : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed (@in_guaranteed Any) -> @out Any, AnyObject) -> @autoreleased AnyObject
let fn : @convention(block) (Any) -> Any = { y in takeTwoAnys(x, y) }
}
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$sypypIegnr_yXlyXlIeyBya_TR : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed (@in_guaranteed Any) -> @out Any, AnyObject) -> @autoreleased AnyObject
// CHECK: bb0(%0 : @trivial $*@block_storage @callee_guaranteed (@in_guaranteed Any) -> @out Any, %1 : @unowned $AnyObject):
// CHECK: [[T0:%.*]] = copy_value %1 : $AnyObject
// CHECK: [[T1:%.*]] = open_existential_ref [[T0]] : $AnyObject
// CHECK: [[ARG:%.*]] = alloc_stack $Any
// CHECK: [[T2:%.*]] = init_existential_addr [[ARG]]
// CHECK: store [[T1]] to [init] [[T2]]
// CHECK: [[RESULT:%.*]] = alloc_stack $Any
// CHECK: apply {{.*}}([[RESULT]], [[ARG]])
// CHECK-LABEL: sil hidden @$s13objc_bridging15castToCFunction3ptrySV_tF : $@convention(thin) (UnsafeRawPointer) -> () {
func castToCFunction(ptr: UnsafeRawPointer) {
// CHECK: [[OUT:%.*]] = alloc_stack $@convention(c) (Optional<AnyObject>) -> ()
// CHECK: [[IN:%.]] = alloc_stack $UnsafeRawPointer
// CHECK: store %0 to [trivial] [[IN]] : $*UnsafeRawPointer
// CHECK: [[META:%.*]] = metatype $@thick (@convention(c) (Optional<AnyObject>) -> ()).Type
// CHECK: [[CASTFN:%.*]] = function_ref @$ss13unsafeBitCast_2toq_x_q_mtr0_lF
// CHECK: apply [[CASTFN]]<UnsafeRawPointer, @convention(c) (AnyObject?) -> ()>([[OUT]], [[IN]], [[META]]) : $@convention(thin) <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0, @thick τ_0_1.Type) -> @out τ_0_1
// CHECK: [[RESULT:%.*]] = load [trivial] [[OUT]] : $*@convention(c) (Optional<AnyObject>) -> ()
typealias Fn = @convention(c) (AnyObject?) -> Void
unsafeBitCast(ptr, to: Fn.self)(nil)
}
| apache-2.0 | d7515ab75277cfc2122fd29319f2123b | 55.89168 | 286 | 0.636727 | 3.335788 | false | false | false | false |
arbitur/Func | source/UI/ActivityIndicator.swift | 1 | 5730 | //
// ActivityController.swift
// Test
//
// Created by Philip Fryklund on 3/Dec/16.
// Copyright © 2016 Philip Fryklund. All rights reserved.
//
import Foundation
public class ActivityIndicator: UIView {
private static let shared = ActivityIndicator()
static var dismissDelay: Double = 0.25
public static func show() {
// if shared.showTimer == nil {
// shared.showTimer = Timer.scheduledTimer(timeInterval: 0.25, target: shared, selector: #selector(shared.show), userInfo: nil, repeats: false)
// }
if !shared.isShowing {
shared.show()
}
}
public static func dismiss(animated: Bool) {
shared.removeTimer?.invalidate()
shared.removeTimer = Timer.scheduledTimer(timeInterval: 0.25, target: shared, selector: #selector(shared.remove(timer:)), userInfo: animated, repeats: false)
}
private let contentView = UIView(backgroundColor: UIColor.black.alpha(0.2))
private let contentStack = StackView(axis: .vertical)
private let spinner = Spinner(numberOfLines: 1, minSpeed: CGFloat(0.75).rad, maxSpeed: CGFloat(4.25).rad)
// private let spinner = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
// private var showTimer: Timer?
private var removeTimer: Timer?
private var isShowing = false
private func show() {
isShowing = true
UIWindow.current?.addSubview(self)
self.alpha = 0
contentView.transform(scale: 1.2)
self.layoutIfNeeded()
UIView.animate(withDuration: 0.4) {
self.alpha = 1
self.contentView.transform(scale: 1.0)
}
}
@objc private func remove(timer: Timer) {
let animated = timer.userInfo as! Bool
timer.invalidate()
removeTimer = nil
if animated {
UIView.animate(withDuration: 0.2,
animations: {
self.alpha = 0
},
completion: { _ in
self.isShowing = false
self.removeFromSuperview()
})
}
else {
self.isShowing = false
self.removeFromSuperview()
}
}
public override func willMove(toSuperview newSuperview: UIView?) {
if newSuperview != nil {
spinner.startAnimating()
}
}
public override func didMoveToSuperview() {
if self.superview == nil {
spinner.stopAnimating()
}
}
init() {
super.init(frame: UIScreen.main.bounds)
self.backgroundColor = UIColor.black.alpha(0.2)
contentView.cornerRadius = 30
self.addSubview(contentView)
contentView.lac.make {
$0.centerX.equalToSuperview()
$0.centerY.equalToSuperview()
$0.width.equalTo(200)
$0.height.greaterThan(contentView.lac.width)
}
contentStack.spacing = 20
contentStack.isLayoutMarginsRelativeArrangement = true
contentStack.layoutMargins = UIEdgeInsets(inset: 40)
contentView.addSubview(contentStack)
contentStack.lac.make {
$0.top.equalToSuperview()
$0.left.equalToSuperview()
$0.right.equalToSuperview()
$0.bottom.equalToSuperview()
}
// spinner.backgroundColor = .red
spinner.lac.make {
$0.height.equalTo($0.width)
}
contentStack.addArrangedSubview(spinner)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private class Spinner: UIView {
let numberOfLines: Int
let spacing: CGFloat = 0
let innerRadius: CGFloat = 45
private let paths: [Path]
var timer: Timer!
var isAnimating = false
@objc func update() {
self.setNeedsDisplay()
}
func startAnimating() {
print("Spinner.startAnimating")
timer = Timer.scheduledTimer(timeInterval: 1.0/60.0, target: self, selector: #selector(update), userInfo: nil, repeats: true)
isAnimating = true
for (i, path) in paths.enumerated() {
path.angle = -CGFloat.pi / 2 + CGFloat(i) * CGFloat(45).rad
path.length = CGFloat.pi / 2
}
}
func stopAnimating() {
print("Spinner.stopAnimating")
timer?.invalidate()
timer = nil
isAnimating = false
}
init(numberOfLines lines: Int, minSpeed: CGFloat, maxSpeed: CGFloat) {
self.numberOfLines = lines
let speedRange = maxSpeed - minSpeed
paths = (0..<lines).map { i in
let percent = CGFloat(i + 1) / CGFloat(lines)
let path = Path()
// path.angle = -CGFloat.pi / 2
path.speed = minSpeed + speedRange * percent
// path.length = CGFloat.pi / 2
path.color = UIColor(hex: 0x2DBDB6).lightened(by: percent * 0.25 + 0.065)
return path
}
super.init(frame: CGRect.zero)
self.isOpaque = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate override func draw(_ rect: CGRect) {
UIColor.white.alpha(0.2).setFill()
UIBezierPath(ovalIn: rect).fill()
let totalRadius = rect.width/2
let availableRadius = totalRadius - innerRadius - CGFloat(numberOfLines-1) * spacing
let center = rect.center
let lineWidth = availableRadius / CGFloat(numberOfLines)
let x = paths.first!.angle
// let curve = cos(x * 0.3) * 0.4 + 0.6
let curve = (1 - abs(cos(x * 0.5))) * 0.95 + 0.05
let length = CGFloat.pi * 2 * curve
// print(curve)
for (i, path) in paths.enumerated() {
let percent = CGFloat(i + 1) / CGFloat(numberOfLines)
let radius = availableRadius * percent - lineWidth / 2 + spacing * CGFloat(i) + innerRadius
path.length = length
let sa = path.angle - path.length / 2
let ea = path.angle + path.length / 2
path.angle += path.speed
path.lineWidth = lineWidth
path.removeAllPoints()
path.addArc(withCenter: center, radius: radius, startAngle: sa, endAngle: ea, clockwise: true)
path.color.setStroke()
path.stroke()
}
}
private class Path: UIBezierPath {
var angle: CGFloat = 0
var speed: CGFloat = 0
var length: CGFloat = 0
var color: UIColor = .black
}
}
| mit | be316c3edc91bc966f540e4a87e6c6e7 | 19.460714 | 159 | 0.676034 | 3.461631 | false | false | false | false |
prolificinteractive/simcoe | Simcoe/mParticle/mParticle.swift | 1 | 12912 | //
// mParticleAnalyticsHandler.swift
// Simcoe
//
// Created by Christopher Jones on 2/16/16.
// Copyright © 2016 Prolific Interactive. All rights reserved.
//
import mParticle_Apple_SDK
/// Simcoe Analytics handler for the MParticle iOS SDK.
public class mParticle {
fileprivate static let unknownErrorMessage = "An unknown error occurred."
fileprivate var currentUser: MParticleUser? {
return MParticle.sharedInstance().identity.currentUser
}
/// The name of the tracker.
public let name = "mParticle"
/// Initializes and starts the SDK with the input options.
///
/// - Parameter options: The mParticle SDK options.
public init(options: MParticleOptions) {
MParticle.sharedInstance().start(with: options)
}
/// Starts the mParticle SDK with the api_key and api_secret saved in MParticleConfig.plist.
/// - warning: This may throw an error if the MPartcileConfig.plist file is not found in the main bundle.
public init() {
MParticle.sharedInstance().start()
}
}
// MARK: - CartLogging
extension mParticle: CartLogging {
/// Logs the addition of a product to the cart.
///
/// - Parameters:
/// - product: The SimcoeProductConvertible instance.
/// - eventProperties: The event properties.
/// - Returns: A tracking result.
public func logAddToCart<T: SimcoeProductConvertible>(_ product: T, eventProperties: Properties?) -> TrackingResult {
let mPProduct = MPProduct(product: product)
let event = MPCommerceEvent(eventType: .addToCart,
products: [mPProduct],
eventProperties: eventProperties)
MParticle.sharedInstance().logCommerceEvent(event)
return .success
}
/// Logs the removal of a product from the cart.
///
/// - Parameters:
/// - product: The SimcoeProductConvertible instance.
/// - eventProperties: The event properties.
/// - Returns: A tracking result.
public func logRemoveFromCart<T: SimcoeProductConvertible>(_ product: T, eventProperties: Properties?) -> TrackingResult {
let mPProduct = MPProduct(product: product)
let event = MPCommerceEvent(eventType: .removeFromCart,
products: [mPProduct],
eventProperties: eventProperties)
MParticle.sharedInstance().logCommerceEvent(event)
return .success
}
}
// MARK: - CheckoutTracking
extension mParticle: CheckoutTracking {
/// Tracks a checkout event.
///
/// - Parameters:
/// - products: The products.
/// - eventProperties: The event properties.
/// - Returns: A tracking result.
public func trackCheckoutEvent<T: SimcoeProductConvertible>(_ products: [T], eventProperties: Properties?) -> TrackingResult {
let mPProducts = products.map { MPProduct(product: $0) }
let event = MPCommerceEvent(eventType: .checkout,
products: mPProducts,
eventProperties: eventProperties)
MParticle.sharedInstance().logCommerceEvent(event)
return .success
}
}
// MARK: - ErrorLogging
extension mParticle: ErrorLogging {
/// Logs an error through mParticle.
///
/// It is recommended that you use the `Simcoe.eventData()` function in order to generate the properties
/// dictionary properly.
///
/// - Parameters:
/// - error: The error to log.
/// - properties: The properties of the event.
/// - Returns: A tracking result.
public func log(error: String, withAdditionalProperties properties: Properties? = nil) -> TrackingResult {
MParticle.sharedInstance().logError(error, eventInfo: properties)
return .success
}
}
// MARK: - EventTracking
extension mParticle: EventTracking {
/// Tracks an mParticle event.
///
/// Internally, this generates an MPEvent object based on the properties passed in. The event string
/// passed as the first parameter is delineated as the .name of the MPEvent. As a caller, you are
/// required to pass in non-nil properties where one of the properties is the MPEventType. Failure
/// to do so will cause this function to fail.
///
/// It is recommended that you use the `Simcoe.eventData()` function in order to generate the properties
/// dictionary properly.
///
/// - Parameters:
/// - event: The event name to log.
/// - properties: The properties of the event.
/// - Returns: A tracking result.
public func track(event: String, withAdditionalProperties properties: Properties?) -> TrackingResult {
guard var properties = properties else {
return .error(message: "Cannot track an event without valid properties.")
}
properties[MPEventKeys.name.rawValue] = event
let event: MPEvent
do {
event = try MPEvent.toEvent(usingData: properties)
} catch let error as MPEventGenerationError {
return .error(message: error.description)
} catch {
return .error(message: mParticle.unknownErrorMessage)
}
MParticle.sharedInstance().logEvent(event)
return .success
}
}
// MARK: - LifetimeValueTracking
extension mParticle: LifetimeValueTracking {
/// Tracks the lifetime value.
///
/// - Parameters:
/// - key: The lifetime value's identifier.
/// - value: The lifetime value.
/// - properties: The optional additional properties.
/// - Returns: A tracking result.
public func trackLifetimeValue(_ key: String, value: Any, withAdditionalProperties properties: Properties?) -> TrackingResult {
guard let value = value as? Double else {
return .error(message: "Value must map to a Double")
}
MParticle.sharedInstance().logLTVIncrease(value, eventName: key, eventInfo: properties)
return .success
}
/// Track the lifetime values.
///
/// - Parameter:
/// - attributes: The lifetime attribute values.
/// - properties: The optional additional properties.
/// - Returns: A tracking result.
public func trackLifetimeValues(_ attributes: Properties, withAdditionalProperties properties: Properties?) -> TrackingResult {
attributes.forEach { (key, value) in
_ = trackLifetimeValue(key, value: value, withAdditionalProperties: properties)
}
return .success
}
}
// MARK: - LocationTracking
extension mParticle: LocationTracking {
/// Tracks the user's location.
///
/// Internally, this generates an MPEvent object based on the properties passed in. As a result, it is
/// required that the properties dictionary not be nil and contains keys for .name and .eventType. The latitude
/// and longitude of the location object passed in will automatically be added to the info dictionary of the MPEvent
/// object; it is recommended not to include them manually unless there are other properties required to use them.
///
/// It is recommended that you use the `Simcoe.eventData()` function in order to generate the properties
/// dictionary properly.
/// - Parameters:
/// - location: The location data being tracked.
/// - properties: The properties for the MPEvent.
/// - Returns: A tracking result.
public func track(location: CLLocation, withAdditionalProperties properties: Properties?) -> TrackingResult {
var eventProperties = properties ?? Properties() // TODO: Handle Error
eventProperties["latitude"] = String(location.coordinate.latitude)
eventProperties["longitude"] = String(location.coordinate.longitude)
let event: MPEvent
do {
event = try MPEvent.toEvent(usingData: eventProperties)
} catch let error as MPEventGenerationError {
return .error(message: error.description)
} catch {
return .error(message: mParticle.unknownErrorMessage)
}
MParticle.sharedInstance().logEvent(event)
return .success
}
}
// MARK: - PageViewTracking
extension mParticle: PageViewTracking {
/// Tracks the page view.
///
/// - Parameters:
/// - pageView: The page view to track.
/// - properties: The optional additional properties.
/// - Returns: A tracking result.
public func track(pageView: String, withAdditionalProperties properties: Properties?) -> TrackingResult {
MParticle.sharedInstance().logScreen(pageView, eventInfo: properties)
return .success
}
}
// MARK: - PurchaseTracking
extension mParticle: PurchaseTracking {
/// Tracks a purchase event.
///
/// - Parameters:
/// - products: The products.
/// - eventProperties: The event properties
/// - Returns: A tracking result.
public func trackPurchaseEvent<T : SimcoeProductConvertible>(_ products: [T], eventProperties: Properties?) -> TrackingResult {
let mPProducts = products.map { MPProduct(product: $0) }
let event = MPCommerceEvent(eventType: .purchase,
products: mPProducts,
eventProperties: eventProperties)
MParticle.sharedInstance().logCommerceEvent(event)
return .success
}
}
// MARK: - TimedEventTracking
extension mParticle: TimedEventTracking {
/// Starts the timed event.
///
/// - Parameters:
/// - event: The event name.
/// - properties: The event properties.
/// - Returns: A tracking result.
public func start(timedEvent event: String, withAdditionalProperties properties: Properties?) -> TrackingResult {
guard var properties = properties else {
return .error(message: "Cannot track a timed event without valid properties.")
}
properties[MPEventKeys.name.rawValue] = event as String
let event: MPEvent
do {
event = try MPEvent.toEvent(usingData: properties)
} catch let error as MPEventGenerationError {
return .error(message: error.description)
} catch {
return .error(message: mParticle.unknownErrorMessage)
}
MParticle.sharedInstance().beginTimedEvent(event)
return .success
}
/// Stops the timed event.
///
/// - Parameters:
/// - event: The event name.
/// - properties: The event properties.
/// - Returns: A tracking result.
public func stop(timedEvent event: String, withAdditionalProperties properties: Properties?) -> TrackingResult {
guard var properties = properties else {
return .error(message: "Cannot track a timed event without valid properties.")
}
properties[MPEventKeys.name.rawValue] = event as String
let event: MPEvent
do {
event = try MPEvent.toEvent(usingData: properties)
} catch let error as MPEventGenerationError {
return .error(message: error.description)
} catch {
return .error(message: mParticle.unknownErrorMessage)
}
MParticle.sharedInstance().endTimedEvent(event)
return .success
}
}
// MARK: - UserAttributeTracking
extension mParticle: UserAttributeTracking {
/// Sets the User Attribute.
///
/// - Parameters:
/// - key: The attribute key to log.
/// - value: The attribute value to log.
/// - Returns: A tracking result.
public func setUserAttribute(_ key: String, value: Any) -> TrackingResult {
currentUser?.setUserAttribute(key, value: value)
return .success
}
/// Sets the User Attributes.
///
/// - Parameter attributes: The attribute values to log.
/// - Returns: A tracking result.
public func setUserAttributes(_ attributes: Properties) -> TrackingResult {
attributes.forEach {
currentUser?.setUserAttribute($0, value: $1)
}
return .success
}
}
// MARK: - ViewDetailLogging
extension mParticle: ViewDetailLogging {
/// Logs the action of viewing a product's details.
///
/// - Parameters:
/// - product: The SimcoeProductConvertible instance.
/// - eventProperties: The event properties.
/// - Returns: A tracking result.
public func logViewDetail<T: SimcoeProductConvertible>(_ product: T, eventProperties: Properties?) -> TrackingResult {
let mPProduct = MPProduct(product: product)
let event = MPCommerceEvent(eventType: .viewDetail,
products: [mPProduct],
eventProperties: eventProperties)
MParticle.sharedInstance().logCommerceEvent(event)
return .success
}
}
| mit | b5c6f91faa5298a4a6c3b019d3e21d8a | 32.105128 | 131 | 0.642011 | 4.748437 | false | false | false | false |
tirupati17/loan-emi-calculator-clean-swift | EmiCalculator/Scenes/EmiCalculator/EmiCalculatorRouter.swift | 1 | 2215 | //
// EmiCalculatorRouter.swift
// EmiCalculator
//
// Created by Tirupati Balan on 11/04/16.
// Copyright (c) 2016 CelerStudio. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so you can apply
// clean architecture to your iOS and Mac projects, see http://clean-swift.com
//
import UIKit
protocol EmiCalculatorRouterInput
{
func navigateToSomewhere()
}
class EmiCalculatorRouter: EmiCalculatorRouterInput
{
weak var viewController: EmiCalculatorViewController!
// MARK: Navigation
func navigateToSomewhere()
{
// NOTE: Teach the router how to navigate to another scene. Some examples follow:
// 1. Trigger a storyboard segue
// viewController.performSegueWithIdentifier("ShowSomewhereScene", sender: nil)
// 2. Present another view controller programmatically
// viewController.presentViewController(someWhereViewController, animated: true, completion: nil)
// 3. Ask the navigation controller to push another view controller onto the stack
// viewController.navigationController?.pushViewController(someWhereViewController, animated: true)
// 4. Present a view controller from a different storyboard
// let storyboard = UIStoryboard(name: "OtherThanMain", bundle: nil)
// let someWhereViewController = storyboard.instantiateInitialViewController() as! SomeWhereViewController
// viewController.navigationController?.pushViewController(someWhereViewController, animated: true)
}
// MARK: Communication
func passDataToNextScene(_ segue: UIStoryboardSegue)
{
// NOTE: Teach the router which scenes it can communicate with
if segue.identifier == "ShowSomewhereScene" {
passDataToSomewhereScene(segue)
}
}
func passDataToSomewhereScene(_ segue: UIStoryboardSegue)
{
// NOTE: Teach the router how to pass data to the next scene
// let someWhereViewController = segue.destinationViewController as! SomeWhereViewController
// someWhereViewController.output.name = viewController.output.name
}
}
| mit | 19657808e7b4033b67a2114c509963d3 | 34.725806 | 114 | 0.700226 | 5.723514 | false | false | false | false |
tjw/swift | test/decl/class/override.swift | 2 | 19590 | // RUN: %target-typecheck-verify-swift -parse-as-library
class A {
func ret_sametype() -> Int { return 0 }
func ret_subclass() -> A { return self }
func ret_subclass_rev() -> B { return B() }
func ret_nonclass_optional() -> Int? { return .none }
func ret_nonclass_optional_rev() -> Int { return 0 }
func ret_class_optional() -> B? { return .none }
func ret_class_optional_rev() -> A { return self }
func ret_class_uoptional() -> B! { return B() }
func ret_class_uoptional_rev() -> A { return self }
func ret_class_optional_uoptional() -> B? { return .none }
func ret_class_optional_uoptional_rev() -> A! { return self }
func param_sametype(_ x : Int) {}
func param_subclass(_ x : B) {}
func param_subclass_rev(_ x : A) {}
func param_nonclass_optional(_ x : Int) {}
func param_nonclass_optional_rev(_ x : Int?) {}
func param_class_optional(_ x : B) {}
func param_class_optional_rev(_ x : B?) {}
func param_class_uoptional(_ x : B) {}
func param_class_uoptional_rev(_ x : B!) {}
func param_class_optional_uoptional(_ x : B!) {}
func param_class_optional_uoptional_rev(_ x : B?) {}
}
class B : A {
override func ret_sametype() -> Int { return 1 }
override func ret_subclass() -> B { return self }
func ret_subclass_rev() -> A { return self }
override func ret_nonclass_optional() -> Int { return 0 }
func ret_nonclass_optional_rev() -> Int? { return 0 }
override func ret_class_optional() -> B { return self }
func ret_class_optional_rev() -> A? { return self }
override func ret_class_uoptional() -> B { return self }
func ret_class_uoptional_rev() -> A! { return self }
override func ret_class_optional_uoptional() -> B! { return self }
override func ret_class_optional_uoptional_rev() -> A? { return self }
override func param_sametype(_ x : Int) {}
override func param_subclass(_ x : A) {}
func param_subclass_rev(_ x : B) {}
override func param_nonclass_optional(_ x : Int?) {}
func param_nonclass_optional_rev(_ x : Int) {}
override func param_class_optional(_ x : B?) {}
func param_class_optional_rev(_ x : B) {}
override func param_class_uoptional(_ x : B!) {}
func param_class_uoptional_rev(_ x : B) {}
override func param_class_optional_uoptional(_ x : B?) {}
override func param_class_optional_uoptional_rev(_ x : B!) {}
}
class C<T> {
func ret_T() -> T {}
}
class D<T> : C<[T]> {
override func ret_T() -> [T] {}
}
class E {
var var_sametype: Int { get { return 0 } set {} }
var var_subclass: E { get { return self } set {} } // expected-note{{attempt to override property here}}
var var_subclass_rev: F { get { return F() } set {} } // expected-note{{attempt to override property here}}
var var_nonclass_optional: Int? { get { return .none } set {} } // expected-note{{attempt to override property here}}
var var_nonclass_optional_rev: Int { get { return 0 } set {} } // expected-note{{attempt to override property here}}
var var_class_optional: F? { get { return .none } set {} } // expected-note{{attempt to override property here}}
var var_class_optional_rev: E { get { return self } set {} } // expected-note{{attempt to override property here}}
var var_class_uoptional: F! { get { return F() } set {} } // expected-note{{attempt to override property here}}
var var_class_uoptional_rev: E { get { return self } set {} } // expected-note{{attempt to override property here}}
var var_class_optional_uoptional: F? { get { return .none } set {} }
var var_class_optional_uoptional_rev: E! { get { return self } set {} }
var ro_sametype: Int { return 0 }
var ro_subclass: E { return self }
var ro_subclass_rev: F { return F() }
var ro_nonclass_optional: Int? { return 0 }
var ro_nonclass_optional_rev: Int { return 0 } // expected-note{{attempt to override property here}}
var ro_class_optional: F? { return .none }
var ro_class_optional_rev: E { return self } // expected-note{{attempt to override property here}}
var ro_class_uoptional: F! { return F() }
var ro_class_uoptional_rev: E { return self } // expected-note{{attempt to override property here}}
var ro_class_optional_uoptional: F? { return .none }
var ro_class_optional_uoptional_rev: E! { return self }
}
class F : E {
override var var_sametype: Int { get { return 0 } set {} }
override var var_subclass: F { get { return self } set {} } // expected-error{{cannot override mutable property 'var_subclass' of type 'E' with covariant type 'F'}}
override var var_subclass_rev: E { get { return F() } set {} } // expected-error{{property 'var_subclass_rev' with type 'E' cannot override a property with type 'F}}
override var var_nonclass_optional: Int { get { return 0 } set {} } // expected-error{{cannot override mutable property 'var_nonclass_optional' of type 'Int?' with covariant type 'Int'}}
override var var_nonclass_optional_rev: Int? { get { return 0 } set {} } // expected-error{{property 'var_nonclass_optional_rev' with type 'Int?' cannot override a property with type 'Int'}}
override var var_class_optional: F { get { return self } set {} } // expected-error{{cannot override mutable property 'var_class_optional' of type 'F?' with covariant type 'F'}}
override var var_class_optional_rev: E? { get { return self } set {} } // expected-error{{property 'var_class_optional_rev' with type 'E?' cannot override a property with type 'E'}}
override var var_class_uoptional: F { get { return F() } set {} } // expected-error{{cannot override mutable property 'var_class_uoptional' of type 'F?' with covariant type 'F'}}
override var var_class_uoptional_rev: E! { get { return self } set {} } // expected-error{{property 'var_class_uoptional_rev' with type 'E?' cannot override a property with type 'E'}}
override var var_class_optional_uoptional: F! { get { return .none } set {} }
override var var_class_optional_uoptional_rev: E? { get { return self } set {} }
override var ro_sametype: Int { return 0 }
override var ro_subclass: E { return self }
override var ro_subclass_rev: F { return F() }
override var ro_nonclass_optional: Int { return 0 }
override var ro_nonclass_optional_rev: Int? { return 0 } // expected-error{{property 'ro_nonclass_optional_rev' with type 'Int?' cannot override a property with type 'Int'}}
override var ro_class_optional: F { return self }
override var ro_class_optional_rev: E? { return self } // expected-error{{property 'ro_class_optional_rev' with type 'E?' cannot override a property with type 'E'}}
override var ro_class_uoptional: F { return F() }
override var ro_class_uoptional_rev: E! { return self } // expected-error{{property 'ro_class_uoptional_rev' with type 'E?' cannot override a property with type 'E'}}
override var ro_class_optional_uoptional: F! { return .none }
override var ro_class_optional_uoptional_rev: E? { return self }
}
class G {
func f1(_: Int, int: Int) { }
func f2(_: Int, int: Int) { }
func f3(_: Int, int: Int) { }
func f4(_: Int, int: Int) { }
func f5(_: Int, int: Int) { }
func f6(_: Int, int: Int) { }
func f7(_: Int, int: Int) { }
func g1(_: Int, string: String) { } // expected-note{{potential overridden instance method 'g1(_:string:)' here}} {{28-28=string }}
func g1(_: Int, path: String) { } // expected-note{{potential overridden instance method 'g1(_:path:)' here}} {{28-28=path }}
func g2(_: Int, string: String) { } // expected-note{{potential overridden instance method 'g2(_:string:)' here}} {{none}}
func g2(_: Int, path: String) { }
func g3(_: Int, _ another: Int) { }
func g3(_: Int, path: String) { } // expected-note{{potential overridden instance method 'g3(_:path:)' here}} {{none}}
func g4(_: Int, _ another: Int) { }
func g4(_: Int, path: String) { }
init(a: Int) {} // expected-note {{potential overridden initializer 'init(a:)' here}} {{none}}
init(a: String) {} // expected-note {{potential overridden initializer 'init(a:)' here}} {{17-17=a }} expected-note {{potential overridden initializer 'init(a:)' here}} {{none}}
init(b: String) {} // expected-note {{potential overridden initializer 'init(b:)' here}} {{17-17=b }} expected-note {{potential overridden initializer 'init(b:)' here}} {{none}}
}
class H : G {
override func f1(_: Int, _: Int) { } // expected-error{{argument labels for method 'f1' do not match those of overridden method 'f1(_:int:)'}}{{28-28=int }}
override func f2(_: Int, value: Int) { } // expected-error{{argument labels for method 'f2(_:value:)' do not match those of overridden method 'f2(_:int:)'}}{{28-28=int }}
override func f3(_: Int, value int: Int) { } // expected-error{{argument labels for method 'f3(_:value:)' do not match those of overridden method 'f3(_:int:)'}}{{28-34=}}
override func f4(_: Int, _ int: Int) { } // expected-error{{argument labels for method 'f4' do not match those of overridden method 'f4(_:int:)'}}{{28-30=}}
override func f5(_: Int, value inValue: Int) { } // expected-error{{argument labels for method 'f5(_:value:)' do not match those of overridden method 'f5(_:int:)'}}{{28-33=int}}
override func f6(_: Int, _ inValue: Int) { } // expected-error{{argument labels for method 'f6' do not match those of overridden method 'f6(_:int:)'}}{{28-29=int}}
override func f7(_: Int, int value: Int) { } // okay
override func g1(_: Int, s: String) { } // expected-error{{declaration 'g1(_:s:)' has different argument labels from any potential overrides}}{{none}}
override func g2(_: Int, string: Int) { } // expected-error{{method does not override any method from its superclass}} {{none}}
override func g3(_: Int, path: Int) { } // expected-error{{method does not override any method from its superclass}} {{none}}
override func g4(_: Int, string: Int) { } // expected-error{{argument labels for method 'g4(_:string:)' do not match those of overridden method 'g4'}} {{28-28=_ }}
override init(x: Int) {} // expected-error{{argument labels for initializer 'init(x:)' do not match those of overridden initializer 'init(a:)'}} {{17-17=a }}
override init(x: String) {} // expected-error{{declaration 'init(x:)' has different argument labels from any potential overrides}} {{none}}
override init(a: Double) {} // expected-error{{initializer does not override a designated initializer from its superclass}} {{none}}
override init(b: Double) {} // expected-error{{initializer does not override a designated initializer from its superclass}} {{none}}
}
@objc class IUOTestBaseClass {
func none() {}
func oneA(_: AnyObject) {}
func oneB(x: AnyObject) {}
func oneC(_ x: AnyObject) {}
func manyA(_: AnyObject, _: AnyObject) {}
func manyB(_ a: AnyObject, b: AnyObject) {}
func manyC(var a: AnyObject, // expected-error {{'var' as a parameter attribute is not allowed}}
var b: AnyObject) {} // expected-error {{'var' as a parameter attribute is not allowed}}
func result() -> AnyObject? { return nil }
func both(_ x: AnyObject) -> AnyObject? { return x }
init(_: AnyObject) {}
init(one: AnyObject) {}
init(a: AnyObject, b: AnyObject) {}
}
class IUOTestSubclass : IUOTestBaseClass {
override func oneA(_: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}}
override func oneB(x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}}
override func oneC(_ x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{36-37=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{27-27=(}} {{37-37=)}}
override func manyA(_: AnyObject!, _: AnyObject!) {} // expected-warning 2 {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 2 {{remove '!' to make the parameter required}}
// expected-note@-2 2 {{add parentheses to silence this warning}}
override func manyB(_ a: AnyObject!, b: AnyObject!) {} // expected-warning 2 {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 2 {{remove '!' to make the parameter required}}
// expected-note@-2 2 {{add parentheses to silence this warning}}
override func result() -> AnyObject! { return nil } // expected-warning {{overriding instance method optional result type 'AnyObject?' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 {{use '?' to make the result optional}} {{38-39=?}}
// expected-note@-2 {{add parentheses to silence this warning}} {{29-29=(}} {{39-39=)}}
override func both(_ x: AnyObject!) -> AnyObject! { return x } // expected-warning {{overriding instance method optional result type 'AnyObject?' with implicitly unwrapped optional type 'AnyObject?'}} expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 {{use '?' to make the result optional}} {{51-52=?}} expected-note@-1 {{remove '!' to make the parameter required}} {{36-37=}}
// expected-note@-2 2 {{add parentheses to silence this warning}}
override init(_: AnyObject!) {} // expected-warning {{overriding initializer parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{29-30=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{20-20=(}} {{30-30=)}}
override init(one: AnyObject!) {} // expected-warning {{overriding initializer parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{31-32=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{22-22=(}} {{32-32=)}}
override init(a: AnyObject!, b: AnyObject!) {} // expected-warning 2 {{overriding initializer parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 2 {{remove '!' to make the parameter required}}
// expected-note@-2 2 {{add parentheses to silence this warning}}
}
class IUOTestSubclass2 : IUOTestBaseClass {
override func oneA(_ x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{36-37=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{27-27=(}} {{37-37=)}}
override func oneB(x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}}
override func oneC(_: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject?'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}}
}
class IUOTestSubclassOkay : IUOTestBaseClass {
override func oneA(_: AnyObject?) {}
override func oneC(_ x: AnyObject) {}
}
class GenericBase<T> {}
class ConcreteDerived: GenericBase<Int> {}
class OverriddenWithConcreteDerived<T> {
func foo() -> GenericBase<T> {} // expected-note{{potential overridden instance method 'foo()' here}}
}
class OverridesWithMismatchedConcreteDerived<T>:
OverriddenWithConcreteDerived<T> {
override func foo() -> ConcreteDerived {} //expected-error{{does not override}}
}
class OverridesWithConcreteDerived:
OverriddenWithConcreteDerived<Int> {
override func foo() -> ConcreteDerived {}
}
// <rdar://problem/24646184>
class Ty {}
class SubTy : Ty {}
class Base24646184 {
init(_: SubTy) { }
func foo(_: SubTy) { }
init(ok: Ty) { }
init(ok: SubTy) { }
func foo(ok: Ty) { }
func foo(ok: SubTy) { }
}
class Derived24646184 : Base24646184 {
override init(_: Ty) { } // expected-note {{'init' previously overridden here}}
override init(_: SubTy) { } // expected-error {{'init' has already been overridden}}
override func foo(_: Ty) { } // expected-note {{'foo' previously overridden here}}
override func foo(_: SubTy) { } // expected-error {{'foo' has already been overridden}}
override init(ok: Ty) { }
override init(ok: SubTy) { }
override func foo(ok: Ty) { }
override func foo(ok: SubTy) { }
}
// Generic subscripts
class GenericSubscriptBase {
var dict: [AnyHashable : Any] = [:]
subscript<T : Hashable, U>(t: T) -> U {
get {
return dict[t] as! U
}
set {
dict[t] = newValue
}
}
}
class GenericSubscriptDerived : GenericSubscriptBase {
override subscript<K : Hashable, V>(t: K) -> V {
get {
return super[t]
}
set {
super[t] = newValue
}
}
}
// @escaping
class CallbackBase {
func perform(handler: @escaping () -> Void) {} // expected-note * {{here}}
func perform(optHandler: (() -> Void)?) {} // expected-note * {{here}}
func perform(nonescapingHandler: () -> Void) {} // expected-note * {{here}}
}
class CallbackSubA: CallbackBase {
override func perform(handler: () -> Void) {} // expected-error {{method does not override any method from its superclass}}
// expected-note@-1 {{type does not match superclass instance method with type '(@escaping () -> Void) -> ()'}}
override func perform(optHandler: () -> Void) {} // expected-error {{method does not override any method from its superclass}}
override func perform(nonescapingHandler: () -> Void) {}
}
class CallbackSubB : CallbackBase {
override func perform(handler: (() -> Void)?) {}
override func perform(optHandler: (() -> Void)?) {}
override func perform(nonescapingHandler: (() -> Void)?) {} // expected-error {{method does not override any method from its superclass}}
}
class CallbackSubC : CallbackBase {
override func perform(handler: @escaping () -> Void) {}
override func perform(optHandler: @escaping () -> Void) {} // expected-error {{cannot override instance method parameter of type '(() -> Void)?' with non-optional type '() -> Void'}}
override func perform(nonescapingHandler: @escaping () -> Void) {} // expected-error {{method does not override any method from its superclass}}
}
// Issues with overrides of internal(set) and fileprivate(set) members
public class BaseWithInternalSetter {
public internal(set) var someValue: Int = 0
}
public class DerivedWithInternalSetter: BaseWithInternalSetter {
override public internal(set) var someValue: Int {
get { return 0 }
set { }
}
}
class BaseWithFilePrivateSetter {
fileprivate(set) var someValue: Int = 0
}
class DerivedWithFilePrivateSetter: BaseWithFilePrivateSetter {
override fileprivate(set) var someValue: Int {
get { return 0 }
set { }
}
}
| apache-2.0 | 26cedb7706698b8413c4bf67e7a40602 | 54.653409 | 333 | 0.671006 | 3.86543 | false | false | false | false |
thatseeyou/SpriteKitExamples.playground | Sources/PlaygroundHelper.swift | 1 | 1600 | /*:
Prepare for key window and live view
*/
import Foundation
import UIKit
//import XCPlayground
import PlaygroundSupport
open class PlaygroundHelper
{
/** mimic iOS initialization
- parameter width: width of window (default 320)
- parameter height: height of window (default 480)
*/
open class func initWindow(_ width:CGFloat = 320.0, _ height:CGFloat = 480.0)
{
/*:
다음과 같이 하면 에러 메시지가 표시된다.
- window.rootViewController = ViewController()
에러 메시지
- Presenting view controllers on detached view controllers is discouraged
다음과 같이 수정
- UIApplication.sharedApplication().keyWindow!.rootViewController = ViewController()
*/
let window : UIWindow! = UIWindow(frame: CGRect(x: 0.0, y: 0.0, width: width, height: height))
window.backgroundColor = UIColor.gray
window.makeKeyAndVisible()
// XCPlaygroundPage.currentPage.liveView = UIApplication.shared.keyWindow!
PlaygroundPage.current.liveView = UIApplication.shared.keyWindow!
print(UIApplication.shared.keyWindow!)
}
/** make UIWindow and show viewController.view
- parameter viewController: root view controller
- parameter width: width of window (default 320)
- parameter height: height of window (default 480)
*/
open class func showViewController(_ viewController:UIViewController, width:CGFloat = 320.0, height:CGFloat = 480.0)
{
self.initWindow(width, height)
UIApplication.shared.keyWindow!.rootViewController = viewController
}
}
| isc | b04820fb5da0d4de1eca7c87c1a33823 | 31.808511 | 120 | 0.702335 | 4.307263 | false | false | false | false |
curia007/Frameworks | src/MotionGame/MotionGame/AppDelegate.swift | 1 | 6103 | //
// AppDelegate.swift
// MotionGame
//
// Created by Carmelo Uria on 8/26/15.
// Copyright © 2015 Carmelo Uria. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.carmelouria.MotionGame" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("MotionGame", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | ab2ce83c299841675facac23324cf76a | 53.972973 | 291 | 0.719928 | 5.856046 | false | false | false | false |
juliangrosshauser/HomeControl | HomeControl/Source/RoomController.swift | 1 | 2903 | //
// RoomController.swift
// HomeControl
//
// Created by Julian Grosshauser on 04/01/16.
// Copyright © 2016 Julian Grosshauser. All rights reserved.
//
import UIKit
final class RoomController: UITableViewController {
//MARK: Properties
private let viewModel: RoomViewModel
weak var delegate: RoomControllerDelegate?
//MARK: Initialization
init(viewModel: RoomViewModel) {
self.viewModel = viewModel
super.init(style: .Plain)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(RoomCell.self, forCellReuseIdentifier: String(RoomCell))
}
}
//MARK: UITableViewDataSource
extension RoomController {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.rooms.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(String(RoomCell)) as! RoomCell
cell.configure(viewModel.rooms[indexPath.row])
return cell
}
}
//MARK: UITableViewDelegate
extension RoomController {
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
delegate?.roomChanged(viewModel.rooms[indexPath.row])
guard let splitViewController = splitViewController, detailViewController = delegate as? UIViewController else {
return
}
if splitViewController.collapsed {
splitViewController.showDetailViewController(detailViewController, sender: nil)
} else {
guard splitViewController.displayMode == .PrimaryOverlay else { return }
UIView.animateWithDuration(0.3) { splitViewController.preferredDisplayMode = .PrimaryHidden }
splitViewController.preferredDisplayMode = .Automatic
}
}
}
//MARK: UISplitViewControllerDelegate
extension RoomController: UISplitViewControllerDelegate {
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool {
// If detail view controller contains a `AccessoryController` and it's `room` property isn't set, show master view controller first, because the `AccessoryController` doesn't yet know what accessories to show.
if let navigationController = secondaryViewController as? UINavigationController, accessoryController = navigationController.topViewController as? AccessoryController where accessoryController.room == nil {
return true
}
return false
}
}
| mit | 5f6c7ea6199c37e8871a48c1a2db8990 | 33.141176 | 224 | 0.731909 | 5.701375 | false | false | false | false |
libzhu/LearnSwift | 闭包/MyPlayground.playground/Contents.swift | 1 | 16552 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
//(1)创建两个类型相同的函数,一个函数返回两个整数的差值 一个返回整数的乘积
func diff (number1 : Int, number2 : Int) -> Int{
return number1 - number2
}
func mul (number1 : Int, number2 : Int) -> Int{
return number1 * number2
}
//(2)定义一个枚举来枚举每种函数的类型,
enum CountType : Int{
case DiffCount = 0
case MulCount
}
//(3)定义一个函数 把 (1)和 (2)定义的东西组合起来
func choiseCountType (countType : CountType) -> (Int, Int) -> Int{
var myFuncType : (Int, Int) -> Int
switch countType {
case .DiffCount:
myFuncType = diff
case .MulCount:
myFuncType = mul
}
return myFuncType
}
var myFouncType : (Int, Int) -> Int
myFouncType = choiseCountType(countType: CountType.DiffCount)
myFouncType(20, 30)
myFouncType = choiseCountType(countType: CountType.MulCount)
myFouncType(30, 20)
/*
本页包含内容:
闭包表达式
尾随闭包
值捕获
闭包是引用类型
逃逸闭包
自动闭包
*/
//闭包 是自包含的函数代码 块, 可以在代码中被传递和使用。Swift 中的闭包 与 c 和 objective-c中的 代码块(blocks)比较相似;
//闭包可以捕获 和 存储其上下文中任意的常量 和 变量的引用。被称为包裹常量和变量。
//Swift 会为你管理在捕获过程中涉及到的所有内存操作
//全局和嵌套函数实际上也是特殊的闭包,
/*
· 全局函数是一个有名字但不会捕获任何值的闭包
· 嵌套函数是一个有名字并且可以捕获其封闭函数内值的闭包
· 闭包表达式是一个利用轻量级语法所写的可以捕获其上下文变量或常量值的匿名闭包
*/
//Swift 的闭包表达式拥有简介的风格,并鼓励在常见的场景中进行语法优化,如下
/*
· 利用上下文推断参数和返回值类型
· 隐式返回但表达式闭包, 即但表达式闭包可以省略 return 关键字
· 参数名称缩写
· 尾随闭包语法
*/
//1-1、Closure 就是匿名 函数,我们可以定义一个闭包变量,而这个闭包类型的变量就是我们上面介绍的函数类型、定义一个闭包变量就是定义一个特殊函数类型的的变量、凡是如下;因为closure变量没有赋初始值、所以我们把其声明成可选的变量
var myCloure0 : ((Int , Int) -> Int)?
//另一种常用的声明闭包变量的方式。使用关键字 typealias定义定义一个特定函数类型,我们可以用这个类型声明一个 Closure 变量
typealias myCloureType = (Int, Int) -> Int
var myCloure : myCloureType?
//给闭包变量赋值,的函数体中含有参数列表 ,参数列表和真正的函数体之间 使用关键字in来分割。闭包可选变量的调用和普通函数没有什么区别,唯一不同是这个函数需要使用 ! 来强制解包。
myCloure0 = {(num1 : Int,num2 : Int) -> Int in
return num1 + num2
}
myCloure0!(10, 20)
//数组中常用的闭包函数 Swift 中 自带一些比较好用的闭包函数;例如 map sorted filter reduce
//Map 映射 map闭包函数的功能就是对数组中的每一项进行遍历,然后通过映射规则对数组中的每一项进行处理,最终的返回结果是处理后的数组(以一个新的数组形式出现)。当然,原来数组中的元素值是保持不变的,这就是map闭包函数的用法与功能。
let family = [1, 2, 3, 4, 5]
var falmilMap = family.map { (item : Int) -> String in
return "我是老\(item)"
}
family
print(falmilMap)
//2.Filter 过滤器
//Filter的用法还是比较好理解的,Filter就是一个漏勺,就是用来过滤符合条件的数据的
let heightOfPerson = [170, 180, 173, 175, 190, 168]
let heightOfPersonFilter = heightOfPerson.filter { (height : Int) -> Bool in
return height >= 173
}
heightOfPerson
print(heightOfPersonFilter)
//Reduce Swift 中使用Reduce 闭包来合并items 并且是和并后的value
let salary = [1000, 2000, 3000, 4000, 9000]
let sumSalary = salary.reduce(0) { (sumSalaryTemp : Int, salaryItems : Int) -> Int in
return sumSalaryTemp + salaryItems
}
//1、闭包表达式
//嵌套函数 是一个在较复杂函数中方便进行命名和定义闭包函数代码块的方块。嵌套函数是一个在较复杂函数中方便进行命名和定义自包含代码模块的方式。当然,有时候编写小巧的没有完整定义和命名的类函数结构也是很有用处的,尤其是在你处理一些函数并需要将另外一些函数作为该函数的参数时。
//闭包表达式是一种利用简洁语法构建内联闭包的方式。闭包表达式提供了一些语法优化,使得撰写闭包变得简单明了。下面闭包表达式的例子通过使用几次迭代展示了 sorted(by:) 方法定义和语法优化的方式。每一次迭代都用更简洁的方式描述了相同的功能。
//1.1、sorted 方法
//Swift 标准库提供了 名为 sorted(by:)的方法,会根据你提供的用于排序的闭包函数将已知类型函数数组中的值进行排序。一旦完成,sorted(by:)方法会返回一个与原数组大小相同,包含同类型元素且元素正确排序的新数组。原数组不会被 sorted(by:)方法修改
//下面的闭包表达式使用 sorted(by:)方法对一个 String 类型的数组进行字母逆序排列。一下是初始数组:
let names = ["xiaoming", "zhansan", "lisi", "wangwu", "zhaoliu"]
//sorted(by:)方法接受一个闭包, 该闭包函数需要传入与数组元素类型相同的两个值, 并返回一个布尔类型值来表明当排序结束后传入的第一个参数排在第二个参数的前面还是后面。如果第一个参数值出现在第二个参数值前面,排序闭包函数返回TRUE 反之 返回FALSE
//该例子对一个 String 类型的数组进行排序,因此排序闭包函数类型需为 (String, String) -> Bool。
let sortedNames = names.sorted { (str1 : String, str2 : String) -> Bool in
return str1 > str2
}
func backward(_ s1 : String, _ s2 : String) -> Bool{
return s1 > s2
}
var reveredNames = names.sorted(by: backward)
//2.闭包表达式的语法
//2.1、闭包表达式语法有如下的一般形式
/*
{ (parameters) -> returnType in
statements
}
*/
//闭包表达式参数可以是 in-out 参数, 但不能设定默认值。也可以使用局名的可变参数 元组也可以作为参数和返回值
names.sorted { (s1, s2) -> Bool in
return s1 > s2
}
reveredNames = names.sorted(by: { (s1 : String, s2 : String) -> Bool in
return s1 > s2
})
///需要注意的是内联闭包参数和返回值类型声明与 backward(_:_:) 函数类型声明相同。在这两种方式中,都写成了 (s1: String, s2: String) -> Bool。然而在内联闭包表达式中,函数和返回值类型都写在大括号内,而不是大括号外。闭包的函数体部分由关键字in引入。该关键字表示闭包的参数和返回值类型定义已经完成,闭包函数体即将开始。
//由于这个闭包的函数体部分如此短,以至于可以将其改写成一行代码:
reveredNames = names.sorted(by: { (s1: String, s2: String) -> Bool in return s1 > s2 } )
print(reveredNames)
//该例中 sorted(by:) 方法的整体调用保持不变,一对圆括号仍然包裹住了方法的整个参数。然而,参数现在变成了内联闭包。
//2、根据上下文推断类型
//因为排序闭包函数是作为 sorted(by:) 方法的参数传入的,Swift 可以推断其参数和返回值的类型。sorted(by:) 方法被一个字符串数组调用,因此其参数必须是 (String, String) -> Bool 类型的函数。这意味着 (String, String) 和 Bool 类型并不需要作为闭包表达式定义的一部分。因为所有的类型都可以被正确推断,返回箭头(->)和围绕在参数周围的括号也可以被省略:
reveredNames = names.sorted(by: { s1, s2 in return s1 > s2 } )
//实际上,通过内联闭包表达式构造的闭包作为参数传递给函数或方法时,总是能够推断出闭包的参数和返回值类型。这意味着闭包作为函数或者方法的参数时,你几乎不需要利用完整格式构造内联闭包。
//尽管如此,你仍然可以明确写出有着完整格式的闭包。如果完整格式的闭包能够提高代码的可读性,则我们更鼓励采用完整格式的闭包。而在 sorted(by:) 方法这个例子里,显然闭包的目的就是排序。由于这个闭包是为了处理字符串数组的排序,因此读者能够推测出这个闭包是用于字符串处理的。
//3、单表达式闭包隐式返回
//单行表达式闭包可以通过省略 return 关键字来隐式返回单行表达式的结果,如上版本的例子可以改写为:
reveredNames = names.sorted(by: { s1, s2 in s1 > s2 } )
//在这个例子中,sorted(by:) 方法的参数类型明确了闭包必须返回一个 Bool 类型值。因为闭包函数体只包含了一个单一表达式(s1 > s2),该表达式返回 Bool 类型值,因此这里没有歧义,return 关键字可以省略。
//4、参数名称缩写
//Swift 自动为内联闭包提供了参数名称缩写功能,你可以直接通过 $0,$1,$2 来顺序调用闭包的参数,以此类推。
//如果你在闭包表达式中使用参数名称缩写,你可以在闭包定义中省略参数列表,并且对应参数名称缩写的类型会通过函数类型进行推断。in关键字也同样可以被省略,因为此时闭包表达式完全由闭包函数体构成:
reveredNames = names.sorted(by: { $0 > $1 } )
//在这个例子中,$0和$1表示闭包中第一个和第二个 String 类型的参数。
//5、运算符方法
//实际上还有一种更简短的方式来编写上面例子中的闭包表达式。Swift 的 String 类型定义了关于大于号(>)的字符串实现,其作为一个函数接受两个 String 类型的参数并返回 Bool 类型的值。而这正好与 sorted(by:) 方法的参数需要的函数类型相符合。因此,你可以简单地传递一个大于号,Swift 可以自动推断出你想使用大于号的字符串函数实现:
reveredNames = names.sorted(by: >)
//更多关于运算符方法的内容请查看运算符方法。
//6、尾随闭包
let digitNameS = [0 : "zero", 1 : "one", 2 : "two", 3 : "three", 4 : "four", 5 : "five", 6 : "six", 7 : "seven", 8 : "eight", 9 : "nine"]
let numbers = [123, 24, 250]
let srings = numbers.map { (num) -> String in
var outPut = ""
var number = num
repeat {
print(number)
outPut = digitNameS[number % 10]! + outPut
number /= 10
} while number > 0
return outPut
}
print(srings)
//值捕获
//闭包可以在其被定义的上下文中 捕获常量 和 变量。即使定义这些常量的作用域已经不存在,闭包任然可以在闭包函数体内应用和修改这些值
//Swift 中 可以捕获值的闭包的最简单的形式即使嵌套函数, 也就是定义在其他函数的函数体内的函数。嵌套函数可以捕获其外部函数的所有参数,及定义的常量 和 变量
func makeIncrementer(forIncrement amount : Int) -> () -> Int{//返回的是一个闭包
var runningTotal = 0
func increment() -> Int{
runningTotal += amount
return runningTotal
}
return increment
}
//解释 :incrementer() 函数并没有任何参数,但是在函数体内访问了 runningTotal 和 amount 变量。这是因为它从外围函数捕获了 runningTotal 和 amount 变量的引用。捕获引用保证了 runningTotal 和 amount 变量在调用完 makeIncrementer 后不会消失,并且保证了在下一次执行 incrementer 函数时,runningTotal 依旧存在。
let incrementByTen = makeIncrementer(forIncrement: 10)//定义了一个 incrementByTen 的常量, 该常量指向一个每次调用会将其 runningTotal 变量增加 10 的 Incrementer 函数
incrementByTen()
incrementByTen()
let incrementBySeven = makeIncrementer(forIncrement: 7)
incrementBySeven()
incrementBySeven()
incrementByTen()
//闭包是引用类型
//上面的例子中,incrementBySeven 和 incrementByTen 都是常量,但是这些常量指向的闭包仍然可以增加其捕获的变量的值。这是因为函数和闭包都是引用类型。无论你将函数或闭包赋值给一个常量还是变量,你实际上都是将常量或变量的值设置为对应函数或闭包的引用。上面的例子中,指向闭包的引用 incrementByTen 是一个常量,而并非闭包内容本身。
//这也意味着如果你将闭包赋值给了两个不同的常量或变量,两个值都会指向同一个闭包:
let alsoIncrementByTen = incrementByTen
alsoIncrementByTen()
//8、逃逸闭包
//当闭包作为一个参数传到一个函数中,但是这个闭包在函数返回之后才会不执行,我们称为该闭包从函数中逃逸。当你定义接受闭包作为参数的函数时,你可以在 参数名称之前 标注 @escaping,用来指明这个闭包是允许“逃逸”出这个函数的
//一种能使闭包“逃逸”出函数的方法是,将这个闭包保存在一个函数外部定义的变量中。举个例子,很多启动异步操作的函数接受一个闭包参数作为 completion handler。这类函数会在异步操作开始之后立刻返回,但是闭包直到异步操作结束后才会被调用。在这种情况下,闭包需要“逃逸”出函数,因为闭包需要在函数返回之后被调用。例如:
var completionHandlers : [() -> Void] = []
func someFuctionWithEscapingClosure(completionHander : @escaping () -> Void){
completionHandlers.append(completionHander)
}
//解释:someFuctionWithEscapingClosure(_:)函数接受一个闭包作为参数, 该闭包被添加到一个函数外定义的数组中,如果你不将这个参数标记为 @escaping 就会得到一个编译错误。将一个闭包 标记为 @escaping 意味着你必须在闭包中 显示的应用 self。比如说,在下面的代码中,传递到 someFunctionWithEscapingClosure(_:) 中的闭包是一个逃逸闭包,这意味着它需要显式地引用 self。相对的,传递到 someFunctionWithNonescapingClosure(_:) 中的闭包是一个非逃逸闭包,这意味着它可以隐式引用 self。
func someFunctionWithNoneEsapingClosure(closure : () -> Void){
closure()
}
class someClass{
var x = 10
func dosomething() -> Void {
someFuctionWithEscapingClosure {
self.x = 100
}
someFunctionWithNoneEsapingClosure {
x = 200
}
}
}
let instance = someClass()
instance.dosomething()
print(instance.x)
completionHandlers.first?()
print(instance.x)
//10、自动闭包
//自动闭包是一种自动创建的闭包,用于包装传递给函数作为参数的表达式。这种闭包不接受任何参数,当他被调用的时候,会返回包装在其中的表达式的值。这个便利语法让你能能够省略闭包的或括号,用普通的表达式来替代显示的表达式
//我们经常会调用采用自动闭包的函数,但是很少去实现这样的函数。举个例子来说,assert(condition:message:file:line:) 函数接受自动闭包作为它的 condition 参数和 message 参数;它的 condition 参数仅会在 debug 模式下被求值,它的 message 参数仅当 condition 参数为 false 时被计算求值。
//自动闭包让你能够延迟求值,因为直到你调用这个闭包,代码段才会被执行。延迟求值对于那些有副作用(Side Effect)和高计算成本的代码来说是很有益处的,因为它使得你能控制代码的执行时机。下面的代码展示了闭包如何延时求值。
var customerInLine = ["Chris", "Alex", "ewa", "Barry", "Daniela"]
let deleteItem = customerInLine.remove(at: 0)
print(customerInLine.count)
let custmerProvider = {customerInLine.remove(at: 0)}
print(customerInLine.count)
print("删除的::\(custmerProvider())!")
print(customerInLine.count)
| mit | 912d33b49b32faee71ae3d414dcc9081 | 25.232493 | 307 | 0.736252 | 2.431836 | false | false | false | false |
VeniceX/File | Tests/FileTests/FileTests.swift | 3 | 6755 | #if os(Linux)
import Glibc
#else
import Darwin.C
#endif
import XCTest
@testable import File
public class FileTests : XCTestCase {
func testReadWrite() throws {
let deadline = 2.seconds.fromNow()
var buffer: Buffer
let file = try File(path: "/tmp/zewo-test-file", mode: .truncateReadWrite)
try file.write("abc", deadline: deadline)
try file.flush(deadline: deadline)
XCTAssertEqual(try file.cursorPosition(), 3)
_ = try file.seek(cursorPosition: 0)
buffer = try file.read(upTo: 3, deadline: deadline)
XCTAssertEqual(buffer.count, 3)
XCTAssertEqual(buffer, Buffer("abc"))
XCTAssertFalse(file.cursorIsAtEndOfFile)
buffer = try file.read(upTo: 3, deadline: deadline)
XCTAssertEqual(buffer.count, 0)
XCTAssertTrue(file.cursorIsAtEndOfFile)
_ = try file.seek(cursorPosition: 0)
XCTAssertFalse(file.cursorIsAtEndOfFile)
_ = try file.seek(cursorPosition: 3)
XCTAssertFalse(file.cursorIsAtEndOfFile)
buffer = try file.read(upTo: 6, deadline: deadline)
XCTAssertEqual(buffer.count, 0)
XCTAssertTrue(file.cursorIsAtEndOfFile)
}
func testReadAllFile() throws {
let file = try File(path: "/tmp/zewo-test-file", mode: .truncateReadWrite)
let word = "hello"
try file.write(word, deadline: 1.second.fromNow())
try file.flush(deadline: 1.second.fromNow())
_ = try file.seek(cursorPosition: 0)
let buffer = try file.readAll(deadline: 1.second.fromNow())
XCTAssert(buffer.count == word.utf8.count)
}
func testStaticMethods() throws {
let filePath = "/tmp/zewo-test-file"
let baseDirectoryPath = "/tmp/zewo"
let directoryPath = baseDirectoryPath + "/test/dir/"
let file = try File(path: filePath, mode: .truncateWrite)
XCTAssertTrue(File.fileExists(path: filePath))
XCTAssertFalse(File.isDirectory(path: filePath))
let word = "hello"
try file.write(word, deadline: 1.second.fromNow())
try file.flush(deadline: 1.second.fromNow())
file.close()
try File.removeFile(path: filePath)
XCTAssertThrowsError(try File.removeFile(path: filePath))
XCTAssertFalse(File.fileExists(path: filePath))
XCTAssertFalse(File.isDirectory(path: filePath))
try File.createDirectory(path: baseDirectoryPath)
XCTAssertThrowsError(try File.createDirectory(path: baseDirectoryPath))
XCTAssertEqual(try File.contentsOfDirectory(path: baseDirectoryPath), [])
XCTAssertTrue(File.fileExists(path: baseDirectoryPath))
XCTAssertTrue(File.isDirectory(path: baseDirectoryPath))
try File.removeDirectory(path: baseDirectoryPath)
XCTAssertThrowsError(try File.removeDirectory(path: baseDirectoryPath))
XCTAssertThrowsError(try File.contentsOfDirectory(path: baseDirectoryPath))
XCTAssertFalse(File.fileExists(path: baseDirectoryPath))
XCTAssertFalse(File.isDirectory(path: baseDirectoryPath))
try File.createDirectory(path: directoryPath, withIntermediateDirectories: true)
XCTAssertEqual(try File.contentsOfDirectory(path: baseDirectoryPath), ["test"])
XCTAssertTrue(File.fileExists(path: directoryPath))
XCTAssertTrue(File.isDirectory(path: directoryPath))
try File.removeDirectory(path: baseDirectoryPath)
XCTAssertThrowsError(try File.changeWorkingDirectory(path: baseDirectoryPath))
XCTAssertFalse(File.fileExists(path: baseDirectoryPath))
XCTAssertFalse(File.isDirectory(path: baseDirectoryPath))
let workingDirectory = File.workingDirectory
try File.changeWorkingDirectory(path: workingDirectory)
XCTAssertEqual(File.workingDirectory, workingDirectory)
}
func testFileSize() throws {
let file = try File(path: "/tmp/zewo-test-file", mode: .truncateReadWrite)
try file.write(Buffer("hello"), deadline: 1.second.fromNow())
try file.flush(deadline: 1.second.fromNow())
XCTAssertEqual(file.length, 5)
try file.write(" world", deadline: 1.second.fromNow())
try file.flush(deadline: 1.second.fromNow())
XCTAssertEqual(file.length, 11)
file.close()
XCTAssertThrowsError(try file.readAll(deadline: 1.second.fromNow()))
}
func testZero() throws {
let file = try File(path: "/dev/zero")
let count = 4096
let length = 256
for _ in 0 ..< count {
let buffer = try file.read(upTo: length, deadline: 1.second.fromNow())
XCTAssertEqual(buffer.count, length)
}
}
func testRandom() throws {
#if os(OSX)
let file = try File(path: "/dev/random")
let count = 4096
let length = 256
for _ in 0 ..< count {
let buffer = try file.read(upTo: length, deadline: 1.second.fromNow())
XCTAssertEqual(buffer.count, length)
}
#endif
}
func testDropLastPathComponent() throws {
XCTAssertEqual("/foo/bar//fuu///baz/".droppingLastPathComponent(), "/foo/bar/fuu")
XCTAssertEqual("/".droppingLastPathComponent(), "/")
XCTAssertEqual("/foo".droppingLastPathComponent(), "/")
XCTAssertEqual("foo".droppingLastPathComponent(), "")
}
func testFixSlashes() throws {
XCTAssertEqual("/foo/bar//fuu///baz/".fixingSlashes(stripTrailing: true), "/foo/bar/fuu/baz")
XCTAssertEqual("/".fixingSlashes(stripTrailing: true), "/")
}
func testFileModeValues() {
let modes: [FileMode: Int32] = [
.read: O_RDONLY,
.createWrite: (O_WRONLY | O_CREAT | O_EXCL),
.truncateWrite: (O_WRONLY | O_CREAT | O_TRUNC),
.appendWrite: (O_WRONLY | O_CREAT | O_APPEND),
.readWrite: (O_RDWR),
.createReadWrite: (O_RDWR | O_CREAT | O_EXCL),
.truncateReadWrite: (O_RDWR | O_CREAT | O_TRUNC),
.appendReadWrite: (O_RDWR | O_CREAT | O_APPEND),
]
for (mode, value) in modes {
XCTAssertEqual(mode.value, value)
}
}
}
extension FileTests {
public static var allTests: [(String, (FileTests) -> () throws -> Void)] {
return [
("testReadWrite", testReadWrite),
("testReadAllFile", testReadAllFile),
("testStaticMethods", testStaticMethods),
("testFileSize", testFileSize),
("testZero", testZero),
("testRandom", testRandom),
("testDropLastPathComponent", testDropLastPathComponent),
("testFixSlashes", testFixSlashes),
("testFileModeValues", testFileModeValues),
]
}
}
| mit | 8508f128bc2c377fd2bbee1fc4d02684 | 39.692771 | 101 | 0.643375 | 4.503333 | false | true | false | false |
crazypoo/PTools | Pods/Appz/Appz/Appz/Apps/Tweetbot.swift | 2 | 7948 | //
// Tweetbot.swift
// Appz
//
// Created by Hamad AlGhanim on 12/25/15.
// Copyright © 2015 kitz. All rights reserved.
//
/*
taken from http://tapbots.net/tweetbot3/support/url-schemes/
tweetbot://<screenname>/timeline
tweetbot://<screenname>/mentions
tweetbot://<screenname>/retweets
tweetbot://<screenname>/direct_messages
tweetbot://<screenname>/lists
tweetbot://<screenname>/favorites
tweetbot://<screenname>/search
tweetbot://<screenname>/search?query=<text>
tweetbot://<screenname>/status/<tweet_id>
tweetbot://<screenname>/user_profile/<profile_screenname>
tweetbot://<screenname>/post
tweetbot://<screenname>/post?text=<text>
tweetbot://<screenname>/post?text=<text>&callback_url=<url>&in_reply_to_status_id=<tweet_id>
tweetbot://<screenname>/search?query=<text>&callback_url=<url>
tweetbot://<screenname>/status/<tweet_id>?callback_url=<url>
tweetbot://<screenname>/user_profile/<screenname|user_id>?callback_url=<url>
tweetbot://<screenname>/follow/<screenname|user_id>
tweetbot://<screenname>/unfollow/<screenname|user_id>
tweetbot://<screenname>/favorite/<tweet_id>
tweetbot://<screenname>/unfavorite/<tweet_id>
tweetbot://<screenname>/retweet/<tweet_id>
tweetbot://<screenname>/list/<list_id>?callback_url=<url>
*/
public extension Applications {
public struct Tweetbot: ExternalApplication {
public typealias ActionType = Applications.Tweetbot.Action
public let scheme = "tweetbot:"
public let fallbackURL = "http://tapbots.com/tweetbot/"
public let appStoreId = "722294701"
public init() {}
}
}
// MARK: - Actions
public extension Applications.Tweetbot {
public enum Action {
case timeline(screenname: String?)
case mentions(screenname: String?)
case retweets(screenname: String?)
case directMessages(screenname: String?)
case lists(screenname: String?)
case favorites(screenname: String?)
case search(screenname: String?, query: String?, callbackurl: String?)
case status(screenname: String?, tweetId: String, callbackurl: String?)
case userProfile(screenname: String?, profileScreennameOrId: String, callbackurl: String?)
case post(screenname: String?,text: String?, callbackurl: String?, repliedStatusId: String?)
case follow(screenname: String?, followScreennameOrId: String)
case unfollow(screenname: String?, followScreennameOrId: String)
case favorite(screenname: String?, tweetId: String)
case unfavorite(screenname: String?, tweetId: String)
case retweet(screenname: String?, tweetId: String)
case list(screenname: String?, listId: String, callbackurl: String?)
}
}
extension Applications.Tweetbot.Action: ExternalApplicationAction {
public var paths: ActionPaths {
switch self {
//do actions
case .timeline(let screenname):
return ActionPaths(
app:
Path(
pathComponents: [screenname ?? "", "timeline"],
queryParameters: [:]),
web: Path())
case .mentions(let screenname):
return ActionPaths(
app:
Path(
pathComponents: [screenname ?? "", "mentions"],
queryParameters: [:]),
web: Path())
case .retweets(let screenname):
return ActionPaths(
app:
Path(
pathComponents: [screenname ?? "", "retweets"],
queryParameters: [:]),
web: Path())
case .directMessages(let screenname):
return ActionPaths(
app:
Path(
pathComponents: [screenname ?? "", "direct_messages"],
queryParameters: [:]),
web: Path())
case .lists(let screenname):
return ActionPaths(
app:
Path(
pathComponents: [screenname ?? "", "lists"],
queryParameters: [:]),
web: Path())
case .favorites(let screenname):
return ActionPaths(
app:
Path(
pathComponents: [screenname ?? "", "favorites"],
queryParameters: [:]),
web: Path())
case .search(let screenname, let query, let callbackurl):
return ActionPaths(
app:
Path(
pathComponents: [screenname ?? "", "search"],
queryParameters: [
"query":query ?? "",
"callback_url":callbackurl ?? ""]),
web: Path())
case .status(let screenname, let tweetId, let callbackurl):
return ActionPaths(
app:
Path(
pathComponents: [screenname ?? "", "status", tweetId],
queryParameters: ["callback_url":callbackurl ?? ""]),
web: Path())
case .userProfile(let screenname , let profileScreennameOrId , let callbackurl):
return ActionPaths(
app:
Path(
pathComponents: [screenname ?? "",
"user_profile", profileScreennameOrId],
queryParameters: ["callback_url":callbackurl ?? ""]),
web: Path())
case .post(let screenname, let text, let callbackurl, let repliedStatusId):
return ActionPaths(
app:
Path(
pathComponents: [screenname ?? "", "post"],
queryParameters: [
"text":text ?? "",
"in_reply_to_status_id": repliedStatusId ?? "",
"callback_url":callbackurl ?? ""]),
web: Path())
case .follow(let screenname, let followScreennameOrId):
return ActionPaths(
app:
Path(
pathComponents: [screenname ?? "", "follow", followScreennameOrId],
queryParameters: [:]),
web: Path())
case .unfollow(let screenname, let followScreennameOrId):
return ActionPaths(
app:
Path(
pathComponents: [screenname ?? "", "unfollow", followScreennameOrId],
queryParameters: [:]),
web: Path())
case .favorite(let screenname, let tweetId):
return ActionPaths(
app:
Path(
pathComponents: [screenname ?? "", "favorite", tweetId],
queryParameters: [:]),
web: Path())
case .unfavorite(let screenname, let tweetId):
return ActionPaths(
app:
Path(
pathComponents: [screenname ?? "", "unfavorite", tweetId],
queryParameters: [:]),
web: Path())
case .retweet(let screenname, let tweetId):
return ActionPaths(
app:
Path(
pathComponents: [screenname ?? "", "retweet", tweetId],
queryParameters: [:]),
web: Path())
case .list(let screenname, let listId, let callbackurl):
return ActionPaths(
app:
Path(
pathComponents: [screenname ?? "", "list", listId],
queryParameters: ["callback_url" : callbackurl ?? ""]),
web: Path())
}
}
}
| mit | 557a24c35af96ad018929d9c0652d7f9 | 35.791667 | 100 | 0.519693 | 5.290945 | false | false | false | false |
AbelSu131/ios-charts | Charts/Classes/Data/CandleChartDataSet.swift | 2 | 2800 | //
// CandleChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
public class CandleChartDataSet: BarLineScatterCandleChartDataSet
{
/// the width of the candle-shadow-line in pixels.
/// :default: 3.0
public var shadowWidth = CGFloat(1.5)
/// the space between the candle entries
/// :default: 0.1 (10%)
private var _bodySpace = CGFloat(0.1)
/// the color of the shadow line
public var shadowColor: UIColor?
/// color for open <= close
public var decreasingColor: UIColor?
/// color for open > close
public var increasingColor: UIColor?
/// Are decreasing values drawn as filled?
public var decreasingFilled = false
/// Are increasing values drawn as filled?
public var increasingFilled = true
public override init(yVals: [ChartDataEntry]?, label: String?)
{
super.init(yVals: yVals, label: label);
}
internal override func calcMinMax(#start: Int, end: Int)
{
if (yVals.count == 0)
{
return;
}
var entries = yVals as! [CandleChartDataEntry];
var endValue : Int;
if end == 0
{
endValue = entries.count - 1;
}
else
{
endValue = end;
}
_lastStart = start;
_lastEnd = end;
_yMin = entries[start].low;
_yMax = entries[start].high;
for (var i = start + 1; i <= endValue; i++)
{
var e = entries[i];
if (e.low < _yMin)
{
_yMin = e.low;
}
if (e.high > _yMax)
{
_yMax = e.high;
}
}
}
/// the space that is left out on the left and right side of each candle,
/// :default: 0.1 (10%), max 0.45, min 0.0
public var bodySpace: CGFloat
{
set
{
_bodySpace = newValue;
if (_bodySpace < 0.0)
{
_bodySpace = 0.0;
}
if (_bodySpace > 0.45)
{
_bodySpace = 0.45;
}
}
get
{
return _bodySpace;
}
}
/// Are increasing values drawn as filled?
public var isIncreasingFilled: Bool { return increasingFilled; }
/// Are decreasing values drawn as filled?
public var isDecreasingFilled: Bool { return decreasingFilled; }
} | apache-2.0 | 931a23fdaeacdda49625adc41393f84a | 22.737288 | 77 | 0.513929 | 4.494382 | false | false | false | false |
cs4278-2015/tinderFood | tinderForFood/CustomFoodView.swift | 1 | 1353 | //
// CustomFoodView.swift
// tinderForFood
//
// Created by Edward Yun on 11/19/15.
// Copyright © 2015 Edward Yun. All rights reserved.
//
import UIKit
import Koloda
let defaultBottomOffset:CGFloat = 0
let defaultTopOffset:CGFloat = 20
let defaultHorizontalOffset:CGFloat = 10
let defaultHeightRatio:CGFloat = 1.25
let backgroundCardHorizontalMarginMultiplier:CGFloat = 0.25
let backgroundCardScalePercent:CGFloat = 1.5
class CustomFoodView: KolodaView {
override func frameForCardAtIndex(index: UInt) -> CGRect {
if index == 0 {
let topOffset:CGFloat = defaultTopOffset
let xOffset:CGFloat = defaultHorizontalOffset
let width = CGRectGetWidth(self.frame ) - 2 * defaultHorizontalOffset
let height = width * defaultHeightRatio
let yOffset:CGFloat = topOffset
let frame = CGRect(x: xOffset, y: yOffset, width: width, height: height)
return frame
} else if index == 1 {
let horizontalMargin = -self.bounds.width * backgroundCardHorizontalMarginMultiplier
let width = self.bounds.width * backgroundCardScalePercent
let height = width * defaultHeightRatio
return CGRect(x: horizontalMargin, y: 0, width: width, height: height)
}
return CGRectZero
}
}
| mit | 7b867665ae07f9fc82e7eb56c4c6f56d | 31.97561 | 96 | 0.669379 | 4.710801 | false | false | false | false |
svenbacia/TraktKit | TraktKit/Sources/Resource/Trakt/EpisodeResource.swift | 1 | 1519 | //
// EpisodeResource.swift
// TraktKit
//
// Created by Sven Bacia on 06.09.16.
// Copyright © 2016 Sven Bacia. All rights reserved.
//
import Foundation
public struct EpisodeResource {
// MARK: - Properties
private let basePath: String
private let configuration: Trakt.Configuration
// MARK: - Init
init(show: Int, season: Int, episode: Int, configuration: Trakt.Configuration) {
self.basePath = "/shows/\(show)/seasons/\(season)/episodes/\(episode)"
self.configuration = configuration
}
// MARK: - Endpoints
public func summary(_ extended: Extended? = nil) -> Resource<Episode> {
return buildResource(base: configuration.base, path: basePath, params: parameters(extended: extended))
}
public func comments(_ extended: Extended? = nil, page: Int? = nil, limit: Int? = nil) -> Resource<[Comment]> {
return buildResource(base: configuration.base, path: basePath + "/comments", params: parameters(page: page, limit: limit, extended: extended))
}
public func ratings() -> Resource<Ratings> {
return buildResource(base: configuration.base, path: basePath + "/ratings")
}
public func stats() -> Resource<Stats> {
return buildResource(base: configuration.base, path: basePath + "/stats")
}
public func watching(_ extended: Extended? = nil) -> Resource<[User]> {
return buildResource(base: configuration.base, path: basePath + "/watching", params: parameters(extended: extended))
}
}
| mit | 3ad302864aa906063e1a742b743ad25e | 32 | 150 | 0.666008 | 4.264045 | false | true | false | false |
natecook1000/swift | stdlib/public/core/CompilerProtocols.swift | 1 | 32427 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Intrinsic protocols shared with the compiler
//===----------------------------------------------------------------------===//
/// A type that can be converted to and from an associated raw value.
///
/// With a `RawRepresentable` type, you can switch back and forth between a
/// custom type and an associated `RawValue` type without losing the value of
/// the original `RawRepresentable` type. Using the raw value of a conforming
/// type streamlines interoperation with Objective-C and legacy APIs and
/// simplifies conformance to other protocols, such as `Equatable`,
/// `Comparable`, and `Hashable`.
///
/// The `RawRepresentable` protocol is seen mainly in two categories of types:
/// enumerations with raw value types and option sets.
///
/// Enumerations with Raw Values
/// ============================
///
/// For any enumeration with a string, integer, or floating-point raw type, the
/// Swift compiler automatically adds `RawRepresentable` conformance. When
/// defining your own custom enumeration, you give it a raw type by specifying
/// the raw type as the first item in the enumeration's type inheritance list.
/// You can also use literals to specify values for one or more cases.
///
/// For example, the `Counter` enumeration defined here has an `Int` raw value
/// type and gives the first case a raw value of `1`:
///
/// enum Counter: Int {
/// case one = 1, two, three, four, five
/// }
///
/// You can create a `Counter` instance from an integer value between 1 and 5
/// by using the `init?(rawValue:)` initializer declared in the
/// `RawRepresentable` protocol. This initializer is failable because although
/// every case of the `Counter` type has a corresponding `Int` value, there
/// are many `Int` values that *don't* correspond to a case of `Counter`.
///
/// for i in 3...6 {
/// print(Counter(rawValue: i))
/// }
/// // Prints "Optional(Counter.three)"
/// // Prints "Optional(Counter.four)"
/// // Prints "Optional(Counter.five)"
/// // Prints "nil"
///
/// Option Sets
/// ===========
///
/// Option sets all conform to `RawRepresentable` by inheritance using the
/// `OptionSet` protocol. Whether using an option set or creating your own,
/// you use the raw value of an option set instance to store the instance's
/// bitfield. The raw value must therefore be of a type that conforms to the
/// `FixedWidthInteger` protocol, such as `UInt8` or `Int`. For example, the
/// `Direction` type defines an option set for the four directions you can
/// move in a game.
///
/// struct Directions: OptionSet {
/// let rawValue: UInt8
///
/// static let up = Directions(rawValue: 1 << 0)
/// static let down = Directions(rawValue: 1 << 1)
/// static let left = Directions(rawValue: 1 << 2)
/// static let right = Directions(rawValue: 1 << 3)
/// }
///
/// Unlike enumerations, option sets provide a nonfailable `init(rawValue:)`
/// initializer to convert from a raw value, because option sets don't have an
/// enumerated list of all possible cases. Option set values have
/// a one-to-one correspondence with their associated raw values.
///
/// In the case of the `Directions` option set, an instance can contain zero,
/// one, or more of the four defined directions. This example declares a
/// constant with three currently allowed moves. The raw value of the
/// `allowedMoves` instance is the result of the bitwise OR of its three
/// members' raw values:
///
/// let allowedMoves: Directions = [.up, .down, .left]
/// print(allowedMoves.rawValue)
/// // Prints "7"
///
/// Option sets use bitwise operations on their associated raw values to
/// implement their mathematical set operations. For example, the `contains()`
/// method on `allowedMoves` performs a bitwise AND operation to check whether
/// the option set contains an element.
///
/// print(allowedMoves.contains(.right))
/// // Prints "false"
/// print(allowedMoves.rawValue & Directions.right.rawValue)
/// // Prints "0"
public protocol RawRepresentable {
/// The raw type that can be used to represent all values of the conforming
/// type.
///
/// Every distinct value of the conforming type has a corresponding unique
/// value of the `RawValue` type, but there may be values of the `RawValue`
/// type that don't have a corresponding value of the conforming type.
associatedtype RawValue
/// Creates a new instance with the specified raw value.
///
/// If there is no value of the type that corresponds with the specified raw
/// value, this initializer returns `nil`. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// print(PaperSize(rawValue: "Legal"))
/// // Prints "Optional("PaperSize.Legal")"
///
/// print(PaperSize(rawValue: "Tabloid"))
/// // Prints "nil"
///
/// - Parameter rawValue: The raw value to use for the new instance.
init?(rawValue: RawValue)
/// The corresponding value of the raw type.
///
/// A new instance initialized with `rawValue` will be equivalent to this
/// instance. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// let selectedSize = PaperSize.Letter
/// print(selectedSize.rawValue)
/// // Prints "Letter"
///
/// print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!)
/// // Prints "true"
var rawValue: RawValue { get }
}
/// Returns a Boolean value indicating whether the two arguments are equal.
///
/// - Parameters:
/// - lhs: A raw-representable instance.
/// - rhs: A second raw-representable instance.
@inlinable // FIXME(sil-serialize-all)
public func == <T : RawRepresentable>(lhs: T, rhs: T) -> Bool
where T.RawValue : Equatable {
return lhs.rawValue == rhs.rawValue
}
/// Returns a Boolean value indicating whether the two arguments are not equal.
///
/// - Parameters:
/// - lhs: A raw-representable instance.
/// - rhs: A second raw-representable instance.
@inlinable // FIXME(sil-serialize-all)
public func != <T : RawRepresentable>(lhs: T, rhs: T) -> Bool
where T.RawValue : Equatable {
return lhs.rawValue != rhs.rawValue
}
// This overload is needed for ambiguity resolution against the
// implementation of != for T : Equatable
/// Returns a Boolean value indicating whether the two arguments are not equal.
///
/// - Parameters:
/// - lhs: A raw-representable instance.
/// - rhs: A second raw-representable instance.
@inlinable // FIXME(sil-serialize-all)
public func != <T : Equatable>(lhs: T, rhs: T) -> Bool
where T : RawRepresentable, T.RawValue : Equatable {
return lhs.rawValue != rhs.rawValue
}
/// A type that provides a collection of all of its values.
///
/// Types that conform to the `CaseIterable` protocol are typically
/// enumerations without associated values. When using a `CaseIterable` type,
/// you can access a collection of all of the type's cases by using the type's
/// `allCases` property.
///
/// For example, the `CompassDirection` enumeration declared in this example
/// conforms to `CaseIterable`. You access the number of cases and the cases
/// themselves through `CompassDirection.allCases`.
///
/// enum CompassDirection: CaseIterable {
/// case north, south, east, west
/// }
///
/// print("There are \(CompassDirection.allCases.count) directions.")
/// // Prints "There are 4 directions."
/// let caseList = CompassDirection.allCases
/// .map({ "\($0)" })
/// .joined(separator: ", ")
/// // caseList == "north, south, east, west"
///
/// Conforming to the CaseIterable Protocol
/// =======================================
///
/// The compiler can automatically provide an implementation of the
/// `CaseIterable` requirements for any enumeration without associated values
/// or `@available` attributes on its cases. The synthesized `allCases`
/// collection provides the cases in order of their declaration.
///
/// You can take advantage of this compiler support when defining your own
/// custom enumeration by declaring conformance to `CaseIterable` in the
/// enumeration's original declaration. The `CompassDirection` example above
/// demonstrates this automatic implementation.
public protocol CaseIterable {
/// A type that can represent a collection of all values of this type.
associatedtype AllCases: Collection
where AllCases.Element == Self
/// A collection of all values of this type.
static var allCases: AllCases { get }
}
/// A type that can be initialized using the nil literal, `nil`.
///
/// `nil` has a specific meaning in Swift---the absence of a value. Only the
/// `Optional` type conforms to `ExpressibleByNilLiteral`.
/// `ExpressibleByNilLiteral` conformance for types that use `nil` for other
/// purposes is discouraged.
public protocol ExpressibleByNilLiteral {
/// Creates an instance initialized with `nil`.
init(nilLiteral: ())
}
public protocol _ExpressibleByBuiltinIntegerLiteral {
init(_builtinIntegerLiteral value: _MaxBuiltinIntegerType)
}
/// A type that can be initialized with an integer literal.
///
/// The standard library integer and floating-point types, such as `Int` and
/// `Double`, conform to the `ExpressibleByIntegerLiteral` protocol. You can
/// initialize a variable or constant of any of these types by assigning an
/// integer literal.
///
/// // Type inferred as 'Int'
/// let cookieCount = 12
///
/// // An array of 'Int'
/// let chipsPerCookie = [21, 22, 25, 23, 24, 19]
///
/// // A floating-point value initialized using an integer literal
/// let redPercentage: Double = 1
/// // redPercentage == 1.0
///
/// Conforming to ExpressibleByIntegerLiteral
/// =========================================
///
/// To add `ExpressibleByIntegerLiteral` conformance to your custom type,
/// implement the required initializer.
public protocol ExpressibleByIntegerLiteral {
/// A type that represents an integer literal.
///
/// The standard library integer and floating-point types are all valid types
/// for `IntegerLiteralType`.
associatedtype IntegerLiteralType : _ExpressibleByBuiltinIntegerLiteral
/// Creates an instance initialized to the specified integer value.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using an integer literal. For example:
///
/// let x = 23
///
/// In this example, the assignment to the `x` constant calls this integer
/// literal initializer behind the scenes.
///
/// - Parameter value: The value to create.
init(integerLiteral value: IntegerLiteralType)
}
public protocol _ExpressibleByBuiltinFloatLiteral {
init(_builtinFloatLiteral value: _MaxBuiltinFloatType)
}
/// A type that can be initialized with a floating-point literal.
///
/// The standard library floating-point types---`Float`, `Double`, and
/// `Float80` where available---all conform to the `ExpressibleByFloatLiteral`
/// protocol. You can initialize a variable or constant of any of these types
/// by assigning a floating-point literal.
///
/// // Type inferred as 'Double'
/// let threshold = 6.0
///
/// // An array of 'Double'
/// let measurements = [2.2, 4.1, 3.65, 4.2, 9.1]
///
/// Conforming to ExpressibleByFloatLiteral
/// =======================================
///
/// To add `ExpressibleByFloatLiteral` conformance to your custom type,
/// implement the required initializer.
public protocol ExpressibleByFloatLiteral {
/// A type that represents a floating-point literal.
///
/// Valid types for `FloatLiteralType` are `Float`, `Double`, and `Float80`
/// where available.
associatedtype FloatLiteralType : _ExpressibleByBuiltinFloatLiteral
/// Creates an instance initialized to the specified floating-point value.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using a floating-point literal. For example:
///
/// let x = 21.5
///
/// In this example, the assignment to the `x` constant calls this
/// floating-point literal initializer behind the scenes.
///
/// - Parameter value: The value to create.
init(floatLiteral value: FloatLiteralType)
}
public protocol _ExpressibleByBuiltinBooleanLiteral {
init(_builtinBooleanLiteral value: Builtin.Int1)
}
/// A type that can be initialized with the Boolean literals `true` and
/// `false`.
///
/// Only three types provided by Swift---`Bool`, `DarwinBoolean`, and
/// `ObjCBool`---are treated as Boolean values. Expanding this set to include
/// types that represent more than simple Boolean values is discouraged.
///
/// To add `ExpressibleByBooleanLiteral` conformance to your custom type,
/// implement the `init(booleanLiteral:)` initializer that creates an instance
/// of your type with the given Boolean value.
public protocol ExpressibleByBooleanLiteral {
/// A type that represents a Boolean literal, such as `Bool`.
associatedtype BooleanLiteralType : _ExpressibleByBuiltinBooleanLiteral
/// Creates an instance initialized to the given Boolean value.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using one of the Boolean literals `true` and `false`. For
/// example:
///
/// let twasBrillig = true
///
/// In this example, the assignment to the `twasBrillig` constant calls this
/// Boolean literal initializer behind the scenes.
///
/// - Parameter value: The value of the new instance.
init(booleanLiteral value: BooleanLiteralType)
}
public protocol _ExpressibleByBuiltinUnicodeScalarLiteral {
init(_builtinUnicodeScalarLiteral value: Builtin.Int32)
}
/// A type that can be initialized with a string literal containing a single
/// Unicode scalar value.
///
/// The `String`, `StaticString`, `Character`, and `Unicode.Scalar` types all
/// conform to the `ExpressibleByUnicodeScalarLiteral` protocol. You can
/// initialize a variable of any of these types using a string literal that
/// holds a single Unicode scalar.
///
/// let ñ: Unicode.Scalar = "ñ"
/// print(ñ)
/// // Prints "ñ"
///
/// Conforming to ExpressibleByUnicodeScalarLiteral
/// ===============================================
///
/// To add `ExpressibleByUnicodeScalarLiteral` conformance to your custom type,
/// implement the required initializer.
public protocol ExpressibleByUnicodeScalarLiteral {
/// A type that represents a Unicode scalar literal.
///
/// Valid types for `UnicodeScalarLiteralType` are `Unicode.Scalar`,
/// `Character`, `String`, and `StaticString`.
associatedtype UnicodeScalarLiteralType : _ExpressibleByBuiltinUnicodeScalarLiteral
/// Creates an instance initialized to the given value.
///
/// - Parameter value: The value of the new instance.
init(unicodeScalarLiteral value: UnicodeScalarLiteralType)
}
public protocol _ExpressibleByBuiltinUTF16ExtendedGraphemeClusterLiteral
: _ExpressibleByBuiltinExtendedGraphemeClusterLiteral {
init(
_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,
utf16CodeUnitCount: Builtin.Word)
}
public protocol _ExpressibleByBuiltinExtendedGraphemeClusterLiteral
: _ExpressibleByBuiltinUnicodeScalarLiteral {
init(
_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1)
}
/// A type that can be initialized with a string literal containing a single
/// extended grapheme cluster.
///
/// An *extended grapheme cluster* is a group of one or more Unicode scalar
/// values that approximates a single user-perceived character. Many
/// individual characters, such as "é", "김", and "🇮🇳", can be made up of
/// multiple Unicode scalar values. These code points are combined by
/// Unicode's boundary algorithms into extended grapheme clusters.
///
/// The `String`, `StaticString`, and `Character` types conform to the
/// `ExpressibleByExtendedGraphemeClusterLiteral` protocol. You can initialize
/// a variable or constant of any of these types using a string literal that
/// holds a single character.
///
/// let snowflake: Character = "❄︎"
/// print(snowflake)
/// // Prints "❄︎"
///
/// Conforming to ExpressibleByExtendedGraphemeClusterLiteral
/// =========================================================
///
/// To add `ExpressibleByExtendedGraphemeClusterLiteral` conformance to your
/// custom type, implement the required initializer.
public protocol ExpressibleByExtendedGraphemeClusterLiteral
: ExpressibleByUnicodeScalarLiteral {
/// A type that represents an extended grapheme cluster literal.
///
/// Valid types for `ExtendedGraphemeClusterLiteralType` are `Character`,
/// `String`, and `StaticString`.
associatedtype ExtendedGraphemeClusterLiteralType
: _ExpressibleByBuiltinExtendedGraphemeClusterLiteral
/// Creates an instance initialized to the given value.
///
/// - Parameter value: The value of the new instance.
init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType)
}
extension ExpressibleByExtendedGraphemeClusterLiteral
where ExtendedGraphemeClusterLiteralType == UnicodeScalarLiteralType {
@_transparent
public init(unicodeScalarLiteral value: ExtendedGraphemeClusterLiteralType) {
self.init(extendedGraphemeClusterLiteral: value)
}
}
public protocol _ExpressibleByBuiltinStringLiteral
: _ExpressibleByBuiltinExtendedGraphemeClusterLiteral {
init(
_builtinStringLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1)
}
public protocol _ExpressibleByBuiltinUTF16StringLiteral
: _ExpressibleByBuiltinStringLiteral {
init(
_builtinUTF16StringLiteral start: Builtin.RawPointer,
utf16CodeUnitCount: Builtin.Word)
}
public protocol _ExpressibleByBuiltinConstStringLiteral
: _ExpressibleByBuiltinExtendedGraphemeClusterLiteral {
init(_builtinConstStringLiteral constantString: Builtin.RawPointer)
}
public protocol _ExpressibleByBuiltinConstUTF16StringLiteral
: _ExpressibleByBuiltinConstStringLiteral {
init(_builtinConstUTF16StringLiteral constantUTF16String: Builtin.RawPointer)
}
/// A type that can be initialized with a string literal.
///
/// The `String` and `StaticString` types conform to the
/// `ExpressibleByStringLiteral` protocol. You can initialize a variable or
/// constant of either of these types using a string literal of any length.
///
/// let picnicGuest = "Deserving porcupine"
///
/// Conforming to ExpressibleByStringLiteral
/// ========================================
///
/// To add `ExpressibleByStringLiteral` conformance to your custom type,
/// implement the required initializer.
public protocol ExpressibleByStringLiteral
: ExpressibleByExtendedGraphemeClusterLiteral {
/// A type that represents a string literal.
///
/// Valid types for `StringLiteralType` are `String` and `StaticString`.
associatedtype StringLiteralType : _ExpressibleByBuiltinStringLiteral
/// Creates an instance initialized to the given string value.
///
/// - Parameter value: The value of the new instance.
init(stringLiteral value: StringLiteralType)
}
extension ExpressibleByStringLiteral
where StringLiteralType == ExtendedGraphemeClusterLiteralType {
@_transparent
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(stringLiteral: value)
}
}
/// A type that can be initialized using an array literal.
///
/// An array literal is a simple way of expressing a list of values. Simply
/// surround a comma-separated list of values, instances, or literals with
/// square brackets to create an array literal. You can use an array literal
/// anywhere an instance of an `ExpressibleByArrayLiteral` type is expected: as
/// a value assigned to a variable or constant, as a parameter to a method or
/// initializer, or even as the subject of a nonmutating operation like
/// `map(_:)` or `filter(_:)`.
///
/// Arrays, sets, and option sets all conform to `ExpressibleByArrayLiteral`,
/// and your own custom types can as well. Here's an example of creating a set
/// and an array using array literals:
///
/// let employeesSet: Set<String> = ["Amir", "Jihye", "Dave", "Alessia", "Dave"]
/// print(employeesSet)
/// // Prints "["Amir", "Dave", "Jihye", "Alessia"]"
///
/// let employeesArray: [String] = ["Amir", "Jihye", "Dave", "Alessia", "Dave"]
/// print(employeesArray)
/// // Prints "["Amir", "Jihye", "Dave", "Alessia", "Dave"]"
///
/// The `Set` and `Array` types each handle array literals in their own way to
/// create new instances. In this case, the newly created set drops the
/// duplicate value ("Dave") and doesn't maintain the order of the array
/// literal's elements. The new array, on the other hand, matches the order
/// and number of elements provided.
///
/// - Note: An array literal is not the same as an `Array` instance. You can't
/// initialize a type that conforms to `ExpressibleByArrayLiteral` simply by
/// assigning an existing array.
///
/// let anotherSet: Set = employeesArray
/// // error: cannot convert value of type '[String]' to specified type 'Set'
///
/// Type Inference of Array Literals
/// ================================
///
/// Whenever possible, Swift's compiler infers the full intended type of your
/// array literal. Because `Array` is the default type for an array literal,
/// without writing any other code, you can declare an array with a particular
/// element type by providing one or more values.
///
/// In this example, the compiler infers the full type of each array literal.
///
/// let integers = [1, 2, 3]
/// // 'integers' has type '[Int]'
///
/// let strings = ["a", "b", "c"]
/// // 'strings' has type '[String]'
///
/// An empty array literal alone doesn't provide enough information for the
/// compiler to infer the intended type of the `Array` instance. When using an
/// empty array literal, specify the type of the variable or constant.
///
/// var emptyArray: [Bool] = []
/// // 'emptyArray' has type '[Bool]'
///
/// Because many functions and initializers fully specify the types of their
/// parameters, you can often use an array literal with or without elements as
/// a parameter. For example, the `sum(_:)` function shown here takes an `Int`
/// array as a parameter:
///
/// func sum(values: [Int]) -> Int {
/// return values.reduce(0, +)
/// }
///
/// let sumOfFour = sum([5, 10, 15, 20])
/// // 'sumOfFour' == 50
///
/// let sumOfNone = sum([])
/// // 'sumOfNone' == 0
///
/// When you call a function that does not fully specify its parameters' types,
/// use the type-cast operator (`as`) to specify the type of an array literal.
/// For example, the `log(name:value:)` function shown here has an
/// unconstrained generic `value` parameter.
///
/// func log<T>(name name: String, value: T) {
/// print("\(name): \(value)")
/// }
///
/// log(name: "Four integers", value: [5, 10, 15, 20])
/// // Prints "Four integers: [5, 10, 15, 20]"
///
/// log(name: "Zero integers", value: [] as [Int])
/// // Prints "Zero integers: []"
///
/// Conforming to ExpressibleByArrayLiteral
/// =======================================
///
/// Add the capability to be initialized with an array literal to your own
/// custom types by declaring an `init(arrayLiteral:)` initializer. The
/// following example shows the array literal initializer for a hypothetical
/// `OrderedSet` type, which has setlike semantics but maintains the order of
/// its elements.
///
/// struct OrderedSet<Element: Hashable>: Collection, SetAlgebra {
/// // implementation details
/// }
///
/// extension OrderedSet: ExpressibleByArrayLiteral {
/// init(arrayLiteral: Element...) {
/// self.init()
/// for element in arrayLiteral {
/// self.append(element)
/// }
/// }
/// }
public protocol ExpressibleByArrayLiteral {
/// The type of the elements of an array literal.
associatedtype ArrayLiteralElement
/// Creates an instance initialized with the given elements.
init(arrayLiteral elements: ArrayLiteralElement...)
}
/// A type that can be initialized using a dictionary literal.
///
/// A dictionary literal is a simple way of writing a list of key-value pairs.
/// You write each key-value pair with a colon (`:`) separating the key and
/// the value. The dictionary literal is made up of one or more key-value
/// pairs, separated by commas and surrounded with square brackets.
///
/// To declare a dictionary, assign a dictionary literal to a variable or
/// constant:
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana",
/// "JP": "Japan", "US": "United States"]
/// // 'countryCodes' has type [String: String]
///
/// print(countryCodes["BR"]!)
/// // Prints "Brazil"
///
/// When the context provides enough type information, you can use a special
/// form of the dictionary literal, square brackets surrounding a single
/// colon, to initialize an empty dictionary.
///
/// var frequencies: [String: Int] = [:]
/// print(frequencies.count)
/// // Prints "0"
///
/// - Note:
/// A dictionary literal is *not* the same as an instance of `Dictionary`.
/// You can't initialize a type that conforms to `ExpressibleByDictionaryLiteral`
/// simply by assigning an instance of `Dictionary`, `KeyValuePairs`, or similar.
///
/// Conforming to the ExpressibleByDictionaryLiteral Protocol
/// =========================================================
///
/// To add the capability to be initialized with a dictionary literal to your
/// own custom types, declare an `init(dictionaryLiteral:)` initializer. The
/// following example shows the dictionary literal initializer for a
/// hypothetical `CountedSet` type, which uses setlike semantics while keeping
/// track of the count for duplicate elements:
///
/// struct CountedSet<Element: Hashable>: Collection, SetAlgebra {
/// // implementation details
///
/// /// Updates the count stored in the set for the given element,
/// /// adding the element if necessary.
/// ///
/// /// - Parameter n: The new count for `element`. `n` must be greater
/// /// than or equal to zero.
/// /// - Parameter element: The element to set the new count on.
/// mutating func updateCount(_ n: Int, for element: Element)
/// }
///
/// extension CountedSet: ExpressibleByDictionaryLiteral {
/// init(dictionaryLiteral elements: (Element, Int)...) {
/// self.init()
/// for (element, count) in elements {
/// self.updateCount(count, for: element)
/// }
/// }
/// }
public protocol ExpressibleByDictionaryLiteral {
/// The key type of a dictionary literal.
associatedtype Key
/// The value type of a dictionary literal.
associatedtype Value
/// Creates an instance initialized with the given key-value pairs.
init(dictionaryLiteral elements: (Key, Value)...)
}
/// A type that can be initialized by string interpolation with a string
/// literal that includes expressions.
///
/// Use string interpolation to include one or more expressions in a string
/// literal, wrapped in a set of parentheses and prefixed by a backslash. For
/// example:
///
/// let price = 2
/// let number = 3
/// let message = "One cookie: $\(price), \(number) cookies: $\(price * number)."
/// print(message)
/// // Prints "One cookie: $2, 3 cookies: $6."
///
/// Conforming to the ExpressibleByStringInterpolation Protocol
/// ===========================================================
///
/// The `ExpressibleByStringInterpolation` protocol is deprecated. Do not add
/// new conformances to the protocol.
@available(*, deprecated, message: "it will be replaced or redesigned in Swift 5.0. Instead of conforming to 'ExpressibleByStringInterpolation', consider adding an 'init(_:String)'")
public typealias ExpressibleByStringInterpolation = _ExpressibleByStringInterpolation
public protocol _ExpressibleByStringInterpolation {
/// Creates an instance by concatenating the given values.
///
/// Do not call this initializer directly. It is used by the compiler when
/// you use string interpolation. For example:
///
/// let s = "\(5) x \(2) = \(5 * 2)"
/// print(s)
/// // Prints "5 x 2 = 10"
///
/// After calling `init(stringInterpolationSegment:)` with each segment of
/// the string literal, this initializer is called with their string
/// representations.
///
/// - Parameter strings: An array of instances of the conforming type.
init(stringInterpolation strings: Self...)
/// Creates an instance containing the appropriate representation for the
/// given value.
///
/// Do not call this initializer directly. It is used by the compiler for
/// each string interpolation segment when you use string interpolation. For
/// example:
///
/// let s = "\(5) x \(2) = \(5 * 2)"
/// print(s)
/// // Prints "5 x 2 = 10"
///
/// This initializer is called five times when processing the string literal
/// in the example above; once each for the following: the integer `5`, the
/// string `" x "`, the integer `2`, the string `" = "`, and the result of
/// the expression `5 * 2`.
///
/// - Parameter expr: The expression to represent.
init<T>(stringInterpolationSegment expr: T)
}
/// A type that can be initialized using a color literal (e.g.
/// `#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1)`).
public protocol _ExpressibleByColorLiteral {
/// Creates an instance initialized with the given properties of a color
/// literal.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using a color literal.
init(_colorLiteralRed red: Float, green: Float, blue: Float, alpha: Float)
}
/// A type that can be initialized using an image literal (e.g.
/// `#imageLiteral(resourceName: "hi.png")`).
public protocol _ExpressibleByImageLiteral {
/// Creates an instance initialized with the given resource name.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using an image literal.
init(imageLiteralResourceName path: String)
}
/// A type that can be initialized using a file reference literal (e.g.
/// `#fileLiteral(resourceName: "resource.txt")`).
public protocol _ExpressibleByFileReferenceLiteral {
/// Creates an instance initialized with the given resource name.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using a file reference literal.
init(fileReferenceLiteralResourceName path: String)
}
/// A container is destructor safe if whether it may store to memory on
/// destruction only depends on its type parameters destructors.
/// For example, whether `Array<Element>` may store to memory on destruction
/// depends only on `Element`.
/// If `Element` is an `Int` we know the `Array<Int>` does not store to memory
/// during destruction. If `Element` is an arbitrary class
/// `Array<MemoryUnsafeDestructorClass>` then the compiler will deduce may
/// store to memory on destruction because `MemoryUnsafeDestructorClass`'s
/// destructor may store to memory on destruction.
/// If in this example during `Array`'s destructor we would call a method on any
/// type parameter - say `Element.extraCleanup()` - that could store to memory,
/// then Array would no longer be a _DestructorSafeContainer.
public protocol _DestructorSafeContainer {
}
| apache-2.0 | 6e907c0367dbc379514ab60f587006c6 | 39.156134 | 183 | 0.681016 | 4.643359 | false | false | false | false |
nakau1/wikipedia_app | Wikipedia/Classes/Cores/AppDelegate.swift | 1 | 704 | // =============================================================================
// wikipedia app
// Copyright (C) 2015年 NeroBlu. All rights reserved.
// =============================================================================
import UIKit
/// アプリケーションデリゲート
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
let window = UIWindow(frame: UIScreen.mainScreen().bounds)
window.rootViewController = MainViewController()
window.makeKeyAndVisible()
self.window = window
return true
}
}
| apache-2.0 | 6f4687d161a3647f83fd3a87dce6454a | 29.727273 | 122 | 0.585799 | 5.540984 | false | false | false | false |
danielgindi/ChartsRealm | ChartsRealm/Classes/Data/RealmLineDataSet.swift | 1 | 5735 | //
// RealmLineDataSet.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import Charts
import Realm
import Realm.Dynamic
open class RealmLineDataSet: RealmLineRadarDataSet, ILineChartDataSet
{
open override func initialize()
{
circleColors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0))
}
// MARK: - Data functions and accessors
// MARK: - Styling functions and accessors
/// The drawing mode for this line dataset
///
/// **default**: Linear
open var mode: LineChartDataSet.Mode = LineChartDataSet.Mode.linear
fileprivate var _cubicIntensity = CGFloat(0.2)
/// Intensity for cubic lines (min = 0.05, max = 1)
///
/// **default**: 0.2
open var cubicIntensity: CGFloat
{
get
{
return _cubicIntensity
}
set
{
_cubicIntensity = newValue
if _cubicIntensity > 1.0
{
_cubicIntensity = 1.0
}
if _cubicIntensity < 0.05
{
_cubicIntensity = 0.05
}
}
}
@available(*, deprecated, message: "Use `mode` instead.")
open var drawCubicEnabled: Bool
{
get
{
return mode == .cubicBezier
}
set
{
mode = newValue ? LineChartDataSet.Mode.cubicBezier : LineChartDataSet.Mode.linear
}
}
@available(*, deprecated, message: "Use `mode` instead.")
open var isDrawCubicEnabled: Bool { return drawCubicEnabled }
@available(*, deprecated, message: "Use `mode` instead.")
open var drawSteppedEnabled: Bool
{
get
{
return mode == .stepped
}
set
{
mode = newValue ? LineChartDataSet.Mode.stepped : LineChartDataSet.Mode.linear
}
}
@available(*, deprecated, message: "Use `mode` instead.")
open var isDrawSteppedEnabled: Bool { return drawSteppedEnabled }
/// The radius of the drawn circles.
open var circleRadius = CGFloat(8.0)
/// The hole radius of the drawn circles
open var circleHoleRadius = CGFloat(4.0)
open var circleColors = [NSUIColor]()
/// - returns: The color at the given index of the DataSet's circle-color array.
/// Performs a IndexOutOfBounds check by modulus.
open func getCircleColor(atIndex index: Int) -> NSUIColor?
{
let size = circleColors.count
let index = index % size
if index >= size
{
return nil
}
return circleColors[index]
}
/// Sets the one and ONLY color that should be used for this DataSet.
/// Internally, this recreates the colors array and adds the specified color.
open func setCircleColor(_ color: NSUIColor)
{
circleColors.removeAll(keepingCapacity: false)
circleColors.append(color)
}
/// Resets the circle-colors array and creates a new one
open func resetCircleColors(_ index: Int)
{
circleColors.removeAll(keepingCapacity: false)
}
/// If true, drawing circles is enabled
open var drawCirclesEnabled = true
/// - returns: `true` if drawing circles for this DataSet is enabled, `false` ifnot
open var isDrawCirclesEnabled: Bool { return drawCirclesEnabled }
/// The color of the inner circle (the circle-hole).
open var circleHoleColor: NSUIColor? = NSUIColor.white
/// `true` if drawing circles for this DataSet is enabled, `false` ifnot
open var drawCircleHoleEnabled = true
/// - returns: `true` if drawing the circle-holes is enabled, `false` ifnot.
open var isDrawCircleHoleEnabled: Bool { return drawCircleHoleEnabled }
/// This is how much (in pixels) into the dash pattern are we starting from.
open var lineDashPhase = CGFloat(0.0)
/// This is the actual dash pattern.
/// I.e. [2, 3] will paint [-- -- ]
/// [1, 3, 4, 2] will paint [- ---- - ---- ]
open var lineDashLengths: [CGFloat]?
/// Line cap type, default is CGLineCap.Butt
open var lineCapType = CGLineCap.butt
/// formatter for customizing the position of the fill-line
fileprivate var _fillFormatter: IFillFormatter = DefaultFillFormatter()
/// Sets a custom IFillFormatter to the chart that handles the position of the filled-line for each DataSet. Set this to null to use the default logic.
open var fillFormatter: IFillFormatter?
{
get
{
return _fillFormatter
}
set
{
if newValue == nil
{
_fillFormatter = DefaultFillFormatter()
}
else
{
_fillFormatter = newValue!
}
}
}
// MARK: NSCopying
open override func copy(with zone: NSZone? = nil) -> Any
{
let copy = super.copy(with: zone) as! RealmLineDataSet
copy.circleRadius = circleRadius
copy.circleHoleRadius = circleHoleRadius
copy.circleColors = circleColors
copy.circleRadius = circleRadius
copy.cubicIntensity = cubicIntensity
copy.lineDashPhase = lineDashPhase
copy.lineDashLengths = lineDashLengths
copy.lineCapType = lineCapType
copy.drawCirclesEnabled = drawCirclesEnabled
copy.drawCircleHoleEnabled = drawCircleHoleEnabled
copy.mode = mode
return copy
}
}
| apache-2.0 | ac28bba139c3d9907a41d7444a2918a2 | 28.715026 | 155 | 0.601918 | 4.918525 | false | false | false | false |
mssun/passforios | passKit/Parser/TokenBuilder.swift | 2 | 3515 | //
// TokenBuilder.swift
// passKit
//
// Created by Danny Moesch on 01.12.18.
// Copyright © 2018 Bob Sun. All rights reserved.
//
import Base32
import OneTimePassword
/// Help building an OTP token from given data.
///
/// There is currently support for TOTP and HOTP tokens:
///
/// * Necessary TOTP data
/// * secret: `secretsecretsecretsecretsecretsecret`
/// * type: `totp`
/// * algorithm: `sha1` (default: `sha1`, optional)
/// * period: `30` (default: `30`, optional)
/// * digits: `6` (default: `6`, optional)
///
/// * Necessary HOTP data
/// * secret: `secretsecretsecretsecretsecretsecret`
/// * type: `hotp`
/// * counter: `1`
/// * digits: `6` (default: `6`, optional)
///
class TokenBuilder {
private var name: String = ""
private var secret: Data?
private var type: OTPType = .totp
private var algorithm: Generator.Algorithm = .sha1
private var digits: Int? = Constants.DEFAULT_DIGITS
private var period: Double? = Constants.DEFAULT_PERIOD
private var counter: UInt64? = Constants.DEFAULT_COUNTER
private var representation: OneTimePassword.Generator.Representation = Constants.DEFAULT_REPRESENTATION
func usingName(_ name: String) -> TokenBuilder {
self.name = name
return self
}
func usingSecret(_ secret: String?) -> TokenBuilder {
if secret != nil, let secretData = MF_Base32Codec.data(fromBase32String: secret!), !secretData.isEmpty {
self.secret = secretData
}
return self
}
func usingType(_ type: String?) -> TokenBuilder {
self.type = OTPType(name: type)
return self
}
func usingAlgorithm(_ algorithm: String?) -> TokenBuilder {
switch algorithm?.lowercased() {
case Constants.SHA256:
self.algorithm = .sha256
case Constants.SHA512:
self.algorithm = .sha512
default:
self.algorithm = .sha1
}
return self
}
func usingDigits(_ digits: String?) -> TokenBuilder {
self.digits = digits == nil ? nil : Int(digits!)
return self
}
func usingPeriod(_ period: String?) -> TokenBuilder {
self.period = period == nil ? nil : Double(period!)
return self
}
func usingCounter(_ counter: String?) -> TokenBuilder {
self.counter = counter == nil ? nil : UInt64(counter!)
return self
}
func usingRepresentation(_ representation: String?) -> TokenBuilder {
switch representation {
case "numeric":
self.representation = .numeric
case "steamguard":
self.representation = .steamguard
default:
self.representation = .numeric
}
return self
}
func build() -> Token? {
guard secret != nil, digits != nil else {
return nil
}
switch type {
case .totp:
return period == nil ? nil : createToken(factor: Generator.Factor.timer(period: period!))
case .hotp:
return counter == nil ? nil : createToken(factor: Generator.Factor.counter(counter!))
default:
return nil
}
}
private func createToken(factor: Generator.Factor) -> Token? {
guard let generator = Generator(factor: factor, secret: secret!, algorithm: algorithm, digits: digits!, representation: representation) else {
return nil
}
return Token(name: name, issuer: "", generator: generator)
}
}
| mit | 067f52f232bccdfe6849f832719fe7fe | 29.293103 | 150 | 0.605009 | 4.269745 | false | false | false | false |
matfur92/SwiftMongoDB | swiftMongoDB/MongoCollection.swift | 1 | 6493 | //
// MongoCollection.swift
// swiftMongoDB
//
// Created by Dan Appel on 8/20/15.
// Copyright © 2015 Dan Appel. All rights reserved.
//
public class MongoCollection {
public let client: MongoClient
public let collectionName: String
let clientRAW: _mongoc_client
let collectionRAW: _mongoc_collection
public init(collectionName: String, client: MongoClient) {
self.client = client
self.clientRAW = client.clientRAW
self.collectionName = collectionName
self.collectionRAW = mongoc_client_get_collection(self.clientRAW, self.client.databaseName, self.collectionName)
}
deinit {
mongoc_collection_destroy(self.collectionRAW)
}
private func cursor(operation operation: MongoCursorOperation, query: _bson_ptr_mutable, options: (queryFlags: mongoc_query_flags_t, skip: Int, limit: Int, batchSize: Int)) -> MongoCursor {
// ugh so ugly
return MongoCursor(collection: self, operation: operation, query: query, options: (queryFlags: options.queryFlags, skip: options.skip, limit: options.limit, batchSize: options.batchSize))
}
public enum InsertFlags {
case None
case ContinueOnError
}
public func insert(document: MongoDocument, flags: InsertFlags = InsertFlags.None) throws {
let insertFlags: mongoc_insert_flags_t
switch flags {
case .None: insertFlags = MONGOC_INSERT_NONE
case .ContinueOnError: insertFlags = MONGOC_INSERT_CONTINUE_ON_ERROR
}
var bsonError = bson_error_t()
mongoc_collection_insert(self.collectionRAW, insertFlags, document.BSONRAW, nil, &bsonError)
if bsonError.error.isError {
throw bsonError.error
}
}
public func insert(document: DocumentData, containsObjectId: Bool = false, flags: InsertFlags = InsertFlags.None) throws {
try self.insert(MongoDocument(data: document), flags: flags)
}
public func renameCollectionTo(newName : String) throws{
var bsonError = bson_error_t()
mongoc_collection_rename(self.collectionRAW, client.databaseName, newName, false, &bsonError)
if bsonError.error.isError {
throw bsonError.error
}
}
public func find(query: DocumentData = DocumentData(), flags: QueryFlags = QueryFlags.None, skip: Int = 0, limit: Int = 0, batchSize: Int = 0) throws -> [MongoDocument] {
var queryBSON = bson_t()
try! MongoBSONEncoder(data: query).copyTo(&queryBSON)
// standard options - should be customizable later on
let cursor = self.cursor(operation: .Find, query: &queryBSON, options: (queryFlags: flags.rawFlag, skip: skip, limit: skip, batchSize: skip))
var outputDocuments = [MongoDocument]()
while cursor.nextIsOK {
guard let nextDocument = cursor.nextDocument else {
throw MongoError.CorruptDocument
}
outputDocuments.append(nextDocument)
}
if cursor.lastError.isError {
throw cursor.lastError
}
return outputDocuments
}
public func findOne(query: DocumentData = DocumentData(), flags: QueryFlags = QueryFlags.None, skip: Int = 0, limit: Int = 0, batchSize: Int = 0) throws -> MongoDocument? {
let queryBSON = try! MongoBSONEncoder(data: query).BSONRAW
let queryFlags: mongoc_query_flags_t = flags.rawFlag
// standard options - should be customizable later on
let cursor = self.cursor(operation: .Find, query: queryBSON, options: (queryFlags: queryFlags, skip: skip, limit: skip, batchSize: skip))
if cursor.nextIsOK {
guard let nextDocument = cursor.nextDocument else {
throw MongoError.CorruptDocument
}
return nextDocument
}
return nil
}
public enum UpdateFlags {
case None
case Upsert
case MultiUpdate
internal var rawFlag: mongoc_update_flags_t {
switch self {
case .None: return MONGOC_UPDATE_NONE
case .Upsert: return MONGOC_UPDATE_UPSERT
case .MultiUpdate: return MONGOC_UPDATE_MULTI_UPDATE
}
}
}
public func update(query: DocumentData = DocumentData(), newValue: DocumentData, flags: UpdateFlags = UpdateFlags.None) throws -> Bool {
let updateFlags: mongoc_update_flags_t = flags.rawFlag
var queryBSON = bson_t()
try MongoBSONEncoder(data: query).copyTo(&queryBSON)
var documentBSON = bson_t()
try MongoBSONEncoder(data: newValue).copyTo(&documentBSON)
var error = bson_error_t()
let success = mongoc_collection_update(self.collectionRAW, updateFlags, &queryBSON, &documentBSON, nil, &error)
if error.error.isError {
throw error.error
}
return success
}
public enum RemoveFlags {
case None
case SingleRemove
}
public func remove(query: DocumentData = DocumentData(), flags: RemoveFlags = RemoveFlags.None) throws -> Bool {
let removeFlags: mongoc_remove_flags_t
switch flags {
case .None: removeFlags = MONGOC_REMOVE_NONE; break
case .SingleRemove: removeFlags = MONGOC_REMOVE_SINGLE_REMOVE; break
}
var queryBSON = bson_t()
try! MongoBSONEncoder(data: query).copyTo(&queryBSON)
var error = bson_error_t()
let success = mongoc_collection_remove(self.collectionRAW, removeFlags, &queryBSON, nil, &error)
if error.error.isError {
throw error.error
}
return success
}
public func performBasicCollectionCommand(command: DocumentData) throws -> DocumentData {
var commandRAW = bson_t()
try MongoBSONEncoder(data: command).copyTo(&commandRAW)
var reply = bson_t()
var error = bson_error_t()
mongoc_collection_command_simple(self.collectionRAW, &commandRAW, nil, &reply, &error)
if error.error.isError {
throw error.error
}
return try MongoBSONDecoder(BSON: &reply).result.data
// mongoc_collection_command_simple(collection: COpaquePointer, command: UnsafePointer<bson_t>, read_prefs: COpaquePointer, reply: UnsafeMutablePointer<bson_t>, error: UnsafeMutablePointer<bson_error_t>)
}
}
| mit | adcc38e93010dba9873cda24d33e6841 | 31.954315 | 210 | 0.639402 | 4.207388 | false | false | false | false |
ttlock/iOS_TTLock_Demo | Pods/iOSDFULibrary/iOSDFULibrary/Classes/Utilities/Streams/DFUStreamBin.swift | 2 | 3325 | /*
* Copyright (c) 2016, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
internal class DFUStreamBin : DFUStream {
private(set) var currentPart = 1
private(set) var parts = 1
private(set) var currentPartType: UInt8 = 0
/// Firmware binaries
private var binaries: Data
/// The init packet content
private var initPacketBinaries: Data?
private var firmwareSize: UInt32 = 0
var size: DFUFirmwareSize {
switch currentPartType {
case FIRMWARE_TYPE_SOFTDEVICE:
return DFUFirmwareSize(softdevice: firmwareSize, bootloader: 0, application: 0)
case FIRMWARE_TYPE_BOOTLOADER:
return DFUFirmwareSize(softdevice: 0, bootloader: firmwareSize, application: 0)
// case FIRMWARE_TYPE_APPLICATION:
default:
return DFUFirmwareSize(softdevice: 0, bootloader: 0, application: firmwareSize)
}
}
var currentPartSize: DFUFirmwareSize {
return size
}
init(urlToBinFile: URL, urlToDatFile: URL?, type: DFUFirmwareType) {
binaries = try! Data(contentsOf: urlToBinFile)
firmwareSize = UInt32(binaries.count)
if let dat = urlToDatFile {
initPacketBinaries = try? Data(contentsOf: dat)
}
currentPartType = type.rawValue
}
init(binFile: Data, datFile: Data?, type: DFUFirmwareType) {
binaries = binFile
firmwareSize = UInt32(binaries.count)
initPacketBinaries = datFile
currentPartType = type.rawValue
}
var data: Data {
return binaries
}
var initPacket: Data? {
return initPacketBinaries
}
func hasNextPart() -> Bool {
return false
}
func switchToNextPart() {
// do nothing
}
}
| mit | d9e2b1c94acdf6efd4ebec5077a23819 | 37.218391 | 144 | 0.695038 | 5.076336 | false | false | false | false |
CoolCodeFactory/Antidote | AntidoteArchitectureExample/UsersTableViewController.swift | 1 | 3780 | //
// UsersTableViewController.swift
// AntidoteArchitectureExample
//
// Created by Dmitriy Utmanov on 16/09/16.
// Copyright © 2016 Dmitry Utmanov. All rights reserved.
//
import UIKit
protocol UsersTableViewControllerProtocol: class {
var selectUserHandler: (String) -> () { get set }
}
extension UsersTableViewControllerProtocol {
func viewController() -> UIViewController? {
let vc = self as? UIViewController
return vc
}
}
class UsersTableViewController: UITableViewController, UsersTableViewControllerProtocol {
var selectUserHandler: (String) -> () = { _ in fatalError() }
var controllerCloseHandler: () -> () = { }
deinit {
print("Deinit: \(self)")
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if isMovingFromParentViewController {
controllerCloseHandler()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
selectUserHandler(cell.textLabel!.text!)
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 07b538b505fc0e5986b3e754c355c3bb | 30.756303 | 157 | 0.677428 | 5.516788 | false | false | false | false |
gkye/TheMovieDatabaseSwiftWrapper | Sources/TMDBSwift/Models/Image.swift | 1 | 1655 | import Foundation
/// A stucture representing an image and it's attributes.
public struct Image: Codable, Equatable {
/// The image file path.
///
/// To build an image URL, you will need 3 pieces of data. The `base_url`, `size` and `file_path`. Simply combine them all and you will have a fully qualified URL.
///
/// Here’s an example URL:
/// ```
/// https://image.tmdb.org/t/p/w500/8uO0gUM8aNqYLs1OsTBQiXu0fEv.jpg
/// ```
///
public var filePath: String
/// The aspect ratio.
public var aspectRatio: Double?
/// The height.
public var height: Int?
/// The language, if any.
public var language: Language?
/// The average voting score.
public var voteAverage: Double?
/// The total vote count.
public var voteCount: Int?
/// The width.
public var width: Int?
enum CodingKeys: String, CodingKey {
case filePath = "file_path"
case aspectRatio = "aspect_ratio"
case height
case language = "iso_639_1"
case voteAverage = "vote_average"
case voteCount = "vote_count"
case width
}
public init(filePath: String,
aspectRatio: Double? = nil,
height: Int? = nil,
language: Language? = nil,
voteAverage: Double? = nil,
voteCount: Int? = nil,
width: Int? = nil) {
self.filePath = filePath
self.aspectRatio = aspectRatio
self.height = height
self.language = language
self.voteAverage = voteAverage
self.voteCount = voteCount
self.width = width
}
}
| mit | 8caa382df223c70479590835c7d79d27 | 30.188679 | 167 | 0.583182 | 4.18481 | false | false | false | false |
AndreMuis/Algorithms | SortedArrayToBinarySearchTree.playground/Contents.swift | 1 | 1269 | //
// Convert a sorted array to a binary search tree with minimal height
//
import Foundation
class Node
{
var number : Int
var left : Node?
var right : Node?
init(number : Int)
{
self.number = number
self.left = nil
self.right = nil
}
}
func createBinarySearchTree(numbers numbers : [Int], start : Int, end : Int) -> Node?
{
if (start > end)
{
return nil
}
let median : Int = (start + end) / 2
let node : Node = Node(number: numbers[median])
node.left = createBinarySearchTree(numbers: numbers, start: start, end: median - 1)
node.right = createBinarySearchTree(numbers: numbers, start: median + 1, end: end)
return node
}
func printBinarySearchTree(rootNode rootNode : Node?)
{
if let root = rootNode
{
print("number: \(root.number) left: \(root.left?.number) right: \(root.right?.number)")
printBinarySearchTree(rootNode: root.left)
printBinarySearchTree(rootNode: root.right)
}
else
{
return
}
}
let numbers : [Int] = [3, 4, 7, 9, 13, 22, 23, 30]
let rootNode = createBinarySearchTree(numbers: numbers, start: 0, end: numbers.count - 1)
printBinarySearchTree(rootNode: rootNode)
| mit | f8db54e7b978aff62bf15a8c48da6d4c | 19.467742 | 95 | 0.611505 | 3.78806 | false | false | false | false |
ALiOSDev/ALTableView | ALTableViewSwift/TestALTableView/TestALTableView/MasterViewController.swift | 1 | 6511 | //
// MasterViewController.swift
// ALTableView
//
// Created by lorenzo villarroel perez on 7/3/18.
// Copyright © 2018 lorenzo villarroel perez. All rights reserved.
//
import UIKit
import ALTableView
class MasterViewController: UITableViewController, ALTableViewProtocol {
var detailViewController: DetailViewController? = nil
var alTableView: ALTableView?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if let split = splitViewController {
let controllers = split.viewControllers
detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
self.tableView.tableFooterView = UIView()
let sectionElements = self.createElements()
self.alTableView = ALTableView(sectionElements: [ALSectionElement](), viewController: self, tableView: self.tableView)
self.alTableView?.delegate = self
self.registerCells()
self.alTableView?.replaceAllSections(sectionElements: sectionElements)
// self.tableView.reloadData()
self.navigationItem.leftBarButtonItem = self.editButtonItem;
self.alTableView?.addPullToRefresh(title: NSAttributedString(string: "Refreshing..."), backgroundColor: .green, tintColor: .blue)
}
override func viewWillAppear(_ animated: Bool) {
clearsSelectionOnViewWillAppear = splitViewController!.isCollapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
// if let indexPath = tableView.indexPathForSelectedRow {
// let object = objects[indexPath.row] as! NSDate
// let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
// controller.detailItem = object
// controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
// controller.navigationItem.leftItemsSupplementBackButton = true
// }
}
}
func createElements() -> [ALSectionElement] {
var sectionElements = [ALSectionElement]()
var rowElements = Array<ALRowElement>()
for _ in 0...8 {
let rowElement = ALRowElement(className:MasterTableViewCell.classForCoder(), identifier: MasterTableViewCell.reuseIdentifier, dataObject: "Texto 1Texto 1Texto 1Texto 1Texto 1Texto 1Texto 1Texto 1Texto 1Texto 1Texto 1Texto 1Texto 1Texto 1Texto 1Texto 1", estimateHeightMode: true, editingAllowed: true)
let rowElement2 = ALRowElement(className:Master2TableViewCell.classForCoder(), identifier: Master2TableViewCell.reuseIdentifier, dataObject: 12, estimateHeightMode: true)
rowElements.append(rowElement)
rowElements.append(rowElement2)
}
let headerElement = ALHeaderFooterElement(identifier: MasterHeaderFooter.reuseIdentifier, dataObject: "Header Test", estimateHeightMode: true)
let section = ALSectionElement(rowElements: rowElements, headerElement: headerElement, footerElement: nil, isExpandable: true)
sectionElements.append(section)
// sectionElements.append(ALSectionElement(rowElements: [ALRowElement](), headerElement: nil, footerElement: nil, isExpandable: true))
return sectionElements
}
// func createElements() -> [ALSectionElement] {
// var sectionElements = [ALSectionElement]()
// var rowElements = Array<ALRowElement>()
// for i in 0...8 {
// let element = OrderElement(orderId: TextStyles.ordersElement(text: "\(i)"),
// orderAmount: TextStyles.ordersElement(text: "\(i)\(i)\(i)"),
// orderCreationDate: Date(),
// orderStatus: TextStyles.ordersElement(text: "status \(i)\(i)\(i)"),
// delegate: nil)
//
// let rowElement = ALRowElement(className: OrdersTableViewCell.classForCoder(),
// identifier: OrdersTableViewCell.reuseIdentifier,
// dataObject: element,
// estimateHeightMode: true,
// height: 92.0)
//// let rowElement = ALRowElement(className: OrdersTableViewCell.classForCoder(),
//// identifier: OrdersTableViewCell.reuseIdentifier,
//// dataObject: element,
//// estimateHeightMode: true)
// rowElements.append(rowElement)
//
//
// }
// let section = ALSectionElement(rowElements: rowElements, headerElement: nil, footerElement: nil, isExpandable: true)
//
// sectionElements.append(section)
//
// return sectionElements
// }
func registerCells() {
self.alTableView?.registerCell(nibName: MasterTableViewCell.nib, reuseIdentifier: MasterTableViewCell.reuseIdentifier)
self.alTableView?.registerCell(nibName: Master2TableViewCell.nib, reuseIdentifier: Master2TableViewCell.reuseIdentifier)
self.alTableView?.registerHeaderFooter(nibName: MasterHeaderFooter.nib, reuseIdentifier: MasterHeaderFooter.reuseIdentifier)
alTableView?.registerCell(nibName: OrdersTableViewCell.nib,
reuseIdentifier: OrdersTableViewCell.reuseIdentifier)
alTableView?.registerCell(nibName: LoadingTableViewCell.nib,
reuseIdentifier: LoadingTableViewCell.reuseIdentifier)
alTableView?.registerCell(nibName: LoadingRetryTableViewCell.nib,
reuseIdentifier: LoadingRetryTableViewCell.reuseIdentifier)
}
func tableViewPullToRefresh() {
print("Refreshed")
}
func tableViewDidReachEnd() {
print("tableViewDidReachEnd")
}
}
| mit | d1dbff5515c1f11455a27cdd1314e8c2 | 45.5 | 313 | 0.633641 | 5.411471 | false | false | false | false |
nifti/CinchKit | CinchKit/Client/CinchClient+Accounts.swift | 1 | 4867 | //
// CinchClient+Accounts.swift
// CinchKit
//
// Created by Mikhail Vetoshkin on 29/12/15.
// Copyright © 2015 cinch. All rights reserved.
//
extension CinchClient {
public func fetchAccountsMatchingIds(ids: [String], completionHandler: ([CNHAccount]?, NSError?) -> ()) {
self.fetchAccountsMatchingParams(["ids": ids], completionHandler: completionHandler)
}
public func fetchAccountsMatchingEmail(email : String, completionHandler : ([CNHAccount]?, NSError?) -> ()) {
self.fetchAccountsMatchingParams(["email" : email], completionHandler: completionHandler)
}
public func fetchAccountsMatchingUsername(username : String, completionHandler : ([CNHAccount]?, NSError?) -> ()) {
self.fetchAccountsMatchingParams(["username" : username], completionHandler: completionHandler)
}
public func createAccount(parameters: [String : AnyObject], completionHandler : ((CNHAccount?, NSError?) -> ())?) {
let serializer = CreateAccountSerializer()
if let accounts = self.rootResources?["accounts"] {
request(.POST, accounts.href, parameters: parameters, serializer: serializer) { (auth, error) in
if let _ = error {
completionHandler?(nil, error)
} else if let a = auth {
self.setActiveSession(a.accessTokenData)
completionHandler?(a.account, nil)
} else {
completionHandler?(nil, nil)
}
}
} else {
completionHandler?(nil, clientNotConnectedError())
}
}
public func updateAccount(atURL url : NSURL, parameters: [String : AnyObject], queue: dispatch_queue_t? = nil, completionHandler : ((CNHAccount?, NSError?) -> ())?) {
let serializer = AccountsSerializer()
authorizedRequest(.PUT, url, parameters: parameters, queue: queue, serializer: serializer) { (accounts, error) in
if let _ = error {
completionHandler?(nil, error)
} else if let account = accounts?.first {
completionHandler?(account, nil)
} else {
completionHandler?(nil, nil)
}
}
}
public func deleteAccount(atURL url : NSURL, queue: dispatch_queue_t? = nil, completionHandler : ((String?, NSError?) -> ())?) {
let serializer = EmptyResponseSerializer()
authorizedRequest(.DELETE, url, parameters: nil, queue: queue, serializer: serializer) { (_, error) in
completionHandler?(nil, error)
}
}
public func checkBlockedAccount(atURL url : NSURL, queue: dispatch_queue_t? = nil, completionHandler : (Bool?, NSError?) -> ()) {
let serializer = FetchAccountsSerializer()
authorizedRequest(.GET, url, parameters: nil, queue: queue, serializer: serializer) { (accounts, error) in
var blocked = false
if accounts != nil {
blocked = true
}
completionHandler(
error == nil || error!.code == 404 ? blocked : nil,
error != nil && error!.code != 404 ? error : nil
)
}
}
public func blockAccount(atURL url : NSURL, accountId: String, queue: dispatch_queue_t? = nil, completionHandler : ((String?, NSError?) -> ())?) {
let serializer = EmptyResponseSerializer()
let params: [String: AnyObject] = ["blockedAccountId": accountId]
authorizedRequest(.POST, url, parameters: params, queue: queue, serializer: serializer) { (_, error) in
completionHandler?(nil, error)
}
}
public func unblockAccount(atURL url : NSURL, queue: dispatch_queue_t? = nil, completionHandler : ((String?, NSError?) -> ())?) {
let serializer = EmptyResponseSerializer()
authorizedRequest(.DELETE, url, parameters: nil, queue: queue, serializer: serializer) { (_, error) in
completionHandler?(nil, error)
}
}
internal func fetchAccountsMatchingParams(var params : [String : AnyObject]?, completionHandler : ([CNHAccount]?, NSError?) -> ()) {
if let accounts = self.rootResources?["accounts"] {
var accountsUrl: NSURL = accounts.href
// Remove ids from query params because of ids should be passed in path
if let ids = params?["ids"] as? [String] {
accountsUrl = NSURL(string: accountsUrl.absoluteString + "/" + ids.joinWithSeparator(","))!
params?.removeValueForKey("ids")
}
let serializer = FetchAccountsSerializer()
request(.GET, accountsUrl, parameters: params, encoding: .URL , serializer: serializer, completionHandler: completionHandler)
} else {
return completionHandler(nil, clientNotConnectedError())
}
}
}
| mit | bef6b5296c01ee51bf65b3a21fbd20c9 | 41.684211 | 170 | 0.607686 | 4.955193 | false | false | false | false |
huangboju/AsyncDisplay_Study | AsyncDisplay/Weibo/WBStatusPicNode.swift | 1 | 1082 | //
// WBStatusPicNode.swift
// AsyncDisplay
//
// Created by 伯驹 黄 on 2017/5/16.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
import AsyncDisplayKit
class WBStatusPicNode: ASNetworkImageNode {
var badgeNode: ASImageNode?
convenience init(badgeName: String?) {
self.init()
if let badgeName = badgeName {
badgeNode = ASImageNode()
let badge = WBStatusHelper.image(with: badgeName)
badgeNode?.image = badge
badgeNode?.isLayerBacked = true
badgeNode?.style.width = ASDimensionMake(badge?.size.width ?? 0)
badgeNode?.style.height = ASDimensionMake(badge?.size.height ?? 0)
addSubnode(badgeNode!)
}
}
// override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
// if let badgeNode = badgeNode {
// return ASRelativeLayoutSpec(horizontalPosition: .end, verticalPosition: .end, sizingOption: [], child: badgeNode)
// }
// return super.layoutSpecThatFits(constrainedSize)
// }
}
| mit | d189542c530701d4cde088a9bcdeaebd | 31.333333 | 127 | 0.638238 | 4.217391 | false | false | false | false |
XCEssentials/UniFlow | Sources/4_Dispatcher/Dispatcher.swift | 1 | 23939 | /*
MIT License
Copyright (c) 2016 Maxim Khatskevich ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import Foundation
import Combine
import XCEPipeline
//---
public
final
class Dispatcher: ObservableObject
{
let executionQueue: DispatchQueue
private
var _storage: Storage
var storage: Storage
{
get
{
if
activeTransaction == nil
{
return executionQueue.sync {
_storage
}
}
else
{
/// NOTE: we are in transaction and already must be
/// on correct queue
return _storage
}
}
}
private
var activeTransaction: Transaction?
private
var internalBindings: [String: [AnyCancellable]] = [:]
private
var externalBindings: [ObjectIdentifier: ExternalSubscription] = [:]
fileprivate
let _accessLog = PassthroughSubject<AccessReport, Never>()
public
var accessLog: AnyPublisher<AccessReport, Never>
{
_accessLog.eraseToAnyPublisher()
}
fileprivate
let _status = CurrentValueSubject<[FeatureStatus], Never>([])
public
var status: AnyPublisher<[FeatureStatus], Never>
{
_status.eraseToAnyPublisher()
}
private
var statusSubscription: AnyCancellable?
private
var externalBindingsSubscription: AnyCancellable?
fileprivate
let _internalBindingsStatusLog = PassthroughSubject<InternalBinding.Status, Never>()
public
var internalBindingsStatusLog: AnyPublisher<InternalBinding.Status, Never>
{
_internalBindingsStatusLog.eraseToAnyPublisher()
}
fileprivate
let _externalBindingsStatusLog = PassthroughSubject<ExternalBinding.Status, Never>()
public
var externalBindingsStatusLog: AnyPublisher<ExternalBinding.Status, Never>
{
_externalBindingsStatusLog.eraseToAnyPublisher()
}
//---
/// Initializes dispatcher.
///
/// - Parameters:
/// - `storage`: underslaying storage for features, empty by default;
/// - `executionQueue`: the queue for read/write operations to storage.
public
init(
with storage: Storage = Storage(),
executionQueue: DispatchQueue? = nil
) {
let executionQueue = executionQueue ?? .init(
label: "com.xcessentials.Dispatcher.\(UUID().uuidString)",
attributes: .concurrent
)
//---
self.executionQueue = executionQueue
self._storage = storage
//---
self.statusSubscription = accessLog
.onProcessed
.statusReport
.sink { [weak self] in
self?._status.send($0)
}
self.externalBindingsSubscription = accessLog
.onProcessed
.perEachMutation
.sink { [weak self] mutation in
guard let dispatcher = self else { return }
//---
dispatcher
.externalBindings
.values
.compactMap {
$0.observer
}
.flatMap {
$0.bindings()
}
.forEach {
$0.execute(
with: dispatcher,
mutation: mutation
)
}
}
}
}
// MARK: - Nested types
extension Dispatcher
{
public
struct AccessReport
{
public
let timestamp = Date()
/// Outcome of the access event (success/failure).
public
let outcome: Result<Storage.History, Error>
/// Snapshot of the storage at the time of the event.
public
let storage: Storage
/// Origin of the event.
public
let origin: AccessOrigin
}
public
struct AccessOrigin
{
public
let file: String
public
let function: String
public
let line: Int
}
public
enum AccessError: Error
{
case noActiveTransaction
case anotherTransactionIsInProgress(
anotherTransaction: AccessOrigin
)
case internalInconsistencyDetected(
anotherTransaction: AccessOrigin
)
case failureDuringAccess(
line: Int,
cause: Error
)
}
fileprivate
typealias Transaction = (
origin: AccessOrigin,
recoverySnapshot: Storage
)
public
struct ProcessedActionReport
{
public
let timestamp: Date
public
let mutations: Storage.History
/// Snapshot of the storage at the time of the event
/// (including the mutations listed above).
public
let storage: Storage
/// Origin of the event.
public
let origin: AccessOrigin
}
public
struct RejectedActionReport: Error
{
public
let timestamp: Date
public
let reason: Error
/// Snapshot of the storage at the time of the event
/// (no mutations were applied as result of this event).
public
let storage: Storage
/// Origin of the event.
public
let origin: AccessOrigin
}
fileprivate
struct ExternalSubscription
{
private(set)
weak
var observer: SomeExternalObserver?
init(
with observer: SomeExternalObserver
) {
self.observer = observer
}
}
}
// MARK: - Access data
public
extension Dispatcher
{
var allStates: [SomeStateBase]
{
storage.allStates
}
var allFeatures: [SomeFeature.Type]
{
storage.allFeatures
}
func fetchState(
forFeature featureType: SomeFeature.Type
) throws -> SomeStateBase {
try storage.fetchState(forFeature: featureType)
}
func fetchState<S: SomeState>(
ofType _: S.Type = S.self
) throws -> S {
try storage.fetchState(ofType: S.self)
}
}
//internal
extension Dispatcher
{
@discardableResult
func transact<T>(
scope: String = #file,
context: String = #function,
location: Int = #line,
_ handler: () throws -> T
) -> Result<T, Error> {
var report: AccessReport!
/// ‼️ NOTE: use `barrier` for exclusive access during whole transaction
let result = executionQueue.sync(flags: .barrier) {
try! (scope, context, location)
./ startTransaction(scope:context:location:)
//---
do
{
let output = try handler()
report = try! (scope, context, location)
./ commitTransaction(scope:context:location:)
//---
return output
./ Result<T, Error>.success(_:)
}
catch
{
report = try! (scope, context, location, error)
./ rejectTransaction(scope:context:location:reason:)
return error
./ Result<T, Error>.failure(_:)
}
}
//---
switch report.outcome
{
case .success(let mutationsToReport):
cleanupExternalBindings()
installInternalBindings(
basedOn: mutationsToReport
)
_accessLog.send(report)
uninstallInternalBindings(
basedOn: mutationsToReport
)
case .failure:
_accessLog.send(report)
}
//---
return result
}
func startTransaction(
scope s: String = #file,
context c: String = #function,
location l: Int = #line
) throws {
guard
activeTransaction == nil
else
{
throw AccessError.anotherTransactionIsInProgress(
anotherTransaction: activeTransaction!.origin
)
}
//---
activeTransaction = (
.init(file: s, function: c, line: l),
_storage
)
}
func commitTransaction(
scope s: String = #file,
context c: String = #function,
location l: Int = #line
) throws -> AccessReport {
guard
let tr = self.activeTransaction
else
{
throw AccessError.noActiveTransaction
}
guard
tr.recoverySnapshot.lastHistoryResetId == storage.lastHistoryResetId
else
{
throw AccessError.internalInconsistencyDetected(
anotherTransaction: tr.origin
)
}
//---
let mutationsToReport = _storage.resetHistory()
activeTransaction = nil
//---
return .init(
outcome: .success(
mutationsToReport
),
storage: _storage,
origin: tr.origin
)
}
func rejectTransaction(
scope s: String = #file,
context c: String = #function,
location l: Int = #line,
reason: Error
) throws -> AccessReport {
guard
let tr = self.activeTransaction
else
{
throw AccessError.noActiveTransaction
}
//---
_storage = tr.recoverySnapshot
self.activeTransaction = nil
//---
return .init(
outcome: .failure(
reason
),
storage: _storage,
origin: tr.origin
)
}
func access(
scope s: String,
context c: String,
location l: Int,
_ handler: (inout Storage) throws -> Void
) throws {
guard
self.activeTransaction != nil
else
{
throw AccessError.noActiveTransaction
}
//---
do
{
try handler(&_storage)
}
catch
{
throw AccessError.failureDuringAccess(
line: l,
cause: error
)
}
}
func resetStorage(
scope s: String = #file,
context c: String = #function,
location l: Int = #line
) {
try! startTransaction(
scope: s,
context: c,
location: l
)
//---
try! access(scope: s, context: c, location: l) {
try! $0.removeAll()
}
//---
_ = try! commitTransaction(
scope: s,
context: c,
location: l
)
}
}
// MARK: - Internal bindings management
private
extension Dispatcher
{
/// This will install bindings for newly initialized keys.
func installInternalBindings(
basedOn reports: Storage.History
) {
reports
.compactMap {
report -> SomeFeature.Type? in
//---
switch report.operation
{
case .initialization(let newState):
return type(of: newState).feature
default:
return nil
}
}
.compactMap {
$0 as? SomeInternalObserver.Type
}
.map {(
observerType: $0,
tokens: $0.bindings.map { $0.construct(with: self) }
)}
.filter {
!$0.tokens.isEmpty
}
.forEach {
self.internalBindings[$0.observerType.name] = $0.tokens
}
}
/// This will uninstall bindings for recently deinitialized keys.
func uninstallInternalBindings(
basedOn reports: Storage.History
) {
reports
.compactMap {
report -> SomeFeature.Type? in
//---
switch report.operation
{
case .deinitialization(let oldState):
return type(of: oldState).feature
default:
return nil
}
}
.forEach {
self.internalBindings.removeValue(forKey: $0.name)
}
}
}
// MARK: - External bindings management
extension Dispatcher
{
/// Registers `observer` for bindings execution
/// within `self` for as long as `observer` is
/// in memory, or until `unsubscribe` is called
/// for same `observer`.
public
func subscribe(_ observer: SomeExternalObserver)
{
let observerId = ObjectIdentifier(observer)
externalBindings[observerId] = ExternalSubscription(with: observer)
}
/// Deactivates `observer` bindings within `self`.
public
func unsubscribe(_ observer: SomeExternalObserver)
{
let observerId = ObjectIdentifier(observer)
externalBindings[observerId] = nil
}
/// Internal method to celanup
private
func cleanupExternalBindings()
{
externalBindings = externalBindings.filter { $0.value.observer != nil }
}
}
// MARK: - Bindings
/// Binding that is defined on type level in a feature and
/// operates within given storage.
public
struct InternalBinding
{
public
enum Status
{
case activated(InternalBinding)
/// After passing through `when` (and `given`,
/// if present) claus(es), right before `then`.
case triggered(InternalBinding, input: Any, output: Any)
/// After executing `then` clause.
case executed(InternalBinding, input: Any)
case failed(InternalBinding, Error)
case cancelled(InternalBinding)
}
public
let description: String
public
let scope: String
public
let source: SomeFeature.Type
public
let location: Int
//---
private
let body: (Dispatcher, Self) -> AnyPublisher<Void, Error>
//---
//internal
func construct(with dispatcher: Dispatcher) -> AnyCancellable
{
body(dispatcher, self).sink(receiveCompletion: { _ in }, receiveValue: { })
}
//internal
init<S: SomeFeature, W: Publisher, G>(
source: S.Type,
description: String,
scope: String,
location: Int,
when: @escaping (AnyPublisher<Dispatcher.AccessReport, Never>) -> W,
given: @escaping (Dispatcher, W.Output) throws -> G?,
then: @escaping (Dispatcher, G) -> Void
) {
self.source = S.self
self.description = description
self.scope = scope
self.location = location
self.body = { dispatcher, binding in
return when(dispatcher.accessLog)
.tryCompactMap { [weak dispatcher] mutation in
guard let dispatcher = dispatcher else { return nil }
//---
let result = try given(dispatcher, mutation)
result.map {
dispatcher
._internalBindingsStatusLog
.send(
.triggered(
binding,
input: mutation,
output: $0
)
)
}
return result
}
.compactMap { [weak dispatcher] (givenOutput: G) -> Void? in
guard let dispatcher = dispatcher else { return nil }
//---
return then(dispatcher, givenOutput) // map into `Void` to erase type info
}
.handleEvents(
receiveSubscription: { [weak dispatcher] _ in
dispatcher?
._internalBindingsStatusLog
.send(
.activated(binding)
)
},
receiveOutput: { [weak dispatcher] in
dispatcher?
._internalBindingsStatusLog
.send(
.executed(binding, input: $0)
)
},
receiveCompletion: { [weak dispatcher] in
switch $0
{
case .failure(let error):
dispatcher?
._internalBindingsStatusLog
.send(
.failed(binding, error)
)
default:
break
}
},
receiveCancel: { [weak dispatcher] in
dispatcher?
._internalBindingsStatusLog
.send(
.cancelled(binding)
)
}
)
.eraseToAnyPublisher()
}
}
}
/// Binding that is defined on instance level in an external observer and
/// operates in context of a given storage + given observer instance.
public
struct ExternalBinding
{
public
enum Status
{
case activated(ExternalBinding)
/// After passing through `when` (and `given`,
/// if present) claus(es), right before `then`.
case triggered(ExternalBinding, input: Any, output: Any)
/// After executing `then` clause.
case executed(ExternalBinding, input: Any)
case failed(ExternalBinding, Error)
case cancelled(ExternalBinding)
}
public
let description: String
public
let scope: String
public
let source: SomeExternalObserver.Type
public
let location: Int
//---
private
let body: (Storage.HistoryElement, Dispatcher, Self) -> Void
//---
//internal
func execute(with dispatcher: Dispatcher, mutation: Storage.HistoryElement)
{
body(mutation, dispatcher, self)
}
//internal
init<S: SomeExternalObserver, W: SomeMutationDecriptor, G>(
description: String,
scope: String,
context: S.Type,
location: Int,
given: @escaping (Dispatcher, W) throws -> G?,
then: @escaping (Dispatcher, G) -> Void
) {
self.description = description
self.scope = scope
self.source = S.self
self.location = location
self.body = { mutation, dispatcher, binding in
Just(mutation)
.as(W.self)
.tryCompactMap { [weak dispatcher] mutation in
guard let dispatcher = dispatcher else { return nil }
//---
let result = try given(dispatcher, mutation)
result.map {
dispatcher
._externalBindingsStatusLog
.send(
.triggered(
binding,
input: mutation,
output: $0
)
)
}
return result
}
.compactMap { [weak dispatcher] (givenOutput: G) -> Void? in
guard let dispatcher = dispatcher else { return nil }
//---
return then(dispatcher, givenOutput) // map into `Void` to erase type info
}
.handleEvents(
receiveSubscription: { [weak dispatcher] _ in
dispatcher?
._externalBindingsStatusLog
.send(
.activated(binding)
)
},
receiveOutput: { [weak dispatcher] in
dispatcher?
._externalBindingsStatusLog
.send(
.executed(binding, input: $0)
)
},
receiveCompletion: { [weak dispatcher] in
switch $0
{
case .failure(let error):
dispatcher?
._externalBindingsStatusLog
.send(
.failed(binding, error)
)
default:
break
}
},
receiveCancel: { [weak dispatcher] in
dispatcher?
._externalBindingsStatusLog
.send(
.cancelled(binding)
)
}
)
.executeNow()
}
}
}
| mit | e7da2ff6d6885d84d94d16eaba301d60 | 24.988056 | 94 | 0.467224 | 5.915719 | false | false | false | false |
GalinaCode/Nutriction-Cal | NutritionCal/Nutrition Cal/Extensions.swift | 1 | 1667 | //
// Extensions.swift
// Nutrition Cal
//
// Created by Galina Petrova on 03/25/16.
// Copyright © 2015 Galina Petrova. All rights reserved.
//
import UIKit
import MaterialDesignColor
extension NSDate {
func isToday() -> Bool {
let cal = NSCalendar.currentCalendar()
var components = cal.components([.Era, .Year, .Month, .Day], fromDate:NSDate())
let today = cal.dateFromComponents(components)!
components = cal.components([.Era, .Year, .Month, .Day], fromDate:self)
let otherDate = cal.dateFromComponents(components)!
if(today.isEqualToDate(otherDate)) {
return true
} else {
return false
}
}
func daysSince1970() -> Int {
let dateIn1970 = NSDate(timeIntervalSince1970: NSTimeIntervalSince1970)
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day], fromDate: dateIn1970, toDate: self, options: [])
return components.day
}
}
extension CollectionType {
func find(@noescape predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Self.Generator.Element? {
return try indexOf(predicate).map({self[$0]})
}
}
extension UIViewController {
func presentMessage(title: String, message: String, action: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: action, style: UIAlertActionStyle.Default, handler: nil))
alert.view.tintColor = MaterialDesignColor.green500
dispatch_async(dispatch_get_main_queue()) {
self.presentViewController(alert, animated: true, completion: nil)
alert.view.tintColor = MaterialDesignColor.green500
}
}
}
| apache-2.0 | 03e01f1499dfd1566d39db03f21b306a | 26.311475 | 110 | 0.72569 | 3.856481 | false | false | false | false |
alienorb/Random-Shapes | Random Shapes/Sources/ConfigureSheetController.swift | 1 | 3122 | //---------------------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2014-2015 Alien Orb Software LLC. 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 Cocoa
import ScreenSaver
class ConfigureSheetController: NSWindowController {
@IBOutlet weak var stylePopUpButton: NSPopUpButton!
@IBOutlet weak var versionTextField: NSTextField!
@IBOutlet weak var copyrightTextField: NSTextField!
func prepareSheet() {
let defaults = ScreenSaverDefaults.randomShapesDefaults()
if let style = defaults?["Style"]?.integerValue {
stylePopUpButton.selectItemWithTag(style)
}
let formatter = NSDateFormatter()
formatter.dateFormat = "MMMM d, yyyy"
if let bundleVersion = NSBundle(forClass: ShapesView.self).objectForInfoDictionaryKey("CFBundleShortVersionString") as? String {
var versionText = versionTextField.stringValue.stringByReplacingOccurrencesOfString("__VERSION__", withString: bundleVersion)
versionText = versionText.stringByReplacingOccurrencesOfString("__DATE__", withString: formatter.stringFromDate(compileDate()))
versionTextField.stringValue = versionText
}
formatter.dateFormat = "yyyy"
let copyrightText = copyrightTextField.stringValue.stringByReplacingOccurrencesOfString("__YEAR__", withString: formatter.stringFromDate(compileDate()))
copyrightTextField.stringValue = copyrightText
}
@IBAction func clickCancelButton(sender: AnyObject) {
dismissSheet()
}
@IBAction func clickOKButton(sender: AnyObject) {
let defaults = ScreenSaverDefaults.randomShapesDefaults()
defaults?["Style"] = stylePopUpButton.selectedTag()
defaults?.synchronize()
// ScreenSaverDefaults doesn't post this notification
NSNotificationCenter.defaultCenter().postNotificationName(NSUserDefaultsDidChangeNotification, object: defaults)
dismissSheet()
}
func dismissSheet() {
NSApplication.sharedApplication().endSheet(window!)
}
}
| mit | e59c684fd84ed514374527489ad6b2bb | 39.025641 | 154 | 0.727739 | 4.955556 | false | false | false | false |
rnystrom/GitHawk | Pods/StyledTextKit/Source/CGSize+Utility.swift | 1 | 596 | //
// CGSize+Utility.swift
// StyledTextKit
//
// Created by Ryan Nystrom on 12/13/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
public extension CGSize {
func snapped(scale: CGFloat) -> CGSize {
var size = self
size.width = ceil(size.width * scale) / scale
size.height = ceil(size.height * scale) / scale
return size
}
func resized(inset: UIEdgeInsets) -> CGSize {
var size = self
size.width += inset.left + inset.right
size.height += inset.top + inset.bottom
return size
}
}
| mit | 89835987521f03fb6aae8384c6f2dc52 | 21.037037 | 55 | 0.605042 | 3.814103 | false | false | false | false |
OatmealDome/dolphin | Source/iOS/DolphiniOS/DolphiniOS/UI/Emulation/TouchController/TCView.swift | 1 | 1221 | // Copyright 2019 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
import Foundation
import UIKit
@objc class TCView: UIView
{
var real_view: UIView?
private var _m_port: Int = 0
@objc var m_port: Int
{
get
{
return _m_port
}
set
{
_m_port = newValue
SetPort(newValue, view: real_view!)
}
}
required init?(coder: NSCoder)
{
super.init(coder: coder)
// Load ourselves from the nib
let name = String(describing: type(of: self))
let view = Bundle(for: type(of: self)).loadNibNamed(name, owner: self, options: nil)![0] as! UIView
view.frame = self.bounds
self.addSubview(view)
real_view = view;
}
func SetPort(_ port: Int, view: UIView)
{
for subview in view.subviews
{
if (subview is TCButton)
{
(subview as! TCButton).m_port = port
}
else if (subview is TCJoystick)
{
(subview as! TCJoystick).m_port = port
}
else if (subview is TCDirectionalPad)
{
(subview as! TCDirectionalPad).m_port = port
}
else
{
SetPort(port, view: subview)
}
}
}
}
| gpl-2.0 | 3afe41e185f84a083d0fd77432276cf0 | 18.380952 | 103 | 0.573301 | 3.633929 | false | false | false | false |
rnystrom/GitHawk | Local Pods/DateAgo/DateAgoTests/DateAgoLongTests.swift | 1 | 3607 | //
// DateAgoShortTests.swift
// DateAgoTests
//
// Created by Ryan Nystrom on 4/29/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import XCTest
@testable import DateAgo
class DateAgoShortTests: XCTestCase {
class DateDisplayTests: XCTestCase {
func test_whenDateFuture() {
let result = Date(timeIntervalSinceNow: 10).agoString(.short)
XCTAssertEqual(result, "in the future")
}
func test_whenDateSeconds() {
let result = Date(timeIntervalSinceNow: -5).agoString(.short)
XCTAssertEqual(result, "just now")
}
func test_whenDateMinutes_withLowerBound_withSingular() {
let result = Date(timeIntervalSinceNow: -61).agoString(.short)
XCTAssertEqual(result, "1m")
}
func test_whenDateMinutes_withUpperBound_withDecimal_withSingular() {
let result = Date(timeIntervalSinceNow: -59.5).agoString(.short)
XCTAssertEqual(result, "1m")
}
func test_whenDateMinutes_withUpperBound_withPlural() {
let result = Date(timeIntervalSinceNow: -119).agoString(.short)
XCTAssertEqual(result, "2m")
}
func test_whenDateHour_withLowerBound_withSingular() {
let result = Date(timeIntervalSinceNow: -3601).agoString(.short)
XCTAssertEqual(result, "1h")
}
func test_whenDateHour_withUpperBound_withDecimal_withSingular() {
let result = Date(timeIntervalSinceNow: -3599.5).agoString(.short)
XCTAssertEqual(result, "1h")
}
func test_whenDateHours_withUpperBound_withPlural() {
let result = Date(timeIntervalSinceNow: -7199).agoString(.short)
XCTAssertEqual(result, "2h")
}
func test_whenDateDay_withLowerBound_withSingular() {
let result = Date(timeIntervalSinceNow: -86401).agoString(.short)
XCTAssertEqual(result, "1d")
}
func test_whenDateDay_withUpperBound_withDecimal_withSingular() {
let result = Date(timeIntervalSinceNow: -86399.5).agoString(.short)
XCTAssertEqual(result, "1d")
}
func test_whenDateDay_withUpperBound_withPlural() {
let result = Date(timeIntervalSinceNow: -172799).agoString(.short)
XCTAssertEqual(result, "2d")
}
func test_whenDateMonth_withLowerBound_withSingular() {
let result = Date(timeIntervalSinceNow: -2592001).agoString(.short)
XCTAssertEqual(result, "1mo")
}
func test_whenDateMonth_withUpperBound_withDecimal_withSingular() {
let result = Date(timeIntervalSinceNow: -2591999.5).agoString(.short)
XCTAssertEqual(result, "1mo")
}
func test_whenDateMonth_withUpperBound_withPlural() {
let result = Date(timeIntervalSinceNow: -5183999).agoString(.short)
XCTAssertEqual(result, "2mo")
}
func test_whenDateYear_withLowerBound_withSingular() {
let result = Date(timeIntervalSinceNow: -31104001).agoString(.short)
XCTAssertEqual(result, "1y")
}
func test_whenDateYear_withUpperBound_withDecimal_withSingular() {
let result = Date(timeIntervalSinceNow: -31103999.5).agoString(.short)
XCTAssertEqual(result, "1y")
}
func test_whenDateYear_withUpperBound_withPlural() {
let result = Date(timeIntervalSinceNow: -62207999).agoString(.short)
XCTAssertEqual(result, "2y")
}
}
}
| mit | 955a082a2befbfdb7a049cbf1231661e | 34.009709 | 82 | 0.628397 | 4.381531 | false | true | false | false |
ben-ng/swift | stdlib/public/SDK/CallKit/CXProviderConfiguration.swift | 1 | 939 | //===----------------------------------------------------------------------===//
//
// 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 CallKit
import Foundation
@available(iOS 10.0, *)
extension CXProviderConfiguration {
@nonobjc
public final var supportedHandleTypes: Set<CXHandle.HandleType> {
get {
return Set(__supportedHandleTypes.map {
CXHandle.HandleType(rawValue: $0.intValue)!
})
}
set {
__supportedHandleTypes =
Set(newValue.lazy.map { $0.rawValue as NSNumber })
}
}
}
| apache-2.0 | 7a9273c6cd7aff03db14b4350d06c9ed | 30.3 | 80 | 0.57721 | 4.766497 | false | false | false | false |
Ryukie/Est | Est/Est/Classes/EstDesktop/Controller/RYDeskTopVC.swift | 1 | 3623 | //
// RYDeskTopVC.swift
// Est
//
// Created by 王荣庆 on 16/3/8.
// Copyright © 2016年 Ryukie. All rights reserved.
//
import UIKit
import EstSharedKit
class RYDeskTopVC: UIViewController {
var appAddedToLauncher = [RYApp]()
// var appIndexInLauncher : Int64 = 0
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = col_purple
prepareCollectionView()
}
private func prepareCollectionView () {
let cv_frame = CGRectMake(0, 0, scrW, scrH)
let cv_fl = UICollectionViewFlowLayout()
cv_appIcons = UICollectionView(frame: cv_frame, collectionViewLayout: cv_fl)
cv_appIcons!.frame = cv_frame
cv_appIcons!.collectionViewLayout = cv_fl
cv_appIcons!.backgroundColor = .None
//SetFlowLayout
let margin : CGFloat = (scrW - 4*appIconWidth)/5
let sectionMargin : CGFloat = margin
cv_fl.minimumInteritemSpacing = margin/2
cv_fl.minimumLineSpacing = margin/2
cv_fl.sectionInset = UIEdgeInsetsMake(sectionMargin, sectionMargin, sectionMargin, sectionMargin)
cv_fl.itemSize = CGSizeMake(appIconWidth, appIconHeight+appNameLableHeight)
view.addSubview(cv_appIcons!)
cv_appIcons!.delegate = self
cv_appIcons!.dataSource = self
cv_appIcons?.registerClass(RYAppCellInside.self, forCellWithReuseIdentifier: "cell")
}
private var cv_appIcons : UICollectionView?
}
extension RYDeskTopVC : UICollectionViewDelegate,UICollectionViewDataSource,RYAppCellInsideDelegate,RYAppEditVCDelegate {
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! RYAppCellInside
cell.delegate = self
cell.tag = indexPath.item
if indexPath.item < appAddedToLauncher.count {//返回已经添加进数组的Cell
let app = appAddedToLauncher[indexPath.item]
cell.app_model = app
return cell
} else {//当库存app数量少于界面cell的数量的时候会越界
cell.app_model = nil
return cell
}
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if appAddedToLauncher.count == 0 {
return 1
}else if appAddedToLauncher.count>=16 {
return 16
}else {
return appAddedToLauncher.count + 1
}
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
}
//点击添加按钮的代理方法
func addApp(cell:RYAppCellInside) {
let editoeVC = RYAppEditVC(style: .Plain)
editoeVC.delegate = self
editoeVC.fromCell = cell
let navi = UINavigationController(rootViewController: editoeVC)
presentViewController(navi, animated: true, completion: nil)
}
func deleteApp(cell:RYAppCellInside) {
if appAddedToLauncher.count != 0 {
appAddedToLauncher.removeAtIndex(cell.tag)
cv_appIcons?.reloadData()
}
}
func addAppToLauncher (app: RYApp,toCell:RYAppCellInside){
if toCell.app_model != nil {
appAddedToLauncher.removeAtIndex(toCell.tag)
appAddedToLauncher.insert(app , atIndex: toCell.tag)
}else {
appAddedToLauncher.append(app)
}
cv_appIcons?.reloadData()
}
} | mit | f448b59cfc1213cf7de63c56e9918d1b | 35.091837 | 130 | 0.658088 | 4.498728 | false | false | false | false |
love-everyday/ExCommentPugin | ExtComment/FoundationExt.swift | 1 | 2842 | //
// FoundationExt.swift
// ExtXcode8
//
// Created by 王洪运 on 2016/9/28.
// Copyright © 2016年 王洪运. All rights reserved.
//
import Foundation
extension String {
/// 检查是否是 OC 的方法
///
/// - returns: 是否是 OC 的方法
func hasMethod() -> Bool {
let str = replacingOccurrences(of: " ", with: "")
let pattern = "[-,+]\\(\\S*\\)"
let regular = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let results = regular.matches(in: str, options: .reportProgress, range: NSMakeRange(0, str.characters.count))
if results.count == 1 {
if let range = results.first?.range, range.location == 0 {
return true
}
}
return false
}
/// 检查是否是 OC 的属性
///
/// - returns: 是否是 OC 的属性
func hasProperty() -> Bool {
return contains("@property")
}
/// 解析 Swift 方法参数
///
/// - returns: 参数名数组
func parserFuncStrParameter() -> Array<String> {
var arr = [String]()
let startIdx = range(of: "(")!.upperBound
let endIdx = range(of: ")")!.lowerBound
if startIdx != endIdx {
let paramStr = substring(with: startIdx..<endIdx)
for paramItem in paramStr.components(separatedBy: ",") {
var paramName = paramItem.components(separatedBy: ":").first!.trimmingCharacters(in: .whitespacesAndNewlines)
if paramName.contains(" ") {
let paramNames = paramName.components(separatedBy: " ")
if paramNames.first!.contains("_") {
paramName = paramNames.last!
}else {
paramName = paramNames.first!
}
}
paramName = paramName.replacingOccurrences(of: ";", with: "")
arr.append(paramName)
}
}
return arr
}
func funcStrHasReturnValue() -> Bool {
let tempIndex = range(of: ")")!.lowerBound
let returnTypeStr = substring(from: tempIndex).replacingOccurrences(of: " ", with: "")
if returnTypeStr.contains("->Void") {
return false
} else if returnTypeStr.contains("->") {
return true
}else {
return false
}
}
/// 检查是否是 Swift 的方法
///
/// - returns: 是否是 Swift 的方法
func hasFuncMethod() -> Bool {
return contains("func ")
}
/// 检查是否是 Swift 的变量或常量
///
/// - returns: 是否是 Swift 的变量或常量
func hasVarOrLet() -> Bool {
return contains("var ") || contains("let ")
}
}
| mit | 1f77649c1273d1fc1b3f37d5945cbe56 | 24.292453 | 126 | 0.515106 | 4.567291 | false | false | false | false |
ura14h/MemoryStreamSample | MemoryStreamSample/MemoryStream.swift | 1 | 5787 | //
// MemoryStream.swift
// MemoryStreamSample
//
// Created by Hiroki Ishiura on 2016/10/29.
// Copyright © 2016年 Hiroki Ishiura. All rights reserved.
//
import Foundation
class MemoryStream {
enum StreamError: Error {
case insufficiencyStreamData
case insufficiencyStreamCapacity
case unknownStringEncoding
case unknownReason
}
enum IntegerByteOrder {
case littleEndian
case bigEndian
}
var integerByteOrder: IntegerByteOrder!
fileprivate var defaultIntegerByteOrder: IntegerByteOrder!
init() {
let bytes = UInt16(0x1234).bytes()
if bytes[0] == 0x12 {
defaultIntegerByteOrder = .bigEndian
} else {
defaultIntegerByteOrder = .littleEndian
}
integerByteOrder = defaultIntegerByteOrder
}
func open() {}
func close() {}
}
class MemoryInputStream: MemoryStream {
// Subclass of InputStream does not work by NSInvalidArgumentException.
// NSInvalidArgumentException says "-open only defined for abstract class."
var stream: InputStream!
var streamDataLength: Int = 0
init(data: Data) {
super.init()
stream = InputStream(data: data)
streamDataLength = data.count
}
deinit {
}
override func open() {
stream.open()
}
override func close() {
stream.close()
}
func readInteger<T: BytePackedInteger>() throws -> T {
let bytes = try readBytes(length: MemoryLayout<T>.size)
guard let value = T(bytes: bytes) else {
throw StreamError.insufficiencyStreamData
}
if integerByteOrder != defaultIntegerByteOrder {
// These converting are not cool.
if let value16 = value as? UInt16 {
return value16.byteSwapped as! T
} else if let value32 = value as? UInt32 {
return value32.byteSwapped as! T
} else if let value64 = value as? UInt64 {
return value64.byteSwapped as! T
}
}
return value
}
func readString(length: Int = Int.max) throws -> String {
let bytes = try readBytes(length: (length == Int.max) ? streamDataLength : length)
guard let string = String(bytes: bytes) else {
throw StreamError.unknownStringEncoding
}
return string
}
func readData(length: Int = Int.max) throws -> Data {
let bytes = try readBytes(length: (length == Int.max) ? streamDataLength : length)
let data = Data(bytes: bytes)
return data
}
func readBytes(length: Int = Int.max) throws -> [UInt8] {
var readBuffer = [UInt8](repeating: 0, count: (length == Int.max) ? streamDataLength : length)
if streamDataLength < readBuffer.count {
throw StreamError.insufficiencyStreamData
}
let readCount = try readStream(&readBuffer, maxLength: readBuffer.count)
if readCount != readBuffer.count {
throw StreamError.insufficiencyStreamData
}
return readBuffer
}
private func readStream(_ buffer: UnsafeMutablePointer<UInt8>, maxLength len: Int) throws -> Int {
if len == 0 {
buffer.initialize(to: 0, count: 0)
return 0
}
let readCount = stream.read(buffer, maxLength: len)
if readCount > 0 {
streamDataLength = streamDataLength - readCount
} else if readCount == 0 {
streamDataLength = 0
} else {
if let error = stream.streamError {
throw error
} else {
throw StreamError.unknownReason
}
}
return readCount
}
}
// MARK: -
class MemoryOutputStream: MemoryStream {
// Subclass of OutputStream does not work by NSInvalidArgumentException.
// NSInvalidArgumentException says "-open only defined for abstract class."
var stream: OutputStream!
var streamDataLength: Int = 0
override init() {
super.init()
stream = OutputStream(toMemory: ())
}
deinit {
}
override func open() {
stream.open()
}
override func close() {
stream.close()
}
func write<T: BytePackedInteger>(integer: T) throws {
var value: T
if integerByteOrder == defaultIntegerByteOrder {
value = integer
} else {
// These converting are not cool.
if let value16 = integer as? UInt16 {
value = value16.byteSwapped as! T
} else if let value32 = integer as? UInt32 {
value = value32.byteSwapped as! T
} else if let value64 = integer as? UInt64 {
value = value64.byteSwapped as! T
} else {
value = integer
}
}
let bytes = value.bytes()
try write(bytes: bytes, length: bytes.count)
}
func write(string: String, length: Int = Int.max) throws {
let bytes = string.bytes()
try write(bytes: bytes, length: (length == Int.max) ? bytes.count : length)
}
func write(data: Data, length: Int = Int.max) throws {
let bytes = data.bytes()
try write(bytes: bytes, length: (length == Int.max) ? bytes.count : length)
}
func write(bytes: [UInt8], length: Int = Int.max) throws {
let writeCount = try writeStream(bytes, maxLength: (length == Int.max) ? bytes.count : length)
if writeCount != length {
throw StreamError.insufficiencyStreamCapacity
}
}
private func writeStream(_ buffer: UnsafePointer<UInt8>, maxLength len: Int) throws -> Int {
if len == 0 {
return 0
}
let writeCount = stream.write(buffer, maxLength: len)
if writeCount > 0 {
streamDataLength = streamDataLength + writeCount
} else if writeCount == 0 {
throw StreamError.insufficiencyStreamCapacity
} else {
if let error = stream.streamError {
throw error
} else {
throw StreamError.unknownReason
}
}
return writeCount
}
func data() -> Data {
return stream.property(forKey: Stream.PropertyKey.dataWrittenToMemoryStreamKey) as! Data
}
}
// MARK: -
protocol BytePackedInteger {
init?(bytes: [UInt8])
func bytes() -> [UInt8]
}
extension UInt8: BytePackedInteger { /* see BytePackerImplements.swift */ }
extension UInt16: BytePackedInteger { /* see BytePackerImplements.swift */ }
extension UInt32: BytePackedInteger { /* see BytePackerImplements.swift */ }
extension UInt64: BytePackedInteger { /* see BytePackerImplements.swift */ }
| mit | 7e268f555c188b6fca9c073652cc8343 | 24.038961 | 99 | 0.697095 | 3.518248 | false | false | false | false |
iyubinest/Encicla | encicla/station/component/Stations.swift | 1 | 2268 | import RxSwift
import CoreLocation.CLLocation
import GoogleMaps
protocol Stations {
func near() -> Observable<(CLLocation, [PolylineStation])>
}
class DefaultStations: Stations {
private static let LIMIT = 3
let gps: GPS
let routesApi: RouteApi
let stationsApi: StationsAPI
init(locationRepo: GPS, routesRepo: RouteApi, stationsApiRepo: StationsAPI) {
self.gps = locationRepo
self.routesApi = routesRepo
self.stationsApi = stationsApiRepo
}
internal func near() -> Observable<(CLLocation, [PolylineStation])> {
return self.gps
.locate()
.flatMap {
location in
self.stationsApi
.stations()
.flatMap {
stations in
self.sort(location: location, stations: stations)
}
.take(3)
.flatMap {
station in
self.route(location: location, station: station)
}
.toArray()
.flatMap {
stations in
Observable.just((location, stations))
}
}
}
private func route(location: CLLocation,
station: Station) -> Observable<PolylineStation> {
let locationTo = CLLocation(latitude: station.lat, longitude: station.lon)
return self.routesApi
.calculate(from: location, to: locationTo)
.flatMap({
route in
return Observable.just(PolylineStation(name: station.name,
lat: station.lat,
lon: station.lon,
bikes: station.bikes,
polyline: route))
})
}
private func sort(location: CLLocation,
stations: [Station]) -> Observable<Station> {
return Observable.from(stations.sorted {
$0.distance(location: location) < $1.distance(location: location)
})
}
}
struct Station {
let name: String
let lat: Double
let lon: Double
let bikes: Int
func distance(location: CLLocation) -> Double {
return CLLocation(latitude: lat, longitude: lon)
.distance(from: location)
}
}
struct PolylineStation {
let name: String
let lat: Double
let lon: Double
let bikes: Int
let polyline: GMSPolyline
func distance(location: CLLocation) -> Double {
return CLLocation(latitude: lat, longitude: lon)
.distance(from: location)
}
}
| mit | 2ab9d248ecc63796621106e152b3f7df | 22.873684 | 79 | 0.631393 | 4.311787 | false | false | false | false |
mark-randall/APIClient | Pod/Classes/APIManager.swift | 1 | 15946 | //
// APIManager.swift
// APIClient
//
// The MIT License (MIT)
//
// Created by mrandall on 12/22/15.
// Copyright © 2015 mark-randall. 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 Alamofire
//MARK: - APIManager Request encoding
public enum APIManagerParameterEncoding: String {
case url
case json
}
//MARK: - RequestResponder
public protocol RequestResponder {
/// Handle a successful request
///
/// - Parameter request: APIRequest
/// - Parameter response: Response<AnyObject, NSError>
func requestSucceeded(_ request: APIRequest, response: APIResponse)
/// Handle a failed request
///
/// - Parameter request: APIRequest
/// - Parameter response: Response<AnyObject, NSError>
func requestFailed(_ request: APIRequest, response: APIResponse)
}
//MARK: - MakeStreamingRequestResult
public enum MakeStreamingRequestResult {
case success(task: URLSessionUploadTask)
case failure(error: NSError)
}
//MARK: - APIManager
open class APIManager: SessionManager, RequestResponder {
//base URL for Requests
//if nil APIRequest path must a fully qualitied url
public var baseUrl: URL?
//Headers to add to every JSONHTTPRequest request
//Headers in addition to SessionManager.defaultHTTPHeaders
public var headers: [String: String] = [:]
//Request encoding type
//Default is url encoded
//All request are made using this parameterEncoding unless APIRequest override
public var parameterEncoding = APIManagerParameterEncoding.url
//MARK: - Create / Make Request
/// Create Alamofire Request
///
/// - Parameter withAPIRequest:APIRequest
/// - Return Request?
open func createRequest(withAPIRequest request: APIRequest) -> Request? {
//prepare headers
var headers = SessionManager.defaultHTTPHeaders
headers += self.headers
headers += request.headers
//ensure URL was able to be created
guard let url = urlWithBaseUrl(path: request.path) else {
let error = NSError(domain: "", code: 1, userInfo: [:])
request.requestFailed(withResponse: DataResponse<Any>(request: nil, response: nil, data: nil, result: Result.failure(error)))
assertionFailure("APIRequest invalid manager.baseurl + request path or request.path. Not able to convert to url")
return nil
}
//create Alamofire request / task
let alamoFireRequest: Alamofire.DataRequest
//if create multipart upload request
if let binaryDataMultipart = request.binaryDataMultipart {
//Assert for debug but allow
if request.requestTimeoutInterval > 0 {
assertionFailure("APIRequest 'requestTimeoutInterval' currently only supported for data tasks.")
}
//create multipart form data in memory
let formData = MultipartFormData()
for (k,v) in binaryDataMultipart {
formData.append(v, withName: k)
}
headers += ["Content-Type": formData.contentType]
do {
let binaryData = try formData.encode()
//create update load task
alamoFireRequest = upload(binaryData, to: url.absoluteString, method: request.method, headers: headers)
} catch {
//binary encode failed
request.requestFailed(withResponse: DataResponse<Any>(request: nil, response: nil, data: nil, result: Result.failure(error as NSError)))
return nil
}
//create upload task
} else if let binaryData = request.binaryData {
//Assert for debug but allow
if request.requestTimeoutInterval > 0 {
assertionFailure("APIRequest 'requestTimeoutInterval' currently only supported for data tasks.")
}
//create update load task
alamoFireRequest = upload(binaryData, to: url.absoluteString, method: request.method, headers: headers)
//create data tasks
} else {
//create data task
let parameterEncoding = alamofireEncoding(forRequest: request)
//APIRequest requestTimeoutInterval support:
//
//Check if request needs to support requestTimeoutInterval
//If set create Alamofire.Request
//Access its NSURLRequest
//Create a NSMutableURLRequest from it
//Set timeoutInterval
//Create Alamofire.Request from NSMutableURLRequest
if request.requestTimeoutInterval > 0 {
let alamoFireRequestTemp = self.request(
url.absoluteString,
method: request.method,
parameters: request.params,
encoding: parameterEncoding,
headers: headers
)
if let mutableURLRequest = (alamoFireRequestTemp.request as NSURLRequest?)?.mutableCopy() as? NSMutableURLRequest {
mutableURLRequest.timeoutInterval = request.requestTimeoutInterval
alamoFireRequest = self.request(mutableURLRequest as! URLRequestConvertible) //TODO validate
} else {
assertionFailure("APIRequest 'requestTimeoutInterval' configuration failed.")
alamoFireRequest = alamoFireRequestTemp
}
} else {
alamoFireRequest = self.request(
url.absoluteString,
method: request.method,
parameters: request.params,
encoding: parameterEncoding,
headers: headers
)
}
}
alamoFireRequest.validate().responseJSON { response in
switch response.result {
case .success(_):
self.requestSucceeded(request, response: response)
case .failure(_):
//4/20/16
//responseJSON() Fails a empty response always, unless 204
//If status code valid and response empty succeed
let acceptableStatusCodes: CountableRange<Int> = 200..<300
if
let statusCode = response.response?.statusCode , acceptableStatusCodes.contains(statusCode),
let data = response.data , data.count == 0
{
let response = DataResponse<Any>(request: nil, response: nil, data: nil, result: Result.success(""))
self.requestSucceeded(request, response: response)
} else {
self.requestFailed(request, response: response)
}
}
}
return alamoFireRequest
}
/// Create and Resume Alamofire Request
///
/// - Parameter withAPIRequest:APIRequest
/// - Return Request?
open func makeRequest(withAPIRequest request: APIRequest) -> Request? {
let request = self.createRequest(withAPIRequest: request)
request?.task?.resume()
return request
}
//9/19/2016 upload and download support will be updated to Swift 3.* shortly
/*
//MARK: - Make / Create Streaming Request
/// Create NSURLSessionUploadTask
///
/// - Parameter withAPIRequest:APIRequest
/// - Parameter completion: (result: MakeStreamingRequestResult) -> Void
open func createStreamingRequest(withAPIRequest request: APIRequest, completion: @escaping (_ result: MakeStreamingRequestResult) -> Void) {
//Assert for debug but allow
if request.requestTimeoutInterval != nil {
assertionFailure("APIRequest 'requestTimeoutInterval' currently only supported for data tasks.")
}
guard let url = urlWithBaseUrl(path: request.path) else {
let error = NSError(domain: "", code: 1, userInfo: [:])
request.requestFailed(withResponse: DataResponse<Any>(request: nil, response: nil, data: nil, result: Result.failure(error)))
assertionFailure("APIRequest invalid manager.baseurl + request path or request.path. Not able to convert to url")
return
}
//prepare headers
var headers = self.headers
headers += request.headers
//create full URL
let URL = self.baseURL.appendingPathComponent(request.path)
upload(request.method, multipartFormData: { (data) in
for (k,v) in request.binaryDataMultipart! {
data.appendBodyPart(data: v, name: k)
}
}, URL, headers: headers, encodingMemoryThreshold: Alamofire.Manager.MultipartFormDataEncodingMemoryThreshold)
{ result in
switch result {
case .success(let alamofireRequest, _, _):
completion(result: MakeStreamingRequestResult.success(task: alamofireRequest.task as! URLSessionUploadTask))
case .failure(let error):
completion(result: MakeStreamingRequestResult.failure(error: error as NSError))
}
}
}
/// Create and Make NSURLSessionUploadTask
///
/// - Parameter withAPIRequest:APIRequest
/// - Parameter completion: (result: MakeStreamingRequestResult) -> Void
open func makeStreamingRequest(withAPIRequest request: APIRequest, completion: @escaping (_ result: MakeStreamingRequestResult) -> Void) {
createStreamingRequest(withAPIRequest: request) { response in
switch response {
case .success(let task):
task.resume()
completion(MakeStreamingRequestResult.success(task: task))
case .failure(let error):
completion(MakeStreamingRequestResult.failure(error: error as NSError))
}
}
}
//MARK: - Make / Create Download Request
/// Create Alamofire Download Request
///
/// - Parameter withAPIRequest:APIRequest
/// - Return Request?
open func createDownloadRequest(withAPIRequest request: APIRequest, streamToURL url: URL) -> Request? {
//Assert for debug but allow
if request.requestTimeoutInterval != nil {
assertionFailure("APIRequest 'requestTimeoutInterval' currently only supported for data tasks.")
}
//prepare headers
var headers = self.headers
headers += request.headers
//create full URL
let URL = baseURL.appendingPathComponent(request.path)
//encoding
let parameterEncoding = alamofireEncoding(forRequest: request)
let destination: Request.DownloadFileDestination = { _, _ in
return (URL, [.createIntermediateDirectories, .removePreviousFile])
}
return download(URL,
method: request.method,
parameters: request.params,
encoding: parameterEncoding,
headers: headers,
to: destination
)
}
/// Create and Resume Alamofire Download Request
///
/// - Parameter withAPIRequest:APIRequest
/// - Return Request?
open func makeDownloadRequest(withAPIRequest request: APIRequest, streamToURL url: URL) -> Request? {
let alamofireRequestTask = self.createDownloadRequest(withAPIRequest: request, streamToURL: url)
alamofireRequestTask?.resume()
return alamofireRequestTask
}
*/
//MARK: - RequestResponder
open func requestSucceeded(_ request: APIRequest, response: APIResponse) {
request.requestSucceeded(withResponse: response)
}
open func requestFailed(_ request: APIRequest, response: APIResponse) {
request.requestFailed(withResponse: response)
}
//MARK: - Create / Make Request Helpers
// Return URL by either returning request path appended to self.baseUrl if self.baseUrl is not nil
// Otherwise attempt to create Url from path
//
// - Parameter path: String
// - Return URL?
private func urlWithBaseUrl(path: String) -> URL? {
let urlFromPathOrAppendedToBaseUrl: URL?
if let baseUrl = self.baseUrl {
urlFromPathOrAppendedToBaseUrl = baseUrl.appendingPathComponent(path)
} else {
urlFromPathOrAppendedToBaseUrl = URL(string: path)
}
return urlFromPathOrAppendedToBaseUrl
}
//MARK: - Determine URL Encoding for Request
/// Maps request.parameterEncoding (APIParameterEncoding) to Alamofire's ParameterEncoding
///
/// - Parameter forRequest: APIRequest
/// - Return Alamofire.ParameterEncoding
private func alamofireEncoding(forRequest request: APIRequest) -> ParameterEncoding {
//if NOT .post, .put, or .patch return URLEncoding
guard [APIRequestMethod.post, APIRequestMethod.put, APIRequestMethod.patch].filter({ $0 == request.method }).last != nil else {
return URLEncoding(destination: request.urlParameterEncodingDestination)
}
//what is clients Alamofire's ParameterEncoding value
//used for clientDefault below
let clientParameterEncoding: ParameterEncoding
switch parameterEncoding {
case .url:
clientParameterEncoding = URLEncoding(destination: request.urlParameterEncodingDestination)
case .json:
clientParameterEncoding = JSONEncoding(options: [])
}
let requestParameterEncoding: ParameterEncoding
switch request.parameterEncoding {
case .url:
requestParameterEncoding = URLEncoding(destination: request.urlParameterEncodingDestination)
case .json:
requestParameterEncoding = JSONEncoding(options: [])
case .clientDefault:
requestParameterEncoding = clientParameterEncoding
}
return requestParameterEncoding
}
}
//MARK: - Top Level Helpers
fileprivate func +=<K, V> (left: inout [K : V], right: [K : V]) {
for (k, v) in right {
left[k] = v
}
}
fileprivate extension String {
func split(_ delimiter: Character) -> [String] {
return self.characters.split { $0 == delimiter }.map(String.init)
}
}
| mit | 0f3aa41da41b15b7bbb1faf710fb3bd9 | 36.874109 | 152 | 0.615052 | 5.569333 | false | false | false | false |
mathewa6/Practise | PancakeSort.playground/section-1.swift | 1 | 3064 | //import Cocoa
//import Fou ndation
var pancakes: Array = [8, 1, 6, 7, 2]
/**
//Just seeing if I remember stuff
func exchange<T>(data : T[], i: Int, j:Int)
{
let temp = data[i]
data[i] = data[j]
data[j] = temp
}
func invert<T>(data: T[])
{
for i in 0..data.count {
if i != (data.count - 1) - i {
exchange(data, i, (data.count - 1) - i)
}
}
}
*/
//WHY THE HELL AREN'T THE NEXT TWO LINES WORKING ???
//invert(pancakes)
//pancakes
func indexOfLargestElement<T: Comparable>(inArray array: [T]) -> Int
{
var indexOfLargestElement: Int = -1
if !array.isEmpty {
indexOfLargestElement = 0
for index in (1..<array.count) {
if array[indexOfLargestElement] < array[index] {
indexOfLargestElement = index
}
}
}
return indexOfLargestElement
}
func subArray<T>(ofArray array: [T], withRange range: Range<Int>) -> Array<T>
{
var returnArray: Array = [T]()
if !array.isEmpty {
for index in range {
returnArray.append(array[index])
}
}
return returnArray
}
func flip<T>(flipIndex: Int, array: [T]) -> [T] {
var returnArray = array
// If index is less than number of elements
if flipIndex < returnArray.count && !returnArray.isEmpty {
// Create temp array of pancakes to flip
var pileToFlip = [T]()
// Iterate over pancakes
for (index, element) in returnArray.enumerate() {
// Till spatula is reached append to temp array
pileToFlip.append(element)
if index == flipIndex {
// On reaching spatula, reverse temp array to flip
pileToFlip = pileToFlip.reverse()
for i in (0...index).reverse() {
// Copy values to original array and break
returnArray[i] = pileToFlip[i]
}
break
}
}
}
return returnArray
}
func pancakeSort<T: Comparable>(pile: [T]) -> [T] {
var sortingPile = pile
if !sortingPile.isEmpty {
for i in (0..<sortingPile.count).reverse() {
if indexOfLargestElement(inArray: subArray(ofArray: sortingPile, withRange: 0..<i)) != 0 {
sortingPile = flip(indexOfLargestElement(inArray: subArray(ofArray: sortingPile, withRange: 0..<i)), array: sortingPile)
}
sortingPile = flip(i, array: sortingPile)
}
}
return sortingPile
}
pancakes = pancakeSort(pancakes)
pancakes
/*
var final = T[]()
var elementsToSort = subArray(ofArray: pile, withRange: 0..pile.count)
while !elementsToSort.isEmpty {
var currentIndex = indexOfLargestElement(inArray: elementsToSort)
if currentIndex == elementsToSort.endIndex {
continue
}
else if currentIndex == 0 {
flip(elementsToSort.endIndex, elementsToSort)
}
else {
flip(indexOfLargestElement(inArray: elementsToSort), elementsToSort)
flip(elementsToSort.endIndex, elementsToSort)
}
final.append(elementsToSort.removeLast())
elementsToSort
}
final
*/
| mit | e0033eed977b719fbdff238143e5e964 | 25.188034 | 136 | 0.605744 | 3.691566 | false | false | false | false |
Shopify/mobile-buy-sdk-ios | Buy/Generated/Storefront/MoneyV2.swift | 1 | 3272 | //
// MoneyV2.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// A monetary value with currency.
open class MoneyV2Query: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = MoneyV2
/// Decimal money amount.
@discardableResult
open func amount(alias: String? = nil) -> MoneyV2Query {
addField(field: "amount", aliasSuffix: alias)
return self
}
/// Currency of the money.
@discardableResult
open func currencyCode(alias: String? = nil) -> MoneyV2Query {
addField(field: "currencyCode", aliasSuffix: alias)
return self
}
}
/// A monetary value with currency.
open class MoneyV2: GraphQL.AbstractResponse, GraphQLObject, PricingValue, SellingPlanCheckoutChargeValue {
public typealias Query = MoneyV2Query
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "amount":
guard let value = value as? String else {
throw SchemaViolationError(type: MoneyV2.self, field: fieldName, value: fieldValue)
}
return Decimal(string: value, locale: GraphQL.posixLocale)
case "currencyCode":
guard let value = value as? String else {
throw SchemaViolationError(type: MoneyV2.self, field: fieldName, value: fieldValue)
}
return CurrencyCode(rawValue: value) ?? .unknownValue
default:
throw SchemaViolationError(type: MoneyV2.self, field: fieldName, value: fieldValue)
}
}
/// Decimal money amount.
open var amount: Decimal {
return internalGetAmount()
}
func internalGetAmount(alias: String? = nil) -> Decimal {
return field(field: "amount", aliasSuffix: alias) as! Decimal
}
/// Currency of the money.
open var currencyCode: Storefront.CurrencyCode {
return internalGetCurrencyCode()
}
func internalGetCurrencyCode(alias: String? = nil) -> Storefront.CurrencyCode {
return field(field: "currencyCode", aliasSuffix: alias) as! Storefront.CurrencyCode
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
return []
}
}
}
| mit | bdffc7419afbea9b496fca26d6727ddd | 33.442105 | 108 | 0.726773 | 4.059553 | false | false | false | false |
danielallsopp/Charts | Source/Charts/Filters/ChartDataApproximatorFilter.swift | 15 | 7318 | //
// ChartDataApproximator.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
public class ChartDataApproximatorFilter: ChartDataBaseFilter
{
@objc
public enum ApproximatorType: Int
{
case None
case RamerDouglasPeucker
}
/// the type of filtering algorithm to use
public var type = ApproximatorType.None
/// the tolerance to be filtered with
/// When using the Douglas-Peucker-Algorithm, the tolerance is an angle in degrees, that will trigger the filtering
public var tolerance = Double(0.0)
public var scaleRatio = Double(1.0)
public var deltaRatio = Double(1.0)
public override init()
{
super.init()
}
/// Initializes the approximator with the given type and tolerance.
/// If toleranec <= 0, no filtering will be done.
public init(type: ApproximatorType, tolerance: Double)
{
super.init()
setup(type, tolerance: tolerance)
}
/// Sets type and tolerance.
/// If tolerance <= 0, no filtering will be done.
public func setup(type: ApproximatorType, tolerance: Double)
{
self.type = type
self.tolerance = tolerance
}
/// Sets the ratios for x- and y-axis, as well as the ratio of the scale levels
public func setRatios(deltaRatio: Double, scaleRatio: Double)
{
self.deltaRatio = deltaRatio
self.scaleRatio = scaleRatio
}
/// Filters according to type. Uses the pre set set tolerance
///
/// - parameter points: the points to filter
public override func filter(points: [ChartDataEntry]) -> [ChartDataEntry]
{
return filter(points, tolerance: tolerance)
}
/// Filters according to type.
///
/// - parameter points: the points to filter
/// - parameter tolerance: the angle in degrees that will trigger the filtering
public func filter(points: [ChartDataEntry], tolerance: Double) -> [ChartDataEntry]
{
if (tolerance <= 0)
{
return points
}
switch (type)
{
case .RamerDouglasPeucker:
return reduceWithDouglasPeuker(points, epsilon: tolerance)
case .None:
return points
}
}
/// uses the douglas peuker algorithm to reduce the given arraylist of entries
private func reduceWithDouglasPeuker(entries: [ChartDataEntry], epsilon: Double) -> [ChartDataEntry]
{
// if a shape has 2 or less points it cannot be reduced
if (epsilon <= 0 || entries.count < 3)
{
return entries
}
var keep = [Bool](count: entries.count, repeatedValue: false)
// first and last always stay
keep[0] = true
keep[entries.count - 1] = true
// first and last entry are entry point to recursion
algorithmDouglasPeucker(entries, epsilon: epsilon, start: 0, end: entries.count - 1, keep: &keep)
// create a new array with series, only take the kept ones
var reducedEntries = [ChartDataEntry]()
for i in 0 ..< entries.count
{
if (keep[i])
{
let curEntry = entries[i]
reducedEntries.append(ChartDataEntry(value: curEntry.value, xIndex: curEntry.xIndex))
}
}
return reducedEntries
}
/// apply the Douglas-Peucker-Reduction to an ArrayList of Entry with a given epsilon (tolerance)
///
/// - parameter entries:
/// - parameter epsilon: as y-value
/// - parameter start:
/// - parameter end:
private func algorithmDouglasPeucker(entries: [ChartDataEntry], epsilon: Double, start: Int, end: Int, inout keep: [Bool])
{
if (end <= start + 1)
{
// recursion finished
return
}
// find the greatest distance between start and endpoint
var maxDistIndex = Int(0)
var distMax = Double(0.0)
let firstEntry = entries[start]
let lastEntry = entries[end]
for i in start + 1 ..< end
{
let dist = calcAngleBetweenLines(firstEntry, end1: lastEntry, start2: firstEntry, end2: entries[i])
// keep the point with the greatest distance
if (dist > distMax)
{
distMax = dist
maxDistIndex = i
}
}
if (distMax > epsilon)
{
// keep max dist point
keep[maxDistIndex] = true
// recursive call
algorithmDouglasPeucker(entries, epsilon: epsilon, start: start, end: maxDistIndex, keep: &keep)
algorithmDouglasPeucker(entries, epsilon: epsilon, start: maxDistIndex, end: end, keep: &keep)
} // else don't keep the point...
}
/// calculate the distance between a line between two entries and an entry (point)
///
/// - parameter startEntry: line startpoint
/// - parameter endEntry: line endpoint
/// - parameter entryPoint: the point to which the distance is measured from the line
private func calcPointToLineDistance(startEntry: ChartDataEntry, endEntry: ChartDataEntry, entryPoint: ChartDataEntry) -> Double
{
let xDiffEndStart = Double(endEntry.xIndex) - Double(startEntry.xIndex)
let xDiffEntryStart = Double(entryPoint.xIndex) - Double(startEntry.xIndex)
let normalLength = sqrt((xDiffEndStart)
* (xDiffEndStart)
+ (endEntry.value - startEntry.value)
* (endEntry.value - startEntry.value))
return Double(fabs((xDiffEntryStart)
* (endEntry.value - startEntry.value)
- (entryPoint.value - startEntry.value)
* (xDiffEndStart))) / Double(normalLength)
}
/// Calculates the angle between two given lines. The provided entries mark the starting and end points of the lines.
private func calcAngleBetweenLines(start1: ChartDataEntry, end1: ChartDataEntry, start2: ChartDataEntry, end2: ChartDataEntry) -> Double
{
let angle1 = calcAngleWithRatios(start1, p2: end1)
let angle2 = calcAngleWithRatios(start2, p2: end2)
return fabs(angle1 - angle2)
}
/// calculates the angle between two entries (points) in the chart taking ratios into consideration
private func calcAngleWithRatios(p1: ChartDataEntry, p2: ChartDataEntry) -> Double
{
let dx = Double(p2.xIndex) * Double(deltaRatio) - Double(p1.xIndex) * Double(deltaRatio)
let dy = p2.value * scaleRatio - p1.value * scaleRatio
return atan2(Double(dy), dx) * ChartUtils.Math.RAD2DEG
}
// calculates the angle between two entries (points) in the chart
private func calcAngle(p1: ChartDataEntry, p2: ChartDataEntry) -> Double
{
let dx = p2.xIndex - p1.xIndex
let dy = p2.value - p1.value
return atan2(Double(dy), Double(dx)) * ChartUtils.Math.RAD2DEG
}
} | apache-2.0 | 31065f59368b9bdd9f84db32f9621f5a | 33.200935 | 140 | 0.609319 | 4.534077 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Stats/Insights/StatsMostPopularTimeInsightsCell.swift | 1 | 8293 | import UIKit
class StatsMostPopularTimeInsightsCell: StatsBaseCell {
private var data: StatsMostPopularTimeData? = nil
private weak var siteStatsInsightsDelegate: SiteStatsInsightsDelegate?
// MARK: - Subviews
private var outerStackView: UIStackView!
private var noDataLabel: UILabel!
private var topLeftLabel: UILabel!
private var middleLeftLabel: UILabel!
private var bottomLeftLabel: UILabel!
private var topRightLabel: UILabel!
private var middleRightLabel: UILabel!
private var bottomRightLabel: UILabel!
// MARK: - Initialization
required override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
configureView()
}
required init(coder: NSCoder) {
fatalError()
}
override func prepareForReuse() {
super.prepareForReuse()
displayNoData(show: false)
}
// MARK: - View Configuration
private func configureView() {
selectionStyle = .none
outerStackView = makeOuterStackView()
contentView.addSubview(outerStackView)
topConstraint = outerStackView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: StatsBaseCell.Metrics.padding)
NSLayoutConstraint.activate([
topConstraint,
outerStackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -StatsBaseCell.Metrics.padding),
outerStackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: StatsBaseCell.Metrics.padding),
outerStackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -StatsBaseCell.Metrics.padding),
])
noDataLabel = makeNoDataLabel()
contentView.addSubview(noDataLabel)
outerStackView.pinSubviewToAllEdges(noDataLabel)
noDataLabel.isHidden = true
}
private func makeOuterStackView() -> UIStackView {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .horizontal
stackView.spacing = Metrics.horizontalStackViewSpacing
let leftStackView = makeLeftStackView()
let rightStackView = makeRightStackView()
let divider = makeVerticalDivider()
stackView.addArrangedSubviews([leftStackView, divider, rightStackView])
configureInnerStackViews(leftStackView: leftStackView,
rightStackView: rightStackView)
NSLayoutConstraint.activate([
leftStackView.widthAnchor.constraint(equalTo: rightStackView.widthAnchor),
divider.widthAnchor.constraint(equalToConstant: Metrics.dividerWidth)
])
return stackView
}
private func makeLeftStackView() -> UIStackView {
let leftStackView = UIStackView()
leftStackView.translatesAutoresizingMaskIntoConstraints = false
leftStackView.axis = .vertical
return leftStackView
}
private func makeRightStackView() -> UIStackView {
let rightStackView = UIStackView()
rightStackView.translatesAutoresizingMaskIntoConstraints = false
rightStackView.axis = .vertical
return rightStackView
}
private func makeVerticalDivider() -> UIView {
let divider = UIView()
divider.translatesAutoresizingMaskIntoConstraints = false
WPStyleGuide.Stats.configureViewAsVerticalSeparator(divider)
return divider
}
private func configureInnerStackViews(leftStackView: UIStackView,
rightStackView: UIStackView) {
let leftLabels = configure(verticalStackView: leftStackView)
let rightLabels = configure(verticalStackView: rightStackView)
topLeftLabel = leftLabels.topLabel
middleLeftLabel = leftLabels.middleLabel
bottomLeftLabel = leftLabels.bottomLabel
topRightLabel = rightLabels.topLabel
middleRightLabel = rightLabels.middleLabel
bottomRightLabel = rightLabels.bottomLabel
}
private func configure(verticalStackView: UIStackView) -> (topLabel: UILabel, middleLabel: UILabel, bottomLabel: UILabel) {
let topLabel = UILabel()
topLabel.textColor = .text
topLabel.font = .preferredFont(forTextStyle: .body)
topLabel.numberOfLines = 0
let middleLabel = UILabel()
middleLabel.textColor = .text
middleLabel.font = WPStyleGuide.Stats.insightsCountFont
middleLabel.adjustsFontForContentSizeCategory = true
middleLabel.numberOfLines = 0
let bottomLabel = UILabel()
bottomLabel.textColor = .textSubtle
bottomLabel.font = .preferredFont(forTextStyle: .body)
bottomLabel.numberOfLines = 0
verticalStackView.spacing = Metrics.verticalStackViewSpacing
verticalStackView.addArrangedSubviews([topLabel, middleLabel, bottomLabel])
return (topLabel: topLabel, middleLabel: middleLabel, bottomLabel: bottomLabel)
}
private func makeNoDataLabel() -> UILabel {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = .preferredFont(forTextStyle: .body)
label.textColor = .textSubtle
label.numberOfLines = 0
label.text = TextContent.noData
return label
}
private func displayNoData(show: Bool) {
outerStackView.subviews.forEach({ $0.isHidden = show })
noDataLabel.isHidden = !show
}
// MARK: Public configuration
func configure(data: StatsMostPopularTimeData?, siteStatsInsightsDelegate: SiteStatsInsightsDelegate?) {
self.data = data
self.statSection = .insightsMostPopularTime
self.siteStatsInsightsDelegate = siteStatsInsightsDelegate
guard let data = data else {
displayNoData(show: true)
return
}
topLeftLabel.text = data.mostPopularDayTitle
middleLeftLabel.text = data.mostPopularDay
bottomLeftLabel.text = data.dayPercentage
topRightLabel.text = data.mostPopularTimeTitle
middleRightLabel.text = data.mostPopularTime
bottomRightLabel.text = data.timePercentage
}
private enum Metrics {
static let horizontalStackViewSpacing: CGFloat = 16.0
static let verticalStackViewSpacing: CGFloat = 8.0
static let dividerWidth: CGFloat = 1.0
}
private enum TextContent {
static let noData = NSLocalizedString("stats.insights.mostPopularTime.noData", value: "Not enough activity. Check back later when your site's had more visitors!", comment: "Hint displayed on the 'Most Popular Time' stats card when a user's site hasn't yet received enough traffic.")
}
}
// MARK: - Data / View Model
struct StatsMostPopularTimeData {
var mostPopularDayTitle: String
var mostPopularTimeTitle: String
var mostPopularDay: String
var mostPopularTime: String
var dayPercentage: String
var timePercentage: String
}
// MARK: - Model Formatting Helpers
extension StatsAnnualAndMostPopularTimeInsight {
func formattedMostPopularDay() -> String? {
guard var mostPopularWeekday = mostPopularDayOfWeek.weekday else {
return nil
}
var calendar = Calendar.init(identifier: .gregorian)
calendar.locale = Locale.autoupdatingCurrent
// Back up mostPopularWeekday by 1 to get correct index for standaloneWeekdaySymbols.
mostPopularWeekday = mostPopularWeekday == 0 ? calendar.standaloneWeekdaySymbols.count - 1 : mostPopularWeekday - 1
return calendar.standaloneWeekdaySymbols[mostPopularWeekday]
}
func formattedMostPopularTime() -> String? {
var calendar = Calendar.init(identifier: .gregorian)
calendar.locale = Locale.autoupdatingCurrent
guard let hour = mostPopularHour.hour,
let timeModifiedDate = calendar.date(bySettingHour: hour, minute: 0, second: 0, of: Date()) else {
return nil
}
let timeFormatter = DateFormatter()
timeFormatter.setLocalizedDateFormatFromTemplate("h a")
return timeFormatter.string(from: timeModifiedDate).uppercased()
}
}
| gpl-2.0 | 08df0be13a2cb5b7629bce5dde59ef16 | 34.139831 | 290 | 0.699264 | 5.513963 | false | false | false | false |
DeveloperLx/LxNavigationController-swift | LxNavigationController.swift | 1 | 6918 | //
// LxNavigationController.swift
// LxNavigationControllerDemo
//
// Created by DeveloperLx on 15/7/3.
// Copyright (c) 2015年 DeveloperLx. All rights reserved.
//
import UIKit
enum LxNavigationControllerInteractionStopReason {
case Finished, Cancelled, Failed
}
let POP_ANIMATION_DURATION = 0.2
let MIN_VALID_PROPORTION = 0.6
class PopTransition: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
return POP_ANIMATION_DURATION
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!
let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!
transitionContext.containerView().insertSubview(toViewController.view, belowSubview: fromViewController.view)
toViewController.view.frame.origin.x = -toViewController.view.frame.size.width/2
toViewController.view.alpha = fromViewController.view.alpha - 0.2
UIView.animateWithDuration(POP_ANIMATION_DURATION, animations: { () -> Void in
fromViewController.view.frame.origin.x = fromViewController.view.frame.size.width
toViewController.view.frame.origin.x = 0
toViewController.view.alpha = 1
}) { (finished) -> Void in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
}
}
}
class LxNavigationController: UINavigationController, UINavigationControllerDelegate,UIGestureRecognizerDelegate {
var popGestureRecognizerEnable: Bool {
set {
_popGestureRecognizer.enabled = newValue
}
get {
return _popGestureRecognizer.enabled
}
}
var recognizeOtherGestureSimultaneously = false
var isTranslating = false
var popGestureRecognizerBeginCallBack = { () -> () in }
var popGestureRecognizerStopBlock = { (stopReason: LxNavigationControllerInteractionStopReason) -> () in }
var rootViewController: UIViewController? {
return viewControllers.first as? UIViewController
}
let _popGestureRecognizer = UIPanGestureRecognizer()
var _interactivePopTransition: UIPercentDrivenInteractiveTransition?
convenience init () {
self.init()
setup()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(navigationBarClass: AnyClass?, toolbarClass: AnyClass?) {
super.init(navigationBarClass: navigationBarClass, toolbarClass: toolbarClass)
setup()
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// setup()
}
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
setup()
}
func setup() {
delegate = self
interactivePopGestureRecognizer.enabled = false
_popGestureRecognizer.addTarget(self, action: Selector("popGestureRecognizerTriggerd:"))
_popGestureRecognizer.delegate = self
_popGestureRecognizer.cancelsTouchesInView = false
_popGestureRecognizer.maximumNumberOfTouches = 1
interactivePopGestureRecognizer.view?.addGestureRecognizer(_popGestureRecognizer)
}
// MARK:- UINavigationControllerDelegate
func navigationController(navigationController: UINavigationController, interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if animationController is PopTransition {
return _interactivePopTransition
}
else {
return nil
}
}
func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if operation == .Pop {
return PopTransition()
}
else {
return nil
}
}
func popGestureRecognizerTriggerd(popPan: UIPanGestureRecognizer) {
var progress = popPan.translationInView(popPan.view!).x / popPan.view!.bounds.size.width
progress = max(0, progress)
progress = min(1, progress)
switch popPan.state {
case .Began:
isTranslating = true
_interactivePopTransition = UIPercentDrivenInteractiveTransition()
popViewControllerAnimated(true)
self.popGestureRecognizerBeginCallBack()
case .Changed:
_interactivePopTransition?.updateInteractiveTransition(progress)
case .Failed:
isTranslating = false
self.popGestureRecognizerStopBlock(.Failed)
default:
if progress > CGFloat(MIN_VALID_PROPORTION) {
_interactivePopTransition?.finishInteractiveTransition()
self.popGestureRecognizerStopBlock(.Finished)
}
else {
_interactivePopTransition?.cancelInteractiveTransition()
self.popGestureRecognizerStopBlock(.Cancelled)
}
_interactivePopTransition = nil
isTranslating = false
}
}
func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == _popGestureRecognizer {
let location = gestureRecognizer.locationInView(gestureRecognizer.view)
let translationX = _popGestureRecognizer.translationInView(gestureRecognizer.view!).x
if location.x > gestureRecognizer.view!.frame.size.width * CGFloat(MIN_VALID_PROPORTION) || translationX < 0 || viewControllers.count < 2 {
return false
}
else {
return true
}
}
else {
return true
}
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == _popGestureRecognizer || otherGestureRecognizer == _popGestureRecognizer {
return recognizeOtherGestureSimultaneously
}
else {
return false
}
}
}
| apache-2.0 | 5896dfc1c718c69a8b88ad2374a1e552 | 34.466667 | 281 | 0.665124 | 6.339138 | false | false | false | false |
narner/AudioKit | AudioKit/Common/User Interface/AKView.swift | 1 | 3230 | //
// AKView.swift
// AudioKitUI
//
// Created by Stéphane Peter, revision history on Github.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
#if os(macOS)
public typealias AKView = NSView
public typealias AKColor = NSColor
#else
public typealias AKView = UIView
public typealias AKColor = UIColor
#endif
/// Class to handle colors, fonts, etc.
public enum AKTheme {
case basic
case midnight
}
public class AKStylist {
public static let sharedInstance = AKStylist()
public var bgColor: AKColor {
return bgColors[theme]!
}
public var fontColor: AKColor {
return fontColors[theme]!
}
public var theme = AKTheme.midnight
private var bgColors: [AKTheme: AKColor]
private var fontColors: [AKTheme: AKColor]
private var colorCycle: [AKTheme: [AKColor]]
var counter = 0
init() {
fontColors = Dictionary()
fontColors[.basic] = AKColor.black
fontColors[.midnight] = AKColor.white
bgColors = Dictionary()
bgColors[.basic] = AKColor.white
bgColors[.midnight] = #colorLiteral(red: 0.1019607843, green: 0.1019607843, blue: 0.1019607843, alpha: 1)
colorCycle = Dictionary()
colorCycle[.basic] = [AKColor(red: 165.0 / 255.0, green: 26.0 / 255.0, blue: 216.0 / 255.0, alpha: 1.0),
AKColor(red: 238.0 / 255.0, green: 66.0 / 255.0, blue: 102.0 / 255.0, alpha: 1.0),
AKColor(red: 244.0 / 255.0, green: 96.0 / 255.0, blue: 54.0 / 255.0, alpha: 1.0),
AKColor(red: 36.0 / 255.0, green: 110.0 / 255.0, blue: 185.0 / 255.0, alpha: 1.0),
AKColor(red: 14.0 / 255.0, green: 173.0 / 255.0, blue: 105.0 / 255.0, alpha: 1.0)]
colorCycle[.midnight] = [AKColor(red: 165.0 / 255.0, green: 26.0 / 255.0, blue: 216.0 / 255.0, alpha: 1.0),
AKColor(red: 238.0 / 255.0, green: 66.0 / 255.0, blue: 102.0 / 255.0, alpha: 1.0),
AKColor(red: 244.0 / 255.0, green: 96.0 / 255.0, blue: 54.0 / 255.0, alpha: 1.0),
AKColor(red: 36.0 / 255.0, green: 110.0 / 255.0, blue: 185.0 / 255.0, alpha: 1.0),
AKColor(red: 14.0 / 255.0, green: 173.0 / 255.0, blue: 105.0 / 255.0, alpha: 1.0)]
}
public var nextColor: AKColor {
get {
counter += 1
if counter >= colorCycle[theme]!.count {
counter = 0
}
return colorCycle[theme]![counter]
}
}
public var colorForTrueValue: AKColor {
switch theme {
case .basic: return AKColor(red: 35.0 / 255.0, green: 206.0 / 255.0, blue: 92.0 / 255.0, alpha: 1.0)
case .midnight: return AKColor(red: 35.0 / 255.0, green: 206.0 / 255.0, blue: 92.0 / 255.0, alpha: 1.0)
}
}
public var colorForFalseValue: AKColor {
switch theme {
case .basic: return AKColor(red: 255.0 / 255.0, green: 22.0 / 255.0, blue: 22.0 / 255.0, alpha: 1.0)
case .midnight: return AKColor(red: 255.0 / 255.0, green: 22.0 / 255.0, blue: 22.0 / 255.0, alpha: 1.0)
}
}
}
| mit | 5fba7e85ac4a93b43a0420b421217a59 | 35.681818 | 115 | 0.553284 | 3.380105 | false | false | false | false |
wireapp/wire-ios-data-model | Source/Utilis/Protos/GenericMessage+Helper.swift | 1 | 22908 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireProtos
// MARK: - GenericMessage
public extension GenericMessage {
init?(withBase64String base64String: String?) {
guard
let string = base64String,
let data = Data(base64Encoded: string),
let message = GenericMessage.with({ try? $0.merge(serializedData: data) }).validatingFields()
else { return nil }
self = message
}
init(content: EphemeralMessageCapable, nonce: UUID = UUID(), expiresAfter timeout: MessageDestructionTimeoutValue? = nil) {
self.init(content: content, nonce: nonce, expiresAfterTimeInterval: timeout?.rawValue)
}
init(content: EphemeralMessageCapable, nonce: UUID = UUID(), expiresAfterTimeInterval timeout: TimeInterval? = nil) {
self = GenericMessage.with {
$0.messageID = nonce.transportString()
let messageContent: MessageCapable
if let timeout = timeout, timeout > 0 {
messageContent = Ephemeral(content: content, expiresAfter: timeout)
} else {
messageContent = content
}
messageContent.setContent(on: &$0)
}
}
init(content: MessageCapable, nonce: UUID = UUID()) {
self = GenericMessage.with {
$0.messageID = nonce.transportString()
let messageContent = content
messageContent.setContent(on: &$0)
}
}
init(clientAction action: ClientAction, nonce: UUID = UUID()) {
self = GenericMessage.with {
$0.messageID = nonce.transportString()
$0.clientAction = action
}
}
}
extension GenericMessage {
public var messageData: MessageCapable? {
guard let content = content else { return nil }
switch content {
case .text(let data):
return data
case .confirmation(let data):
return data
case .reaction(let data):
return data
case .asset(let data):
return data
case .ephemeral(let data):
return data.messageData
case .clientAction(let data):
return data
case .cleared(let data):
return data
case .lastRead(let data):
return data
case .knock(let data):
return data
case .external(let data):
return data
case .availability(let data):
return data
case .edited(let data):
return data
case .deleted(let data):
return data
case .calling(let data):
return data
case .hidden(let data):
return data
case .location(let data):
return data
case .image(let data):
return data
case .composite(let data):
return data
case .buttonAction(let data):
return data
case .buttonActionConfirmation(let data):
return data
case .dataTransfer(let data):
return data
}
}
var locationData: Location? {
guard let content = content else { return nil }
switch content {
case .location(let data):
return data
case .ephemeral(let data):
switch data.content {
case .location(let data)?:
return data
default:
return nil
}
default:
return nil
}
}
public var compositeData: Composite? {
guard let content = content else { return nil }
switch content {
case .composite(let data):
return data
default:
return nil
}
}
public var imageAssetData: ImageAsset? {
guard let content = content else { return nil }
switch content {
case .image(let data):
return data
case .ephemeral(let data):
switch data.content {
case .image(let data)?:
return data
default:
return nil
}
default:
return nil
}
}
public var assetData: WireProtos.Asset? {
guard let content = content else { return nil }
switch content {
case .asset(let data):
return data
case .ephemeral(let data):
switch data.content {
case .asset(let data)?:
return data
default:
return nil
}
default:
return nil
}
}
public var knockData: Knock? {
guard let content = content else { return nil }
switch content {
case .knock(let data):
return data
case .ephemeral(let data):
switch data.content {
case .knock(let data)?:
return data
default:
return nil
}
default:
return nil
}
}
public var textData: Text? {
guard let content = content else { return nil }
switch content {
case .text(let data):
return data
case .edited(let messageEdit):
if case .text(let data)? = messageEdit.content {
return data
}
case .ephemeral(let ephemeral):
if case .text(let data)? = ephemeral.content {
return data
}
default:
return nil
}
return nil
}
}
public extension Text {
func isMentioningSelf(_ selfUser: ZMUser) -> Bool {
return mentions.any {$0.userID.uppercased() == selfUser.remoteIdentifier.uuidString }
}
func isQuotingSelf(_ quotedMessage: ZMOTRMessage?) -> Bool {
return quotedMessage?.sender?.isSelfUser ?? false
}
}
extension GenericMessage {
var v3_isImage: Bool {
return assetData?.original.hasRasterImage ?? false
}
var v3_uploadedAssetId: String? {
guard
let assetData = assetData,
case .uploaded? = assetData.status
else {
return nil
}
return assetData.uploaded.assetID
}
public var previewAssetId: String? {
guard
let assetData = assetData,
assetData.hasPreview,
assetData.preview.hasRemote,
assetData.preview.remote.hasAssetID
else {
return nil
}
return assetData.preview.remote.assetID
}
}
extension GenericMessage {
public var linkPreviews: [LinkPreview] {
guard let content = content else { return [] }
switch content {
case .text:
return text.linkPreview.compactMap { $0 }
case .edited:
return edited.text.linkPreview.compactMap { $0 }
case .ephemeral(let ephemeral):
if case .text? = ephemeral.content {
return ephemeral.text.linkPreview.compactMap { $0 }
} else {
return []
}
default:
return []
}
}
}
// MARK: - Ephemeral
extension Ephemeral {
public init(content: EphemeralMessageCapable, expiresAfter timeout: TimeInterval) {
self = Ephemeral.with {
$0.expireAfterMillis = Int64(timeout * 1000)
content.setEphemeralContent(on: &$0)
}
}
public var messageData: MessageCapable? {
guard let content = content else { return nil }
switch content {
case .text(let data):
return data
case .asset(let data):
return data
case .knock(let data):
return data
case .location(let data):
return data
case .image(let data):
return data
}
}
}
public extension Proteus_QualifiedUserId {
init(with uuid: UUID, domain: String) {
self = Proteus_QualifiedUserId.with {
$0.id = uuid.transportString()
$0.domain = domain
}
}
}
// MARK: - ClientEntry
public extension Proteus_ClientEntry {
init(withClient client: UserClient, data: Data) {
self = Proteus_ClientEntry.with {
$0.client = client.clientId
$0.text = data
}
}
}
// MARK: - QualifiedUserEntry
public extension Proteus_QualifiedUserEntry {
init(withDomain domain: String, userEntries: [Proteus_UserEntry]) {
self = Proteus_QualifiedUserEntry.with {
$0.domain = domain
$0.entries = userEntries
}
}
}
// MARK: - UserEntry
public extension Proteus_UserEntry {
init(withUser user: ZMUser, clientEntries: [Proteus_ClientEntry]) {
self = Proteus_UserEntry.with {
$0.user = user.userId
$0.clients = clientEntries
}
}
}
// MARK: - QualifiedNewOtrMessage
public extension Proteus_QualifiedNewOtrMessage {
init(withSender sender: UserClient,
nativePush: Bool,
recipients: [Proteus_QualifiedUserEntry],
missingClientsStrategy: MissingClientsStrategy,
blob: Data? = nil ) {
self = Proteus_QualifiedNewOtrMessage.with {
$0.nativePush = nativePush
$0.sender = sender.clientId
$0.recipients = recipients
if let blob = blob {
$0.blob = blob
}
switch missingClientsStrategy {
case .doNotIgnoreAnyMissingClient:
$0.clientMismatchStrategy = .reportAll(.init())
case .ignoreAllMissingClients:
$0.clientMismatchStrategy = .ignoreAll(.init())
case .ignoreAllMissingClientsNotFromUsers(users: let users):
$0.clientMismatchStrategy = .reportOnly(.with({
$0.userIds = users.compactMap({
guard
let uuid = $0.remoteIdentifier,
let domain = $0.domain
else {
return nil
}
return Proteus_QualifiedUserId(with: uuid, domain: domain)
})
}))
}
}
}
}
// MARK: - NewOtrMessage
public extension Proteus_NewOtrMessage {
init(withSender sender: UserClient, nativePush: Bool, recipients: [Proteus_UserEntry], blob: Data? = nil) {
self = Proteus_NewOtrMessage.with {
$0.nativePush = nativePush
$0.sender = sender.clientId
$0.recipients = recipients
if blob != nil {
$0.blob = blob!
}
}
}
}
// MARK: - ButtonAction
extension ButtonAction {
init(buttonId: String, referenceMessageId: UUID) {
self = ButtonAction.with {
$0.buttonID = buttonId
$0.referenceMessageID = referenceMessageId.transportString()
}
}
}
// MARK: - Location
extension Location {
init(latitude: Float, longitude: Float) {
self = WireProtos.Location.with {
$0.latitude = latitude
$0.longitude = longitude
}
}
}
// MARK: - Text
extension Text {
public init(content: String, mentions: [Mention] = [], linkPreviews: [LinkMetadata] = [], replyingTo: ZMOTRMessage? = nil) {
self = Text.with {
$0.content = content
$0.mentions = mentions.compactMap { WireProtos.Mention.createMention($0) }
$0.linkPreview = linkPreviews.map { WireProtos.LinkPreview($0) }
if let quotedMessage = replyingTo,
let quotedMessageNonce = quotedMessage.nonce,
let quotedMessageHash = quotedMessage.hashOfContent {
$0.quote = Quote.with {
$0.quotedMessageID = quotedMessageNonce.transportString()
$0.quotedMessageSha256 = quotedMessageHash
}
}
}
}
public func applyEdit(from text: Text) -> Text {
var updatedText = text
// Transfer read receipt expectation
updatedText.expectsReadConfirmation = expectsReadConfirmation
// We always keep the quote from the original message
hasQuote
? updatedText.quote = quote
: updatedText.clearQuote()
return updatedText
}
public func updateLinkPreview(from text: Text) -> Text {
guard !text.linkPreview.isEmpty else {
return self
}
do {
let data = try serializedData()
var updatedText = try Text(serializedData: data)
updatedText.linkPreview = text.linkPreview
return updatedText
} catch {
return self
}
}
}
// MARK: - Reaction
extension WireProtos.Reaction {
public static func createReaction(emoji: String, messageID: UUID) -> WireProtos.Reaction {
return WireProtos.Reaction.with({
$0.emoji = emoji
$0.messageID = messageID.transportString()
})
}
}
public enum ProtosReactionFactory {
public static func createReaction(emoji: String, messageID: UUID) -> WireProtos.Reaction {
return WireProtos.Reaction.createReaction(emoji: emoji,
messageID: messageID)
}
}
// MARK: - LastRead
extension LastRead {
public init(conversationID: UUID, lastReadTimestamp: Date) {
self = LastRead.with {
$0.conversationID = conversationID.transportString()
$0.lastReadTimestamp = Int64(lastReadTimestamp.timeIntervalSince1970 * 1000)
}
}
}
// MARK: - Calling
extension Calling {
public init(content: String) {
self = Calling.with {
$0.content = content
}
}
}
// MARK: - MessageEdit
extension WireProtos.MessageEdit {
public init(replacingMessageID: UUID, text: Text) {
self = MessageEdit.with {
$0.replacingMessageID = replacingMessageID.transportString()
$0.text = text
}
}
}
// MARK: - Cleared
extension Cleared {
public init(timestamp: Date, conversationID: UUID) {
self = Cleared.with {
$0.clearedTimestamp = Int64(timestamp.timeIntervalSince1970 * 1000)
$0.conversationID = conversationID.transportString()
}
}
}
// MARK: - MessageHide
extension MessageHide {
public init(conversationId: UUID, messageId: UUID) {
self = MessageHide.with {
$0.conversationID = conversationId.transportString()
$0.messageID = messageId.transportString()
}
}
}
// MARK: - MessageDelete
extension MessageDelete {
public init(messageId: UUID) {
self = MessageDelete.with {
$0.messageID = messageId.transportString()
}
}
}
// MARK: - Confirmation
extension WireProtos.Confirmation {
public init?(messageIds: [UUID], type: Confirmation.TypeEnum = .delivered) {
guard let firstMessageID = messageIds.first else {
return nil
}
let moreMessageIds = Array(messageIds.dropFirst())
self = WireProtos.Confirmation.with({
$0.firstMessageID = firstMessageID.transportString()
$0.moreMessageIds = moreMessageIds.map { $0.transportString() }
$0.type = type
})
}
public init(messageId: UUID, type: Confirmation.TypeEnum = .delivered) {
self = WireProtos.Confirmation.with {
$0.firstMessageID = messageId.transportString()
$0.type = type
}
}
}
// MARK: - External
extension External {
init(withOTRKey otrKey: Data, sha256: Data) {
self = External.with {
$0.otrKey = otrKey
$0.sha256 = sha256
}
}
init(withKeyWithChecksum key: ZMEncryptionKeyWithChecksum) {
self = External(withOTRKey: key.aesKey, sha256: key.sha256)
}
}
// MARK: - Mention
public extension WireProtos.Mention {
static func createMention(_ mention: WireDataModel.Mention) -> WireProtos.Mention? {
return mention.convertToProtosMention()
}
}
public extension WireDataModel.Mention {
func convertToProtosMention() -> WireProtos.Mention? {
guard let userID = (user as? ZMUser)?.remoteIdentifier.transportString() else { return nil }
return WireProtos.Mention.with {
$0.start = Int32(range.location)
$0.length = Int32(range.length)
$0.userID = userID
guard let domain = user.domain else { return }
$0.qualifiedUserID = WireProtos.QualifiedUserId.with {
$0.id = userID
$0.domain = domain
}
}
}
}
// MARK: - Availability
extension WireProtos.Availability {
public init(_ availability: AvailabilityKind) {
self = WireProtos.Availability.with {
switch availability {
case .none:
$0.type = .none
case .available:
$0.type = .available
case .away:
$0.type = .away
case .busy:
$0.type = .busy
}
}
}
}
// MARK: - LinkPreview
public extension LinkPreview {
init(_ linkMetadata: LinkMetadata) {
if let articleMetadata = linkMetadata as? ArticleMetadata {
self = LinkPreview(articleMetadata: articleMetadata)
} else if let twitterMetadata = linkMetadata as? TwitterStatusMetadata {
self = LinkPreview(twitterMetadata: twitterMetadata)
} else {
self = LinkPreview.with {
$0.url = linkMetadata.originalURLString
$0.permanentURL = linkMetadata.permanentURL?.absoluteString ?? linkMetadata.resolvedURL?.absoluteString ?? linkMetadata.originalURLString
$0.urlOffset = Int32(linkMetadata.characterOffsetInText)
}
}
}
init(articleMetadata: ArticleMetadata) {
self = LinkPreview.with {
$0.url = articleMetadata.originalURLString
$0.permanentURL = articleMetadata.permanentURL?.absoluteString ?? articleMetadata.resolvedURL?.absoluteString ?? articleMetadata.originalURLString
$0.urlOffset = Int32(articleMetadata.characterOffsetInText)
$0.title = articleMetadata.title ?? ""
$0.summary = articleMetadata.summary ?? ""
if let imageData = articleMetadata.imageData.first {
$0.image = WireProtos.Asset(imageSize: CGSize(width: 0, height: 0), mimeType: "image/jpeg", size: UInt64(imageData.count))
}
}
}
init(twitterMetadata: TwitterStatusMetadata) {
self = LinkPreview.with {
$0.url = twitterMetadata.originalURLString
$0.permanentURL = twitterMetadata.permanentURL?.absoluteString ?? twitterMetadata.resolvedURL?.absoluteString ?? twitterMetadata.originalURLString
$0.urlOffset = Int32(twitterMetadata.characterOffsetInText)
$0.title = twitterMetadata.message ?? ""
if let imageData = twitterMetadata.imageData.first {
$0.image = WireProtos.Asset(imageSize: CGSize(width: 0, height: 0), mimeType: "image/jpeg", size: UInt64(imageData.count))
}
guard let author = twitterMetadata.author,
let username = twitterMetadata.username else { return }
$0.tweet = WireProtos.Tweet.with({
$0.author = author
$0.username = username
})
}
}
init(withOriginalURL originalURL: String,
permanentURL: String,
offset: Int32,
title: String?,
summary: String?,
imageAsset: WireProtos.Asset?,
article: Article? = nil,
tweet: Tweet? = nil) {
self = LinkPreview.with {
$0.url = originalURL
$0.permanentURL = permanentURL
$0.urlOffset = offset
if let title = title {
$0.title = title
}
if let summary = summary {
$0.summary = summary
}
if let image = imageAsset {
$0.image = image
}
if let tweet = tweet {
$0.tweet = tweet
}
if let article = article {
$0.article = article
}
}
}
mutating func update(withOtrKey otrKey: Data, sha256: Data, original: WireProtos.Asset.Original?) {
image.uploaded = WireProtos.Asset.RemoteData(withOTRKey: otrKey, sha256: sha256)
if let original = original {
image.original = original
}
}
mutating func update(withAssetKey assetKey: String, assetToken: String?, assetDomain: String?) {
image.uploaded.assetID = assetKey
image.uploaded.assetToken = assetToken ?? ""
image.uploaded.assetDomain = assetDomain ?? ""
}
var hasTweet: Bool {
switch metaData {
case .tweet:
return true
default:
return false
}
}
}
public extension Tweet {
init(author: String?, username: String?) {
self = Tweet.with {
if let author = author {
$0.author = author
}
if let username = username {
$0.username = username
}
}
}
}
// MARK: - ImageAsset
extension ImageAsset {
public func imageFormat() -> ZMImageFormat {
return ImageFormatFromString(self.tag)
}
}
// MARK: - DataTransfer
extension DataTransfer {
init(trackingIdentifier: UUID) {
self = DataTransfer.with {
$0.trackingIdentifier = TrackingIdentifier(trackingIdentifier)
}
}
var trackingIdentifierData: String? {
guard
hasTrackingIdentifier,
trackingIdentifier.hasIdentifier
else {
return nil
}
return trackingIdentifier.identifier
}
}
// MARK: - TrackingIdentifier
extension TrackingIdentifier {
init(_ uuid: UUID) {
self = TrackingIdentifier.with {
$0.identifier = uuid.transportString()
}
}
}
| gpl-3.0 | 900b0c3e7fb2b9131b4c2f06260c5de5 | 28.182166 | 158 | 0.569976 | 4.711641 | false | false | false | false |
hughbe/swift | test/IRGen/objc_super.swift | 2 | 6657 | // RUN: %empty-directory(%t)
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
import gizmo
// CHECK: [[CLASS:%objc_class]] = type
// CHECK: [[TYPE:%swift.type]] = type
// CHECK: [[HOOZIT:%T10objc_super6HoozitC]] = type
// CHECK: [[PARTIAL_APPLY_CLASS:%T10objc_super12PartialApplyC]] = type
// CHECK: [[SUPER:%objc_super]] = type
// CHECK: [[OBJC:%objc_object]] = type
// CHECK: [[GIZMO:%TSo5GizmoC]] = type
// CHECK: [[NSRECT:%TSC6NSRectV]] = type
class Hoozit : Gizmo {
// CHECK: define hidden swiftcc void @_T010objc_super6HoozitC4frobyyF([[HOOZIT]]* swiftself) {{.*}} {
override func frob() {
// CHECK: [[T0:%.*]] = call [[TYPE]]* @_T010objc_super6HoozitCMa()
// CHECK: [[T1:%.*]] = bitcast [[TYPE]]* [[T0]] to [[CLASS]]*
// CHECK: store [[CLASS]]* [[T1]], [[CLASS]]** {{.*}}, align 8
// CHECK: load i8*, i8** @"\01L_selector(frob)"
// CHECK: call void bitcast (void ()* @objc_msgSendSuper2 to void ([[SUPER]]*, i8*)*)([[SUPER]]* {{.*}}, i8* {{.*}})
super.frob()
}
// CHECK: }
// CHECK: define hidden swiftcc void @_T010objc_super6HoozitC5runceyyFZ([[TYPE]]* swiftself) {{.*}} {
override class func runce() {
// CHECK: store [[CLASS]]* @"OBJC_METACLASS_$__TtC10objc_super6Hoozit", [[CLASS]]** {{.*}}, align 8
// CHECK: load i8*, i8** @"\01L_selector(runce)"
// CHECK: call void bitcast (void ()* @objc_msgSendSuper2 to void ([[SUPER]]*, i8*)*)([[SUPER]]* {{.*}}, i8* {{.*}})
super.runce()
}
// CHECK: }
// CHECK: define hidden swiftcc { double, double, double, double } @_T010objc_super6HoozitC5frameSC6NSRectVyF(%T10objc_super6HoozitC* swiftself) {{.*}} {
override func frame() -> NSRect {
// CHECK: [[T0:%.*]] = call [[TYPE]]* @_T010objc_super6HoozitCMa()
// CHECK: [[T1:%.*]] = bitcast [[TYPE]]* [[T0]] to [[CLASS]]*
// CHECK: store [[CLASS]]* [[T1]], [[CLASS]]** {{.*}}, align 8
// CHECK: load i8*, i8** @"\01L_selector(frame)"
// CHECK: call void bitcast (void ()* @objc_msgSendSuper2_stret to void ([[NSRECT]]*, [[SUPER]]*, i8*)*)([[NSRECT]]* noalias nocapture sret {{.*}}, [[SUPER]]* {{.*}}, i8* {{.*}})
return NSInsetRect(super.frame(), 2.0, 2.0)
}
// CHECK: }
// CHECK: define hidden swiftcc [[HOOZIT]]* @_T010objc_super6HoozitCACSi1x_tcfc(i64, %T10objc_super6HoozitC* swiftself) {{.*}} {
init(x:Int) {
// CHECK: load i8*, i8** @"\01L_selector(init)"
// CHECK: call [[OPAQUE:.*]]* bitcast (void ()* @objc_msgSendSuper2 to [[OPAQUE:.*]]* (%objc_super*, i8*)*)([[SUPER]]* {{.*}}, i8* {{.*}})
// CHECK-NOT: @swift_dynamicCastClassUnconditional
// CHECK: ret
super.init()
}
// CHECK: }
// CHECK: define hidden swiftcc [[HOOZIT]]* @_T010objc_super6HoozitCACSi1y_tcfc(i64, %T10objc_super6HoozitC* swiftself) {{.*}} {
init(y:Int) {
// CHECK: load i8*, i8** @"\01L_selector(initWithBellsOn:)"
// CHECK: call [[OPAQUE:.*]]* bitcast (void ()* @objc_msgSendSuper2 to [[OPAQUE:.*]]* (%objc_super*, i8*, i64)*)([[SUPER]]* {{.*}}, i8* {{.*}}, i64 {{.*}})
// CHECK-NOT: swift_dynamicCastClassUnconditional
// CHECK: ret
super.init(bellsOn:y)
}
// CHECK: }
}
func acceptFn(_ fn: () -> Void) { }
class PartialApply : Gizmo {
// CHECK: define hidden swiftcc void @_T010objc_super12PartialApplyC4frobyyF([[PARTIAL_APPLY_CLASS]]* swiftself) {{.*}} {
override func frob() {
// CHECK: call swiftcc void @_T010objc_super8acceptFnyyycF(i8* bitcast (void (%swift.refcounted*)* [[PARTIAL_FORWARDING_THUNK:@[A-Za-z0-9_]+]] to i8*), %swift.refcounted* %3)
acceptFn(super.frob)
}
// CHECK: }
}
class GenericRuncer<T> : Gizmo {
var x: Gizmo? = nil
var y: T?
// Use a constant indirect field access instead of a non-constant direct
// access because the layout dependents on the alignment of y.
// CHECK: define hidden swiftcc i64 @_T010objc_super13GenericRuncerC1xSo5GizmoCSgfg(%T10objc_super13GenericRuncerC* swiftself)
// CHECK: inttoptr
// CHECK: [[CAST:%.*]] = bitcast %T10objc_super13GenericRuncerC* %0 to i64*
// CHECK: [[ISA:%.*]] = load i64, i64* [[CAST]]
// CHECK: [[ISAMASK:%.*]] = load i64, i64* @swift_isaMask
// CHECK: [[CLASS:%.*]] = and i64 [[ISA]], [[ISAMASK]]
// CHECK: [[TY:%.*]] = inttoptr i64 [[CLASS]] to %swift.type*
// CHECK: [[CAST:%.*]] = bitcast %swift.type* [[TY]] to i64*
// CHECK: [[OFFSETADDR:%.*]] = getelementptr inbounds i64, i64* [[CAST]], i64 19
// CHECK: [[FIELDOFFSET:%.*]] = load i64, i64* [[OFFSETADDR]]
// CHECK: [[BYTEADDR:%.*]] = bitcast %T10objc_super13GenericRuncerC* %0 to i8*
// CHECK: [[FIELDADDR:%.*]] = getelementptr inbounds i8, i8* [[BYTEADDR]], i64 [[FIELDOFFSET]]
// CHECK: [[XADDR:%.*]] = bitcast i8* [[FIELDADDR]] to %TSo5GizmoCSg*
// CHECK: [[OPTIONALADDR:%.*]] = bitcast %TSo5GizmoCSg* [[XADDR]] to i64*
// CHECK: [[OPTIONAL:%.*]] = load i64, i64* [[OPTIONALADDR]]
// CHECK: [[OBJ:%.*]] = inttoptr i64 [[OPTIONAL]] to %objc_object*
// CHECK: call %objc_object* @objc_retain(%objc_object* [[OBJ]]
// CHECK: ret i64 [[OPTIONAL]]
// CHECK: define hidden swiftcc void @_T010objc_super13GenericRuncerC5runceyyFZ(%swift.type* swiftself) {{.*}} {
override class func runce() {
// CHECK: [[CLASS:%.*]] = call %swift.type* @_T010objc_super13GenericRuncerCMa(%swift.type* %T)
// CHECK-NEXT: [[CLASS1:%.*]] = bitcast %swift.type* [[CLASS]] to %objc_class*
// CHECK-NEXT: [[CLASS2:%.*]] = bitcast %objc_class* [[CLASS1]] to i64*
// CHECK-NEXT: [[ISA:%.*]] = load i64, i64* [[CLASS2]], align 8
// CHECK-NEXT: [[ISA_MASK:%.*]] = load i64, i64* @swift_isaMask, align 8
// CHECK-NEXT: [[ISA_MASKED:%.*]] = and i64 [[ISA]], [[ISA_MASK]]
// CHECK-NEXT: [[ISA_PTR:%.*]] = inttoptr i64 [[ISA_MASKED]] to %swift.type*
// CHECK-NEXT: [[METACLASS:%.*]] = bitcast %swift.type* [[ISA_PTR]] to %objc_class*
// CHECK: [[METACLASS_ADDR:%.*]] = getelementptr %objc_super, %objc_super* %objc_super, i32 0, i32 1
// CHECK-NEXT: store %objc_class* [[METACLASS]], %objc_class** [[METACLASS_ADDR]], align 8
// CHECK-NEXT: [[SELECTOR:%.*]] = load i8*, i8** @"\01L_selector(runce)", align 8
// CHECK-NEXT: call void bitcast (void ()* @objc_msgSendSuper2 to void (%objc_super*, i8*)*)(%objc_super* %objc_super, i8* [[SELECTOR]])
// CHECK-NEXT: ret void
super.runce()
}
}
// CHECK: define internal swiftcc void [[PARTIAL_FORWARDING_THUNK]](%swift.refcounted* swiftself) #0 {
// CHECK: call %swift.type* @_T010objc_super12PartialApplyCMa()
// CHECK: @"\01L_selector(frob)"
// CHECK: call void bitcast (void ()* @objc_msgSendSuper2
// CHECK: }
| apache-2.0 | d6275a929a2ebcdb052c3db90551c3c3 | 49.431818 | 182 | 0.602373 | 3.261636 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKit/model/CoreData/Shape+CoreDataClass.swift | 1 | 5080 | //
// Shape+CoreDataClass.swift
// TripKit
//
// Created by Adrian Schoenig on 4/7/17.
// Copyright © 2017 SkedGo. All rights reserved.
//
#if canImport(CoreData)
import Foundation
import CoreData
import CoreLocation
import MapKit
@objc(Shape)
public class Shape: NSManagedObject {
/// A turn-by-turn instruction, from one shape to the next
public enum Instruction: Int16 {
case headTowards = 1
case continueStraight = 2
case turnSlightyLeft = 3
case turnSlightlyRight = 4
case turnLeft = 5
case turnRight = 6
case turnSharplyLeft = 7
case turnSharplyRight = 8
}
private enum Flag: Int32 {
case isSafe = 1
case isNotSafe = 2
case dismount = 4
case isHop = 8
}
fileprivate var _sortedCoordinates: [TKNamedCoordinate]?
public var sortedCoordinates: [TKNamedCoordinate]? {
get {
if let encoded = encodedWaypoints, _sortedCoordinates == nil {
let coordinates = CLLocationCoordinate2D.decodePolyline(encoded)
_sortedCoordinates = coordinates.map(TKNamedCoordinate.init)
}
return _sortedCoordinates
}
}
@objc public weak var segment: TKSegment? = nil
public override func didTurnIntoFault() {
super.didTurnIntoFault()
_sortedCoordinates = nil
segment = nil
}
@objc public var start: MKAnnotation? {
return sortedCoordinates?.first
}
@objc public var end: MKAnnotation? {
return sortedCoordinates?.last
}
/// The turn-by-turn instruction from the previous shape to this shape
public var instruction: Instruction? {
get {
return Instruction(rawValue: rawInstruction)
}
set {
rawInstruction = newValue?.rawValue ?? 0
}
}
/// Indicates if you need to dismount your vehicle (e.g., your bicycle) to traverse this shape
@objc
public var isDismount: Bool {
get {
return has(.dismount)
}
set {
set(.dismount, to: newValue)
}
}
/// A hop is a shape element where the actual path is unknown and the indicated waypoints
/// can not be relied on.
@objc
public var isHop: Bool {
get {
return has(.isHop)
}
set {
set(.isHop, to: newValue)
}
}
public var isSafe: Bool? {
if has(.isSafe) {
return true
} else if has(.isNotSafe) {
return false
} else {
return nil
}
}
func setSafety(_ bool: Bool?) {
switch bool {
case true?:
set(.isSafe, to: true)
set(.isNotSafe, to: false)
case false?:
set(.isSafe, to: false)
set(.isNotSafe, to: true)
case nil:
set(.isSafe, to: false)
set(.isNotSafe, to: false)
}
}
private func has(_ flag: Flag) -> Bool {
return (flags & flag.rawValue) != 0
}
private func set(_ flag: Flag, to value: Bool) {
if value {
flags = flags | flag.rawValue
} else {
flags = flags & ~flag.rawValue
}
}
}
extension Shape {
public var friendliness: TKPathFriendliness {
if isDismount {
return .dismount
} else if let friendly = isSafe {
return friendly ? .friendly : .unfriendly
} else {
return .unknown
}
}
}
extension Shape {
static func fetchTravelledShape(for template: SegmentTemplate, atStart: Bool) -> Shape? {
let predicate = NSPredicate(format: "template = %@ AND travelled = 1", template)
let sorter = NSSortDescriptor(key: "index", ascending: atStart)
let shapes = template.managedObjectContext?.fetchObjects(Shape.self, sortDescriptors: [sorter], predicate: predicate, relationshipKeyPathsForPrefetching: nil, fetchLimit: 1)
return shapes?.first
}
}
// MARK: - TKDisplayableRoute
extension Shape: TKDisplayableRoute {
public var routePath: [Any] {
return sortedCoordinates ?? []
}
public var routeColor: TKColor? {
if !travelled {
// Non-travelled always gets a special colour
return .routeDashColorNonTravelled
}
if let color = services?.first?.color {
return color
}
#if os(iOS) || os(tvOS)
if let bestTag = roadTags?.first {
return bestTag.safety.color
}
#endif
switch friendliness {
case .friendly, .unfriendly, .dismount:
return friendliness.color
case .unknown:
return segment?.color ?? friendliness.color
}
}
public var routeIsTravelled: Bool {
return travelled
}
public var routeDashPattern: [NSNumber]? {
if isHop {
return [1, 15] // dots
} else {
return nil
}
}
public var selectionIdentifier: String? {
if let segment = segment?.originalSegmentIncludingContinuation() {
// Should match the definition in TripKitUI => TKUIAnnotations+TripKit
switch segment.order {
case .start: return "start"
case .regular: return String(segment.templateHashCode)
case .end: return "end"
}
} else if let service = services?.first {
return service.code
} else {
return nil
}
}
}
#endif
| apache-2.0 | 6f97083a5b3ad12692478c632fdf61db | 21.674107 | 177 | 0.627092 | 4.089372 | false | false | false | false |
Johennes/firefox-ios | Extensions/ShareTo/ShareViewController.swift | 1 | 11272 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import Storage
struct ShareDestination {
let code: String
let name: String
let image: String
}
// TODO: See if we can do this with an Enum instead. Previous attempts failed because for example NSSet does not take (string) enum values.
let ShareDestinationBookmarks: String = "Bookmarks"
let ShareDestinationReadingList: String = "ReadingList"
let ShareDestinations = [
ShareDestination(code: ShareDestinationReadingList, name: NSLocalizedString("Add to Reading List", tableName: "ShareTo", comment: "On/off toggle to select adding this url to your reading list"), image: "AddToReadingList"),
ShareDestination(code: ShareDestinationBookmarks, name: NSLocalizedString("Add to Bookmarks", tableName: "ShareTo", comment: "On/off toggle to select adding this url to your bookmarks"), image: "AddToBookmarks")
]
protocol ShareControllerDelegate {
func shareControllerDidCancel(shareController: ShareDialogController) -> Void
func shareController(shareController: ShareDialogController, didShareItem item: ShareItem, toDestinations destinations: NSSet) -> Void
}
private struct ShareDialogControllerUX {
static let CornerRadius: CGFloat = 4 // Corner radius of the dialog
static let NavigationBarTintColor = UIColor(rgb: 0xf37c00) // Tint color changes the text color in the navigation bar
static let NavigationBarCancelButtonFont = UIFont.systemFontOfSize(UIFont.buttonFontSize()) // System default
static let NavigationBarAddButtonFont = UIFont.boldSystemFontOfSize(UIFont.buttonFontSize()) // System default
static let NavigationBarIconSize = 38 // Width and height of the icon
static let NavigationBarBottomPadding = 12
static let ItemTitleFontMedium = UIFont.systemFontOfSize(15, weight: UIFontWeightMedium)
static let ItemTitleFont = UIFont.systemFontOfSize(15)
static let ItemTitleMaxNumberOfLines = 2
static let ItemTitleLeftPadding = 44
static let ItemTitleRightPadding = 44
static let ItemTitleBottomPadding = 12
static let ItemLinkFont = UIFont.systemFontOfSize(12)
static let ItemLinkMaxNumberOfLines = 3
static let ItemLinkLeftPadding = 44
static let ItemLinkRightPadding = 44
static let ItemLinkBottomPadding = 14
static let DividerColor = UIColor.lightGrayColor() // Divider between the item and the table with destinations
static let DividerHeight = 0.5
static let TableRowHeight: CGFloat = 44 // System default
static let TableRowFont = UIFont.systemFontOfSize(14)
static let TableRowFontMinScale: CGFloat = 0.8
static let TableRowTintColor = UIColor(red:0.427, green:0.800, blue:0.102, alpha:1.0) // Green tint for the checkmark
static let TableRowTextColor = UIColor(rgb: 0x555555)
static let TableHeight = 88 // Height of 2 standard 44px cells
}
class ShareDialogController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var delegate: ShareControllerDelegate!
var item: ShareItem!
var initialShareDestinations: NSSet = NSSet(object: ShareDestinationBookmarks)
var selectedShareDestinations: NSMutableSet = NSMutableSet()
var navBar: UINavigationBar!
var navItem: UINavigationItem!
override func viewDidLoad() {
super.viewDidLoad()
selectedShareDestinations = NSMutableSet(set: initialShareDestinations)
self.view.backgroundColor = UIColor.whiteColor()
self.view.layer.cornerRadius = ShareDialogControllerUX.CornerRadius
self.view.clipsToBounds = true
// Setup the NavigationBar
navBar = UINavigationBar()
navBar.translatesAutoresizingMaskIntoConstraints = false
navBar.tintColor = ShareDialogControllerUX.NavigationBarTintColor
navBar.translucent = false
self.view.addSubview(navBar)
// Setup the NavigationItem
navItem = UINavigationItem()
navItem.leftBarButtonItem = UIBarButtonItem(
title: Strings.ShareToCancelButton,
style: .Plain,
target: self,
action: #selector(ShareDialogController.cancel)
)
navItem.leftBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: ShareDialogControllerUX.NavigationBarCancelButtonFont], forState: UIControlState.Normal)
navItem.leftBarButtonItem?.accessibilityIdentifier = "ShareDialogController.navigationItem.leftBarButtonItem"
navItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Add", tableName: "ShareTo", comment: "Add button in the share dialog"), style: UIBarButtonItemStyle.Done, target: self, action: #selector(ShareDialogController.add))
navItem.rightBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: ShareDialogControllerUX.NavigationBarAddButtonFont], forState: UIControlState.Normal)
let logo = UIImageView(frame: CGRect(x: 0, y: 0, width: ShareDialogControllerUX.NavigationBarIconSize, height: ShareDialogControllerUX.NavigationBarIconSize))
logo.image = UIImage(named: "Icon-Small")
logo.contentMode = UIViewContentMode.ScaleAspectFit // TODO Can go away if icon is provided in correct size
navItem.titleView = logo
navBar.pushNavigationItem(navItem, animated: false)
// Setup the title view
let titleView = UILabel()
titleView.translatesAutoresizingMaskIntoConstraints = false
titleView.numberOfLines = ShareDialogControllerUX.ItemTitleMaxNumberOfLines
titleView.lineBreakMode = NSLineBreakMode.ByTruncatingTail
titleView.text = item.title
titleView.font = ShareDialogControllerUX.ItemTitleFontMedium
view.addSubview(titleView)
// Setup the link view
let linkView = UILabel()
linkView.translatesAutoresizingMaskIntoConstraints = false
linkView.numberOfLines = ShareDialogControllerUX.ItemLinkMaxNumberOfLines
linkView.lineBreakMode = NSLineBreakMode.ByTruncatingTail
linkView.text = item.url
linkView.font = ShareDialogControllerUX.ItemLinkFont
view.addSubview(linkView)
// Setup the icon
let iconView = UIImageView()
iconView.translatesAutoresizingMaskIntoConstraints = false
iconView.image = UIImage(named: "defaultFavicon")
view.addSubview(iconView)
// Setup the divider
let dividerView = UIView()
dividerView.translatesAutoresizingMaskIntoConstraints = false
dividerView.backgroundColor = ShareDialogControllerUX.DividerColor
view.addSubview(dividerView)
// Setup the table with destinations
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.separatorInset = UIEdgeInsetsZero
tableView.layoutMargins = UIEdgeInsetsZero
tableView.userInteractionEnabled = true
tableView.delegate = self
tableView.allowsSelection = true
tableView.dataSource = self
tableView.scrollEnabled = false
view.addSubview(tableView)
// Setup constraints
let views = [
"nav": navBar,
"title": titleView,
"link": linkView,
"icon": iconView,
"divider": dividerView,
"table": tableView
]
// TODO See Bug 1102516 - Use Snappy to define share extension layout constraints
let constraints = [
"H:|[nav]|",
"V:|[nav]",
"H:|-\(ShareDialogControllerUX.ItemTitleLeftPadding)-[title]-\(ShareDialogControllerUX.ItemTitleRightPadding)-|",
"V:[nav]-\(ShareDialogControllerUX.NavigationBarBottomPadding)-[title]",
"H:|-\(ShareDialogControllerUX.ItemLinkLeftPadding)-[link]-\(ShareDialogControllerUX.ItemLinkLeftPadding)-|",
"V:[title]-\(ShareDialogControllerUX.ItemTitleBottomPadding)-[link]",
"H:|[divider]|",
"V:[divider(\(ShareDialogControllerUX.DividerHeight))]",
"V:[link]-\(ShareDialogControllerUX.ItemLinkBottomPadding)-[divider]",
"H:|[table]|",
"V:[divider][table]",
"V:[table(\(ShareDialogControllerUX.TableHeight))]|"
]
for constraint in constraints {
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(constraint, options: NSLayoutFormatOptions(), metrics: nil, views: views))
}
}
// UITabBarItem Actions that map to our delegate methods
func cancel() {
delegate?.shareControllerDidCancel(self)
}
func add() {
delegate?.shareController(self, didShareItem: item, toDestinations: NSSet(set: selectedShareDestinations))
}
// UITableView Delegate and DataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ShareDestinations.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return ShareDialogControllerUX.TableRowHeight
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.textColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.darkGrayColor() : ShareDialogControllerUX.TableRowTextColor
cell.textLabel?.font = ShareDialogControllerUX.TableRowFont
cell.accessoryType = selectedShareDestinations.containsObject(ShareDestinations[indexPath.row].code) ? UITableViewCellAccessoryType.Checkmark : UITableViewCellAccessoryType.None
cell.tintColor = ShareDialogControllerUX.TableRowTintColor
cell.layoutMargins = UIEdgeInsetsZero
cell.textLabel?.text = ShareDestinations[indexPath.row].name
cell.textLabel?.adjustsFontSizeToFitWidth = true
cell.textLabel?.minimumScaleFactor = ShareDialogControllerUX.TableRowFontMinScale
cell.imageView?.image = UIImage(named: ShareDestinations[indexPath.row].image)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
let code = ShareDestinations[indexPath.row].code
if selectedShareDestinations.containsObject(code) {
selectedShareDestinations.removeObject(code)
} else {
selectedShareDestinations.addObject(code)
}
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
navItem.rightBarButtonItem?.enabled = (selectedShareDestinations.count != 0)
}
}
| mpl-2.0 | 8481a876f5e78660192381dbeaaea7a1 | 44.821138 | 244 | 0.702981 | 6.043968 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.