repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
apple/swift-experimental-string-processing | Sources/_StringProcessing/Algorithms/Consumers/PredicateConsumer.swift | 1 | 2212 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 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
//
//===----------------------------------------------------------------------===//
struct PredicateConsumer<Consumed: Collection> {
let predicate: (Consumed.Element) -> Bool
}
extension PredicateConsumer: CollectionConsumer {
public func consuming(
_ consumed: Consumed,
in range: Range<Consumed.Index>
) -> Consumed.Index? {
let start = range.lowerBound
guard start != range.upperBound && predicate(consumed[start]) else {
return nil
}
return consumed.index(after: start)
}
}
extension PredicateConsumer: BidirectionalCollectionConsumer
where Consumed: BidirectionalCollection
{
func consumingBack(
_ consumed: Consumed,
in range: Range<Consumed.Index>
) -> Consumed.Index? {
let end = range.upperBound
guard end != range.lowerBound else { return nil }
let previous = consumed.index(before: end)
return predicate(consumed[previous]) ? previous : nil
}
}
extension PredicateConsumer: StatelessCollectionSearcher {
public typealias Searched = Consumed
public func search(
_ searched: Searched,
in range: Range<Searched.Index>
) -> Range<Searched.Index>? {
// TODO: Make this reusable
guard let index = searched[range].firstIndex(where: predicate) else {
return nil
}
return index..<searched.index(after: index)
}
}
extension PredicateConsumer: BackwardCollectionSearcher,
BackwardStatelessCollectionSearcher
where Searched: BidirectionalCollection
{
typealias BackwardSearched = Consumed
func searchBack(
_ searched: BackwardSearched,
in range: Range<BackwardSearched.Index>
) -> Range<BackwardSearched.Index>? {
// TODO: Make this reusable
guard let index = searched[range].lastIndex(where: predicate) else {
return nil
}
return index..<searched.index(after: index)
}
}
| apache-2.0 | a663f97c6d4f915cb1eee9500df5427a | 28.891892 | 80 | 0.653707 | 4.686441 | false | false | false | false |
byu-oit/ios-byuSuite | byuSuite/Apps/Calendars/controller/CalendarsEventDetailViewController.swift | 2 | 4491 | //
// CalendarsEventDetailViewController.swift
// byuSuite
//
// Created by Erik Brady on 5/2/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
import UIKit
import EventKit
import EventKitUI
class CalendarsEventDetailViewController: ByuTableDataViewController, EKEventEditViewDelegate {
//MARK: Properties
var event: CalendarEvent?
override func viewDidLoad() {
super.viewDidLoad()
tableView.variableHeightForRows()
self.loadTableData()
}
//MARK: IBActions
@IBAction func actionButtonTapped(_ sender: Any) {
self.displayActionSheet(from: sender, actions: [UIAlertAction(title: "Add Event to My Calendar", style: UIAlertActionStyle.default) { (action) in
let store = EKEventStore()
store.requestAccess(to: EKEntityType.event, completion: { (granted, error) in
if granted, let event = self.event?.generateEkEvent(store: store) {
//When user allows the feature to access their calendar.
event.calendar = store.defaultCalendarForNewEvents
let controller = EKEventEditViewController()
controller.event = event
controller.eventStore = store
controller.editViewDelegate = self
self.present(controller, animated: true)
} else {
super.displayAlert(title: "Access Denied", message: "The app was denied access to your calendar. Please edit this preference in your settings.")
}
})
}])
}
//MARK: EkEventEditViewDelegate Methods
func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) {
controller.dismiss(animated: true)
if action == .saved {
super.displayAlert(title: "Success", message: "The event was added to your calendar.", alertHandler: nil)
}
}
//MARK: Custom Methods
private func loadTableData() {
if let event = event, let title = event.title {
let tempTableData = TableData()
tempTableData.add(section: Section(title: "Event Title", rows: [Row(text: title, cellId: "titleCell", enabled: false)]))
var eventInfoRows = [Row]()
if let location = event.location {
eventInfoRows.append(Row(text: "Location: ", detailText: location, action: {
super.displayAlert(title: "Location", message: location, alertHandler: { (action) in
self.tableView.deselectSelectedRow()
})
}))
}
if let start = event.startTimeString {
eventInfoRows.append(Row(text: "Start: ", detailText: start, enabled: false))
}
if let end = event.endTimeString {
eventInfoRows.append(Row(text: "End: ", detailText: end, enabled: false))
}
if event.ticketsExist {
if !event.isFree, let lowPrice = event.lowPrice {
//Price or Range
if let highPrice = event.highPrice {
//Price Range
eventInfoRows.append(Row(text: "Price: ", detailText: String(format: "$%.02f - $%.02f", lowPrice, highPrice), enabled: false))
} else if lowPrice != 0 {
//Fixed Price
eventInfoRows.append(Row(text: "Price: ", detailText: String(format: "$%.02f", lowPrice), enabled: false))
}
}
if let ticketsUrl = event.ticketsUrl {
//If tickets exist, check if there is a ticketUrl regardless of price
eventInfoRows.append(Row(text: "Get Tickets Here", cellId: "ticketsCell", action: {
self.presentSafariViewController(urlString: ticketsUrl)
}))
}
}
tempTableData.add(section: Section(title: "Event Information", cellId: "infoCell", rows: eventInfoRows))
if let desc = event.eventDescription, desc != "" {
tempTableData.add(section: Section(title: "Event Details", cellId: "detailCell", rows: [Row(text: desc, enabled: false)]))
}
tableData = tempTableData
}
}
}
| apache-2.0 | 6d0daa0b4167e4ba2a551744099d4c20 | 41.358491 | 164 | 0.570824 | 5.079186 | false | false | false | false |
chatspry/rubygens | Pods/Nimble/Nimble/ObjCExpectation.swift | 23 | 2404 | internal struct ObjCMatcherWrapper : Matcher {
let matcher: NMBMatcher
func matches(actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool {
return matcher.matches(
({ actualExpression.evaluate() }),
failureMessage: failureMessage,
location: actualExpression.location)
}
func doesNotMatch(actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool {
return matcher.doesNotMatch(
({ actualExpression.evaluate() }),
failureMessage: failureMessage,
location: actualExpression.location)
}
}
// Equivalent to Expectation, but for Nimble's Objective-C interface
public class NMBExpectation : NSObject {
internal let _actualBlock: () -> NSObject!
internal var _negative: Bool
internal let _file: String
internal let _line: UInt
internal var _timeout: NSTimeInterval = 1.0
public init(actualBlock: () -> NSObject!, negative: Bool, file: String, line: UInt) {
self._actualBlock = actualBlock
self._negative = negative
self._file = file
self._line = line
}
private var expectValue: Expectation<NSObject> {
return expect(_file, line: _line){
self._actualBlock() as NSObject?
}
}
public var withTimeout: (NSTimeInterval) -> NMBExpectation {
return ({ timeout in self._timeout = timeout
return self
})
}
public var to: (NMBMatcher) -> Void {
return ({ matcher in
self.expectValue.to(ObjCMatcherWrapper(matcher: matcher))
})
}
public var toNot: (NMBMatcher) -> Void {
return ({ matcher in
self.expectValue.toNot(
ObjCMatcherWrapper(matcher: matcher)
)
})
}
public var notTo: (NMBMatcher) -> Void { return toNot }
public var toEventually: (NMBMatcher) -> Void {
return ({ matcher in
self.expectValue.toEventually(
ObjCMatcherWrapper(matcher: matcher),
timeout: self._timeout
)
})
}
public var toEventuallyNot: (NMBMatcher) -> Void {
return ({ matcher in
self.expectValue.toEventuallyNot(
ObjCMatcherWrapper(matcher: matcher),
timeout: self._timeout
)
})
}
}
| mit | ecd5bd7929b9be12caeffe74a5c85ed7 | 29.43038 | 103 | 0.59817 | 5.342222 | false | false | false | false |
apple/swift-lldb | packages/Python/lldbsuite/test/lang/swift/swift_reference_counting/main.swift | 1 | 1060 | // main.swift
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//
// -----------------------------------------------------------------------------
class Patatino {
var meh : Int
init(_ meh : Int) {
self.meh = meh
}
}
struct Tinky {}
func lambda(_ Arg : Patatino) -> Int {
return Arg.meh
}
func main() -> Int {
var LiveObj = Patatino(37) //%self.expect('language swift refcount Blah', substrs=['unresolved identifier \'Blah\''], error=True)
var Ret : Int = lambda(LiveObj) //%self.expect('language swift refcount LiveObj', substrs=['(strong = 3, unowned = 1, weak = 1)'])
var MyStruct = Tinky() //%self.expect('language swift refcount MyStruct', substrs=['refcount only available for class types'], error=True)
return Ret
}
main()
| apache-2.0 | a50499bd84c014be3caf3129d2e5d14f | 31.121212 | 140 | 0.636792 | 3.897059 | false | false | false | false |
ACChe/eidolon | Kiosk/Bid Fulfillment/ManualCreditCardInputViewController.swift | 1 | 6487 | import UIKit
import ReactiveCocoa
import Keys
class ManualCreditCardInputViewController: UIViewController, RegistrationSubController {
let finishedSignal = RACSubject()
@IBOutlet weak var cardNumberTextField: TextField!
@IBOutlet weak var expirationMonthTextField: TextField!
@IBOutlet weak var expirationYearTextField: TextField!
@IBOutlet weak var securitycodeTextField: TextField!
@IBOutlet weak var billingZipTextField: TextField!
@IBOutlet weak var cardNumberWrapperView: UIView!
@IBOutlet weak var expirationDateWrapperView: UIView!
@IBOutlet weak var securityCodeWrapperView: UIView!
@IBOutlet weak var billingZipWrapperView: UIView!
@IBOutlet weak var billingZipErrorLabel: UILabel!
@IBOutlet weak var cardConfirmButton: ActionButton!
@IBOutlet weak var dateConfirmButton: ActionButton!
@IBOutlet weak var securityCodeConfirmButton: ActionButton!
@IBOutlet weak var billingZipConfirmButton: ActionButton!
lazy var keys = EidolonKeys()
lazy var viewModel: ManualCreditCardInputViewModel = {
var bidDetails = self.navigationController?.fulfillmentNav().bidDetails
return ManualCreditCardInputViewModel(bidDetails: bidDetails, finishedSubject: self.finishedSignal)
}()
override func viewDidLoad() {
super.viewDidLoad()
expirationDateWrapperView.hidden = true
securityCodeWrapperView.hidden = true
billingZipWrapperView.hidden = true
// We show the enter credit card number, then the date switching the views around
RAC(viewModel, "cardFullDigits") <~ cardNumberTextField.rac_textSignal()
RAC(viewModel, "expirationYear") <~ expirationYearTextField.rac_textSignal()
RAC(viewModel, "expirationMonth") <~ expirationMonthTextField.rac_textSignal()
RAC(viewModel, "securityCode") <~ securitycodeTextField.rac_textSignal()
RAC(viewModel, "billingZip") <~ billingZipTextField.rac_textSignal()
RAC(cardConfirmButton, "enabled") <~ viewModel.creditCardNumberIsValidSignal
billingZipConfirmButton.rac_command = viewModel.registerButtonCommand()
RAC(billingZipErrorLabel, "hidden") <~ billingZipConfirmButton.rac_command.errors.take(1).mapReplace(false).startWith(true)
viewModel.moveToYearSignal.take(1).subscribeNext { [weak self] _ -> Void in
self?.expirationYearTextField.becomeFirstResponder()
return
}
cardNumberTextField.becomeFirstResponder()
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
return viewModel.isEntryValid(string)
}
@IBAction func cardNumberconfirmTapped(sender: AnyObject) {
cardNumberWrapperView.hidden = true
expirationDateWrapperView.hidden = false
securityCodeWrapperView.hidden = true
billingZipWrapperView.hidden = true
expirationDateWrapperView.frame = CGRectMake(0, 0, CGRectGetWidth(expirationDateWrapperView.frame), CGRectGetHeight(expirationDateWrapperView.frame))
expirationMonthTextField.becomeFirstResponder()
}
@IBAction func expirationDateConfirmTapped(sender: AnyObject) {
cardNumberWrapperView.hidden = true
expirationDateWrapperView.hidden = true
securityCodeWrapperView.hidden = false
billingZipWrapperView.hidden = true
securityCodeWrapperView.frame = CGRectMake(0, 0, CGRectGetWidth(securityCodeWrapperView.frame), CGRectGetHeight(securityCodeWrapperView.frame))
securitycodeTextField.becomeFirstResponder()
}
@IBAction func securityCodeConfirmTapped(sender: AnyObject) {
cardNumberWrapperView.hidden = true
expirationDateWrapperView.hidden = true
securityCodeWrapperView.hidden = true
billingZipWrapperView.hidden = false
billingZipWrapperView.frame = CGRectMake(0, 0, CGRectGetWidth(billingZipWrapperView.frame), CGRectGetHeight(billingZipWrapperView.frame))
billingZipTextField.becomeFirstResponder()
}
@IBAction func backToCardNumber(sender: AnyObject) {
cardNumberWrapperView.hidden = false
expirationDateWrapperView.hidden = true
securityCodeWrapperView.hidden = true
billingZipWrapperView.hidden = true
cardNumberTextField.becomeFirstResponder()
}
@IBAction func backToExpirationDate(sender: AnyObject) {
cardNumberWrapperView.hidden = true
expirationDateWrapperView.hidden = false
securityCodeWrapperView.hidden = true
billingZipWrapperView.hidden = true
expirationMonthTextField.becomeFirstResponder()
}
@IBAction func backToSecurityCode(sender: AnyObject) {
cardNumberWrapperView.hidden = true
expirationDateWrapperView.hidden = true
securityCodeWrapperView.hidden = false
billingZipWrapperView.hidden = true
securitycodeTextField.becomeFirstResponder()
}
class func instantiateFromStoryboard(storyboard: UIStoryboard) -> ManualCreditCardInputViewController {
return storyboard.viewControllerWithID(.ManualCardDetailsInput) as! ManualCreditCardInputViewController
}
}
private extension ManualCreditCardInputViewController {
func applyCardWithSuccess(success: Bool) {
cardNumberTextField.text = success ? "4242424242424242" : "4000000000000002"
cardNumberTextField.sendActionsForControlEvents(.AllEditingEvents)
cardConfirmButton.sendActionsForControlEvents(.TouchUpInside)
expirationMonthTextField.text = "04"
expirationMonthTextField.sendActionsForControlEvents(.AllEditingEvents)
expirationYearTextField.text = "2018"
expirationYearTextField.sendActionsForControlEvents(.AllEditingEvents)
dateConfirmButton.sendActionsForControlEvents(.TouchUpInside)
securitycodeTextField.text = "123"
securitycodeTextField.sendActionsForControlEvents(.AllEditingEvents)
securityCodeConfirmButton.sendActionsForControlEvents(.TouchUpInside)
billingZipTextField.text = "10001"
billingZipTextField.sendActionsForControlEvents(.AllEditingEvents)
billingZipTextField.sendActionsForControlEvents(.TouchUpInside)
}
@IBAction func dev_creditCardOKTapped(sender: AnyObject) {
applyCardWithSuccess(true)
}
@IBAction func dev_creditCardFailTapped(sender: AnyObject) {
applyCardWithSuccess(false)
}
} | mit | 1baa71d692ef6b2e08c7435244572fcc | 40.858065 | 157 | 0.750886 | 5.750887 | false | false | false | false |
PatrickChow/Swift-Awsome | News/Modules/Auth/SignUp/ViewController/SignUpViewController.swift | 1 | 6192 | //
// Created by Patrick Chow on 2017/6/19.
// Copyright (c) 2017 JIEMIAN. All rights reserved.
import UIKit
import RxSwift
import RxCocoa
import Action
class SignUpViewController: InputViewController {
let phone = LabeledTextField(labeledText: "手机号:")
let verificationCode = LabeledTextField(labeledText: "验证码:")
let password = LabeledTextField(labeledText: "密码:")
let repeatedPassword = LabeledTextField(labeledText: "重复密码:")
let nickname = LabeledTextField(labeledText: "昵称:")
let countdownView = CountdownView()
var viewModel: SignUpViewModel!
override func viewDidLoad() {
super.viewDidLoad()
title = "注册"
view.nv.backgroundColor(UIColor.white, night: UIColor.white)
let authView = SNSOAuthView()
scrollView.addSubview(authView)
authView.snp.makeConstraints {
$0.left.right.equalToSuperview()
$0.top.equalToSuperview().offset(20)
$0.height.equalTo(suitableSize(85, 145, 145))
}
scrollView.addSubview(phone)
phone.snp.makeConstraints {
$0.top.equalTo(authView.snp.bottom)
$0.left.equalToSuperview().offset(20)
$0.height.equalTo(40)
$0.width.equalTo(view.bounds.width - 140)
}
scrollView.addSubview(countdownView)
countdownView.snp.makeConstraints {
$0.bottom.equalTo(phone)
$0.left.equalTo(phone.snp.right).offset(20)
$0.right.equalToSuperview().offset(-20)
$0.height.equalTo(20)
$0.width.equalTo(80)
}
scrollView.addSubview(verificationCode)
verificationCode.snp.makeConstraints {
$0.top.equalTo(phone.snp.bottom)
$0.left.equalToSuperview().offset(20)
$0.right.equalToSuperview().offset(-20)
$0.height.equalTo(40)
$0.width.equalTo(view.bounds.width - 40)
}
scrollView.addSubview(password)
password.snp.makeConstraints {
$0.top.equalTo(verificationCode.snp.bottom)
$0.left.equalToSuperview().offset(20)
$0.right.equalToSuperview().offset(-20)
$0.height.equalTo(40)
$0.width.equalTo(view.bounds.width - 40)
}
scrollView.addSubview(repeatedPassword)
repeatedPassword.snp.makeConstraints {
$0.top.equalTo(password.snp.bottom)
$0.left.equalToSuperview().offset(20)
$0.right.equalToSuperview().offset(-20)
$0.height.equalTo(40)
$0.width.equalTo(view.bounds.width - 40)
}
scrollView.addSubview(nickname)
nickname.snp.makeConstraints {
$0.top.equalTo(repeatedPassword.snp.bottom)
$0.left.equalToSuperview().offset(20)
$0.right.equalToSuperview().offset(-20)
$0.height.equalTo(40)
$0.width.equalTo(view.bounds.width - 40)
}
//
viewModel = SignUpViewModel(input: (phone: phone.rx.text.orEmpty.asDriver(),
verificationCode: verificationCode.rx.text.orEmpty.asDriver(),
password: password.rx.text.orEmpty.asDriver(),
repeatedPassword: repeatedPassword.rx.text.orEmpty.asDriver(),
nickname: nickname.rx.text.orEmpty.asDriver(),
countingDown: countdownView.countingDown),
bind: (phone: phone.rx.isValid,
countdown: countdownView.rx.isEnabled,
verificationCode: verificationCode.rx.isValid,
password: password.rx.isValid,
repeatedPassword: repeatedPassword.rx.isValid,
nickname: nickname.rx.isValid),
dependency: (API: "",
validationService: ValidationService()),
disposeBag: disposeBag)
// foot view
let footerView = SignUpFooterView((signIn: handleSignInSegue(),
register: handleSigningUp(),
agreement: handleAgreementSegue()))
scrollView.addSubview(footerView)
footerView.snp.makeConstraints {
$0.left.right.equalToSuperview()
$0.top.equalTo(nickname.snp.bottom)
$0.height.equalTo(108)
}
password.returnKeyType = .next
repeatedPassword.returnKeyType = .next
nickname.returnKeyType = .join
phone.keyboardType = .numberPad
verificationCode.keyboardType = .numberPad
password.isSecureTextEntry = true
repeatedPassword.isSecureTextEntry = true
viewModel.isEnabled
.drive(footerView.isSignUpButtonEnabled)
.disposed(by: disposeBag)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// ensure invalidate countdown view's timer
// countdownView.invalidateTimer()
}
/// 处理点击登录
private func handleSignInSegue() -> CocoaAction {
return CocoaAction(workFactory: { [weak self] in
return Observable.create { observer in
observer.onCompleted()
self?.popViewController()
return Disposables.create()
}
})
}
// 注册
private func handleSigningUp() -> CocoaAction {
return CocoaAction(enabledIf: viewModel.isEnabled.asObservable(), workFactory: {
return Observable.create { observer in
observer.onCompleted()
return Disposables.create()
}
})
}
// 注册协议跳转
private func handleAgreementSegue() -> CocoaAction {
return CocoaAction(workFactory: {
return Observable.create { observer in
observer.onCompleted()
return Disposables.create()
}
})
}
}
| mit | 2ee1ffd0acad026cbbb7d64f31bcabee | 35.706587 | 90 | 0.573409 | 5.061932 | false | false | false | false |
lucascarletti/Pruuu | Pruuu/API/PRAPIRequestHandler.swift | 1 | 2159 | //
// PRAPIRequestHandler.swift
// Pruuu
//
// Created by Lucas Teixeira Carletti on 16/10/2017.
// Copyright © 2017 PR. All rights reserved.
//
import Foundation
import Alamofire
class PRApiRequestHandler: NSObject {
//MARK: - User Methods
static func submitNewCustomerForm(form : [String:AnyObject], callBack: @escaping postBecomeCustomerFormCallback){
// PRApiRequest.POST(endPoint: Endpoint.postForm, params: form).responseJSON{
// response in
//
// debugPrint(response)
// callBack((response.result.error != nil) ? false : true)
// }
}
//MARK: - Unit Methods
static func getUnits(headers: [String: String]? = nil, callBack: @escaping unitsCallback) {
PRApiRequest.GET(endPoint: Endpoint.getUnits, headers: headers).responseJSON {
response in
guard let dictionary = response.result.value as? [String: Any] else {
callBack(nil)
return
}
debugPrint(dictionary)
callBack(dictionary as [String : AnyObject])
}
}
//MARK: - Region Methods
static func getRegions(callBack: @escaping regionsCallback) {
PRApiRequest.GET(endPoint: Endpoint.getRegions).responseJSON {
response in
guard let dictionary = response.result.value as? [String: Any] else {
callBack(nil)
return
}
debugPrint(dictionary)
callBack(dictionary as [String : AnyObject])
}
}
//MARK: - Support Methods
static func getSupportInformation(callBack: @escaping getSupportInfoCallBack){
PRApiRequest.GET(endPoint: Endpoint.getSupportInfo).responseJSON {
response in
guard let dictionary = response.result.value as? [String: Any] else {
callBack(nil)
return
}
debugPrint(dictionary)
callBack(dictionary as [String : AnyObject])
}
}
}
| mit | 57c459ea7f01ae26f9077a91395fd549 | 27.394737 | 117 | 0.565338 | 4.82774 | false | false | false | false |
slavapestov/swift | test/SILGen/reabstract_lvalue.swift | 2 | 2600 | // RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s
struct MyMetatypeIsThin {}
// CHECK-LABEL: sil hidden @_TF17reabstract_lvalue19consumeGenericInOut{{.*}} : $@convention(thin) <T> (@inout T) -> ()
func consumeGenericInOut<T>(inout x: T) {}
// CHECK-LABEL: sil hidden @_TF17reabstract_lvalue9transformFSiSd : $@convention(thin) (Int) -> Double
func transform(i: Int) -> Double {
return Double(i)
}
// CHECK-LABEL: sil hidden @_TF17reabstract_lvalue23reabstractFunctionInOutFT_T_ : $@convention(thin) () -> ()
func reabstractFunctionInOut() {
// CHECK: [[BOX:%.*]] = alloc_box $@callee_owned (Int) -> Double
// CHECK: [[PB:%.*]] = project_box [[BOX]]
// CHECK: [[ARG:%.*]] = function_ref @_TF17reabstract_lvalue9transformFSiSd
// CHECK: [[THICK_ARG:%.*]] = thin_to_thick_function [[ARG]]
// CHECK: store [[THICK_ARG:%.*]] to [[PB]]
// CHECK: [[FUNC:%.*]] = function_ref @_TF17reabstract_lvalue19consumeGenericInOut
// CHECK: [[ABSTRACTED_BOX:%.*]] = alloc_stack $@callee_owned (@out Double, @in Int) -> ()
// CHECK: [[THICK_ARG:%.*]] = load [[PB]]
// CHECK: strong_retain [[THICK_ARG]]
// CHECK: [[THUNK1:%.*]] = function_ref @_TTRXFo_dSi_dSd_XFo_iSi_iSd_
// CHECK: [[ABSTRACTED_ARG:%.*]] = partial_apply [[THUNK1]]([[THICK_ARG]])
// CHECK: store [[ABSTRACTED_ARG]] to [[ABSTRACTED_BOX]]
// CHECK: apply [[FUNC]]<(Int) -> Double>([[ABSTRACTED_BOX]])
// CHECK: [[NEW_ABSTRACTED_ARG:%.*]] = load [[ABSTRACTED_BOX]]
// CHECK: [[THUNK2:%.*]] = function_ref @_TTRXFo_iSi_iSd_XFo_dSi_dSd_
// CHECK: [[NEW_ARG:%.*]] = partial_apply [[THUNK2]]([[NEW_ABSTRACTED_ARG]])
var minimallyAbstracted = transform
consumeGenericInOut(&minimallyAbstracted)
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dSi_dSd_XFo_iSi_iSd_ : $@convention(thin) (@out Double, @in Int, @owned @callee_owned (Int) -> Double) -> ()
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_iSi_iSd_XFo_dSi_dSd_ : $@convention(thin) (Int, @owned @callee_owned (@out Double, @in Int) -> ()) -> Double
// CHECK-LABEL: sil hidden @_TF17reabstract_lvalue23reabstractMetatypeInOutFT_T_ : $@convention(thin) () -> ()
func reabstractMetatypeInOut() {
var thinMetatype = MyMetatypeIsThin.self
// CHECK: [[FUNC:%.*]] = function_ref @_TF17reabstract_lvalue19consumeGenericInOut
// CHECK: [[BOX:%.*]] = alloc_stack $@thick MyMetatypeIsThin.Type
// CHECK: [[THICK:%.*]] = metatype $@thick MyMetatypeIsThin.Type
// CHECK: store [[THICK]] to [[BOX]]
// CHECK: apply [[FUNC]]<MyMetatypeIsThin.Type>([[BOX]])
consumeGenericInOut(&thinMetatype)
}
| apache-2.0 | 9aab167ab5227b5c3c08c91014bbf6c0 | 54.319149 | 180 | 0.654231 | 3.337612 | false | false | false | false |
danielgindi/Charts | Source/Charts/Data/Implementations/Standard/ChartDataSet.swift | 1 | 16407 | //
// ChartDataSet.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 Algorithms
import Foundation
/// Determines how to round DataSet index values for `ChartDataSet.entryIndex(x, rounding)` when an exact x-value is not found.
@objc
public enum ChartDataSetRounding: Int
{
case up = 0
case down = 1
case closest = 2
}
/// The DataSet class represents one group or type of entries (Entry) in the Chart that belong together.
/// It is designed to logically separate different groups of values inside the Chart (e.g. the values for a specific line in the LineChart, or the values of a specific group of bars in the BarChart).
open class ChartDataSet: ChartBaseDataSet
{
public required init()
{
entries = []
super.init()
}
public override convenience init(label: String)
{
self.init(entries: [], label: label)
}
@objc public init(entries: [ChartDataEntry], label: String)
{
self.entries = entries
super.init(label: label)
self.calcMinMax()
}
@objc public convenience init(entries: [ChartDataEntry])
{
self.init(entries: entries, label: "DataSet")
}
// MARK: - Data functions and accessors
/// - Note: Calls `notifyDataSetChanged()` after setting a new value.
/// - Returns: The array of y-values that this DataSet represents.
/// the entries that this dataset represents / holds together
@objc
open private(set) var entries: [ChartDataEntry]
/// Used to replace all entries of a data set while retaining styling properties.
/// This is a separate method from a setter on `entries` to encourage usage
/// of `Collection` conformances.
///
/// - Parameter entries: new entries to replace existing entries in the dataset
@objc
public func replaceEntries(_ entries: [ChartDataEntry]) {
self.entries = entries
notifyDataSetChanged()
}
/// maximum y-value in the value array
internal var _yMax: Double = -Double.greatestFiniteMagnitude
/// minimum y-value in the value array
internal var _yMin: Double = Double.greatestFiniteMagnitude
/// maximum x-value in the value array
internal var _xMax: Double = -Double.greatestFiniteMagnitude
/// minimum x-value in the value array
internal var _xMin: Double = Double.greatestFiniteMagnitude
open override func calcMinMax()
{
_yMax = -Double.greatestFiniteMagnitude
_yMin = Double.greatestFiniteMagnitude
_xMax = -Double.greatestFiniteMagnitude
_xMin = Double.greatestFiniteMagnitude
guard !isEmpty else { return }
forEach(calcMinMax)
}
open override func calcMinMaxY(fromX: Double, toX: Double)
{
_yMax = -Double.greatestFiniteMagnitude
_yMin = Double.greatestFiniteMagnitude
guard !isEmpty else { return }
let indexFrom = entryIndex(x: fromX, closestToY: .nan, rounding: .closest)
var indexTo = entryIndex(x: toX, closestToY: .nan, rounding: .up)
if indexTo == -1 { indexTo = entryIndex(x: toX, closestToY: .nan, rounding: .closest) }
guard indexTo >= indexFrom else { return }
// only recalculate y
self[indexFrom...indexTo].forEach(calcMinMaxY)
}
@objc open func calcMinMaxX(entry e: ChartDataEntry)
{
_xMin = Swift.min(e.x, _xMin)
_xMax = Swift.max(e.x, _xMax)
}
@objc open func calcMinMaxY(entry e: ChartDataEntry)
{
_yMin = Swift.min(e.y, _yMin)
_yMax = Swift.max(e.y, _yMax)
}
/// Updates the min and max x and y value of this DataSet based on the given Entry.
///
/// - Parameters:
/// - e:
internal func calcMinMax(entry e: ChartDataEntry)
{
calcMinMaxX(entry: e)
calcMinMaxY(entry: e)
}
/// The minimum y-value this DataSet holds
@objc open override var yMin: Double { return _yMin }
/// The maximum y-value this DataSet holds
@objc open override var yMax: Double { return _yMax }
/// The minimum x-value this DataSet holds
@objc open override var xMin: Double { return _xMin }
/// The maximum x-value this DataSet holds
@objc open override var xMax: Double { return _xMax }
/// The number of y-values this DataSet represents
@available(*, deprecated, message: "Use `count` instead")
open override var entryCount: Int { return count }
/// - Throws: out of bounds
/// if `i` is out of bounds, it may throw an out-of-bounds exception
/// - Returns: The entry object found at the given index (not x-value!)
@available(*, deprecated, message: "Use `subscript(index:)` instead.")
open override func entryForIndex(_ i: Int) -> ChartDataEntry?
{
guard indices.contains(i) else {
return nil
}
return self[i]
}
/// - Parameters:
/// - xValue: the x-value
/// - closestToY: If there are multiple y-values for the specified x-value,
/// - rounding: determine whether to round up/down/closest if there is no Entry matching the provided x-value
/// - Returns: The first Entry object found at the given x-value with binary search.
/// If the no Entry at the specified x-value is found, this method returns the Entry at the closest x-value according to the rounding.
/// nil if no Entry object at that x-value.
open override func entryForXValue(
_ xValue: Double,
closestToY yValue: Double,
rounding: ChartDataSetRounding) -> ChartDataEntry?
{
let index = entryIndex(x: xValue, closestToY: yValue, rounding: rounding)
if index > -1
{
return self[index]
}
return nil
}
/// - Parameters:
/// - xValue: the x-value
/// - closestToY: If there are multiple y-values for the specified x-value,
/// - Returns: The first Entry object found at the given x-value with binary search.
/// If the no Entry at the specified x-value is found, this method returns the Entry at the closest x-value.
/// nil if no Entry object at that x-value.
open override func entryForXValue(
_ xValue: Double,
closestToY yValue: Double) -> ChartDataEntry?
{
return entryForXValue(xValue, closestToY: yValue, rounding: .closest)
}
/// - Returns: All Entry objects found at the given xIndex with binary search.
/// An empty array if no Entry object at that index.
open override func entriesForXValue(_ xValue: Double) -> [ChartDataEntry]
{
let match: (ChartDataEntry) -> Bool = { $0.x == xValue }
var partitioned = self.entries
_ = partitioned.partition(by: match)
let i = partitioned.partitioningIndex(where: match)
guard i < endIndex else { return [] }
return partitioned[i...].prefix(while: match)
}
/// - Parameters:
/// - xValue: x-value of the entry to search for
/// - closestToY: If there are multiple y-values for the specified x-value,
/// - rounding: Rounding method if exact value was not found
/// - Returns: The array-index of the specified entry.
/// If the no Entry at the specified x-value is found, this method returns the index of the Entry at the closest x-value according to the rounding.
open override func entryIndex(
x xValue: Double,
closestToY yValue: Double,
rounding: ChartDataSetRounding) -> Int
{
var closest = partitioningIndex { $0.x >= xValue }
guard closest < endIndex else { return index(before: endIndex) }
var closestXValue = self[closest].x
switch rounding {
case .up:
// If rounding up, and found x-value is lower than specified x, and we can go upper...
if closestXValue < xValue && closest < index(before: endIndex)
{
formIndex(after: &closest)
}
case .down:
// If rounding down, and found x-value is upper than specified x, and we can go lower...
if closestXValue > xValue && closest > startIndex
{
formIndex(before: &closest)
}
case .closest:
// The closest value in the beginning of this function
// `var closest = partitioningIndex { $0.x >= xValue }`
// doesn't guarantee closest rounding method
if closest > startIndex {
let distanceAfter = abs(self[closest].x - xValue)
let distanceBefore = abs(self[index(before: closest)].x - xValue)
if distanceBefore < distanceAfter
{
closest = index(before: closest)
}
closestXValue = self[closest].x
}
}
// Search by closest to y-value
if !yValue.isNaN
{
while closest > startIndex && self[index(before: closest)].x == closestXValue
{
formIndex(before: &closest)
}
var closestYValue = self[closest].y
var closestYIndex = closest
while closest < index(before: endIndex)
{
formIndex(after: &closest)
let value = self[closest]
if value.x != closestXValue { break }
if abs(value.y - yValue) <= abs(closestYValue - yValue)
{
closestYValue = yValue
closestYIndex = closest
}
}
closest = closestYIndex
}
return closest
}
/// - Parameters:
/// - e: the entry to search for
/// - Returns: The array-index of the specified entry
// TODO: Should be returning `nil` to follow Swift convention
@available(*, deprecated, message: "Use `firstIndex(of:)` or `lastIndex(of:)`")
open override func entryIndex(entry e: ChartDataEntry) -> Int
{
return firstIndex(of: e) ?? -1
}
/// Adds an Entry to the DataSet dynamically.
/// Entries are added to the end of the list.
/// This will also recalculate the current minimum and maximum values of the DataSet and the value-sum.
///
/// - Parameters:
/// - e: the entry to add
/// - Returns: True
// TODO: This should return `Void` to follow Swift convention
@available(*, deprecated, message: "Use `append(_:)` instead", renamed: "append(_:)")
open override func addEntry(_ e: ChartDataEntry) -> Bool
{
append(e)
return true
}
/// Adds an Entry to the DataSet dynamically.
/// Entries are added to their appropriate index respective to it's x-index.
/// This will also recalculate the current minimum and maximum values of the DataSet and the value-sum.
///
/// - Parameters:
/// - e: the entry to add
/// - Returns: True
// TODO: This should return `Void` to follow Swift convention
open override func addEntryOrdered(_ e: ChartDataEntry) -> Bool
{
if let last = last, last.x > e.x
{
let startIndex = entryIndex(x: e.x, closestToY: e.y, rounding: .up)
let closestIndex = self[startIndex...].lastIndex { $0.x < e.x }
?? startIndex
calcMinMax(entry: e)
entries.insert(e, at: closestIndex)
}
else
{
append(e)
}
return true
}
@available(*, renamed: "remove(_:)")
open override func removeEntry(_ entry: ChartDataEntry) -> Bool
{
remove(entry)
}
/// Removes an Entry from the DataSet dynamically.
/// This will also recalculate the current minimum and maximum values of the DataSet and the value-sum.
///
/// - Parameters:
/// - entry: the entry to remove
/// - Returns: `true` if the entry was removed successfully, else if the entry does not exist
open func remove(_ entry: ChartDataEntry) -> Bool
{
guard let index = firstIndex(of: entry) else { return false }
_ = remove(at: index)
return true
}
/// Removes the first Entry (at index 0) of this DataSet from the entries array.
///
/// - Returns: `true` if successful, `false` if not.
// TODO: This should return the removed entry to follow Swift convention.
@available(*, deprecated, message: "Use `func removeFirst() -> ChartDataEntry` instead.")
open override func removeFirst() -> Bool
{
let entry: ChartDataEntry? = isEmpty ? nil : removeFirst()
return entry != nil
}
/// Removes the last Entry (at index size-1) of this DataSet from the entries array.
///
/// - Returns: `true` if successful, `false` if not.
// TODO: This should return the removed entry to follow Swift convention.
@available(*, deprecated, message: "Use `func removeLast() -> ChartDataEntry` instead.")
open override func removeLast() -> Bool
{
let entry: ChartDataEntry? = isEmpty ? nil : removeLast()
return entry != nil
}
/// Removes all values from this DataSet and recalculates min and max value.
@available(*, deprecated, message: "Use `removeAll(keepingCapacity:)` instead.")
open override func clear()
{
removeAll(keepingCapacity: true)
}
// MARK: - Data functions and accessors
// MARK: - NSCopying
open override func copy(with zone: NSZone? = nil) -> Any
{
let copy = super.copy(with: zone) as! ChartDataSet
copy.entries = entries
copy._yMax = _yMax
copy._yMin = _yMin
copy._xMax = _xMax
copy._xMin = _xMin
return copy
}
}
// MARK: MutableCollection
extension ChartDataSet: MutableCollection {
public typealias Index = Int
public typealias Element = ChartDataEntry
public var startIndex: Index {
return entries.startIndex
}
public var endIndex: Index {
return entries.endIndex
}
public func index(after: Index) -> Index {
return entries.index(after: after)
}
@objc
public subscript(position: Index) -> Element {
get {
// This is intentionally not a safe subscript to mirror
// the behaviour of the built in Swift Collection Types
return entries[position]
}
set {
calcMinMax(entry: newValue)
entries[position] = newValue
}
}
}
// MARK: RandomAccessCollection
extension ChartDataSet: RandomAccessCollection {
public func index(before: Index) -> Index {
return entries.index(before: before)
}
}
// MARK: RangeReplaceableCollection
extension ChartDataSet: RangeReplaceableCollection {
public func replaceSubrange<C>(_ subrange: Swift.Range<Index>, with newElements: C) where C : Collection, Element == C.Element {
entries.replaceSubrange(subrange, with: newElements)
notifyDataSetChanged()
}
public func append(_ newElement: Element) {
calcMinMax(entry: newElement)
entries.append(newElement)
}
public func remove(at position: Index) -> Element {
let element = entries.remove(at: position)
notifyDataSetChanged()
return element
}
public func removeFirst() -> Element {
let element = entries.removeFirst()
notifyDataSetChanged()
return element
}
public func removeFirst(_ n: Int) {
entries.removeFirst(n)
notifyDataSetChanged()
}
public func removeLast() -> Element {
let element = entries.removeLast()
notifyDataSetChanged()
return element
}
public func removeLast(_ n: Int) {
entries.removeLast(n)
notifyDataSetChanged()
}
public func removeSubrange<R>(_ bounds: R) where R : RangeExpression, Index == R.Bound {
entries.removeSubrange(bounds)
notifyDataSetChanged()
}
@objc
public func removeAll(keepingCapacity keepCapacity: Bool) {
entries.removeAll(keepingCapacity: keepCapacity)
notifyDataSetChanged()
}
}
| apache-2.0 | c83b0950e67c0fbf0fb40065c2459cc1 | 32.552147 | 199 | 0.611324 | 4.693078 | false | false | false | false |
rishabhkohli/SwiftColorPicker | SwiftColorPicker/ColorPickerController.swift | 1 | 3638 |
import UIKit
public protocol ColorPickerViewControllerDelegate {
func colorSelected(id: Int, color: UIColor)
}
public class ColorPickerController: UIViewController, ColorPickerViewDelegate, UITextFieldDelegate {
@IBOutlet weak var navBar: UINavigationBar!
@IBOutlet weak var colorPickerView: ColorPickerView!
@IBOutlet weak var oldColorView: UIView!
@IBOutlet weak var newColorView: UIView!
@IBOutlet weak var oldColorHex: UITextField!
@IBOutlet weak var newColorHex: UITextField!
var oldColor: UIColor!
var newColor: UIColor!
public var delegate: ColorPickerViewControllerDelegate?
var id: Int!
var firstTime = true
public convenience init() {
self.init(id: 0, currentColor: UIColor.white)
}
public init(id: Int, currentColor: UIColor) {
super.init(nibName : "ColorPickerController", bundle : Bundle(for: ColorPickerController.self))
self.id = id
oldColor = currentColor
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewDidLoad() {
super.viewDidLoad()
let navItems = UINavigationItem(title: "Pick Color")
navItems.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(dismissSelf))
navItems.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(save))
navBar.items = [navItems]
colorPickerView.delegate = self
newColor = oldColor
oldColorView.layer.borderColor = UIColor.black.cgColor
oldColorView.layer.borderWidth = 1
newColorView.layer.borderColor = UIColor.black.cgColor
newColorView.layer.borderWidth = 1
oldColorView.backgroundColor = oldColor
newColorView.backgroundColor = newColor
oldColorHex.text = oldColor.toHexString()
oldColorHex.isEnabled = false
newColorHex.text = newColor.toHexString()
newColorHex.delegate = self
colorPickerView.update(forColor: newColor)
}
public override func viewDidLayoutSubviews() {
if (firstTime) {
navBar.frame.size.height = navBar.frame.height + self.topLayoutGuide.length
navBar.heightAnchor.constraint(equalToConstant: navBar.frame.height).isActive = true
firstTime = false
}
}
@objc func dismissSelf() {
self.dismiss(animated: true, completion: nil)
}
@objc func save() {
delegate?.colorSelected(id: id, color: newColor)
dismissSelf()
}
func ColorPickerTouched(sender: ColorPickerView, color: UIColor, point: CGPoint, state: UIGestureRecognizerState) {
newColor = color
newColorView.backgroundColor = color
newColorHex.text = newColor.toHexString()
newColorHex.resignFirstResponder()
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let currentCharacterCount = textField.text?.characters.count ?? 0
if (range.length + range.location > currentCharacterCount){
return false
}
let newLength = currentCharacterCount + string.characters.count - range.length
if (newLength <= 6) {
let aSet = NSCharacterSet(charactersIn:"0123456789abcdefABCDEF").inverted
let compSepByCharInSet = string.components(separatedBy: aSet)
let hexFiltered = compSepByCharInSet.joined(separator: "")
if string == hexFiltered {
newColor = UIColor("#" + textField.text! + string)
colorPickerView.update(forColor: newColor)
newColorView.backgroundColor = newColor
return true
} else { return false }
} else { return false }
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| mit | 6e9b8326bcf2fc5d785b5416264ea75c | 29.571429 | 133 | 0.752611 | 4.157714 | false | false | false | false |
natecook1000/swift | test/SILGen/modify_objc.swift | 1 | 3205 | // RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk) -enable-objc-interop -import-objc-header %S/Inputs/modify_objc.h %s | %FileCheck %s
// REQUIRES: objc_interop
public protocol ProtocolWithBlockProperty {
// No abstraction difference between the native witness and the requirement.
var block: ((String?) -> Void)? { get set }
// Abstraction difference between the native witness and the requirement.
associatedtype DependentInput
var dependentBlock: ((DependentInput) -> Void)? { get set }
}
extension ClassWithBlockProperty : ProtocolWithBlockProperty {}
// Protocol witness for 'block'.
// CHECK-LABEL: sil shared [transparent] [serialized] [thunk] @$SSo22ClassWithBlockPropertyC11modify_objc08ProtocolbcD0A2cDP5blockySSSgcSgvMTW :
// CHECK-SAME: $@yield_once @convention(witness_method: ProtocolWithBlockProperty) (@inout ClassWithBlockProperty) -> @yields @inout Optional<@callee_guaranteed (@guaranteed Optional<String>) -> ()>
// CHECK: bb0([[SELF_INDIRECT:%.*]] : @trivial $*ClassWithBlockProperty):
// CHECK-NEXT: [[SELF:%.*]] = load_borrow [[SELF_INDIRECT]] : $*ClassWithBlockProperty
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[FN:%.*]] = function_ref @$SSo22ClassWithBlockPropertyC5blockySSSgcSgvM
// CHECK-NEXT: ([[ADDR:%.*]], [[TOKEN:%.*]]) = begin_apply [[FN]]([[SELF]])
// CHECK-NEXT: yield [[ADDR]] : $*Optional<@callee_guaranteed (@guaranteed Optional<String>) -> ()>
// CHECK-LABEL: sil shared [serializable] @$SSo22ClassWithBlockPropertyC5blockySSSgcSgvM :
// CHECK-SAME: $@yield_once @convention(method) (@guaranteed ClassWithBlockProperty) -> @yields @inout Optional<@callee_guaranteed (@guaranteed Optional<String>) -> ()>
// Protocol witness for 'dependentBlock'
// CHECK-LABEL: sil shared [transparent] [serialized] [thunk] @$SSo22ClassWithBlockPropertyC11modify_objc08ProtocolbcD0A2cDP09dependentC0y14DependentInputQzcSgvMTW :
// CHECK-SAME: $@yield_once @convention(witness_method: ProtocolWithBlockProperty) (@inout ClassWithBlockProperty) -> @yields @inout Optional<@callee_guaranteed (@in_guaranteed Optional<String>) -> ()>
// CHECK: bb0([[SELF_INDIRECT:%.*]] : @trivial $*ClassWithBlockProperty):
// CHECK-NEXT: [[SELF:%.*]] = load_borrow [[SELF_INDIRECT]] : $*ClassWithBlockProperty
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[FN:%.*]] = function_ref @$SSo22ClassWithBlockPropertyC09dependentC0ySSSgcSgvM
// CHECK-NEXT: ([[YIELD_ADDR:%.*]], [[TOKEN:%.*]]) = begin_apply [[FN]]([[SELF]])
// CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Optional<@callee_guaranteed (@in_guaranteed Optional<String>) -> ()>
// CHECK-NEXT: [[IN_FUNCTION:%.*]] = load [take] [[YIELD_ADDR]]
// CHECK: bb3([[OUT_FUNCTION:%.*]] : @owned $Optional<@callee_guaranteed (@in_guaranteed Optional<String>) -> ()>):
// CHECK-NEXT: store [[OUT_FUNCTION]] to [init] [[TEMP]] :
// CHECK-NEXT: yield [[TEMP]] : $*Optional<@callee_guaranteed (@in_guaranteed Optional<String>) -> ()>
// CHECK-LABEL: sil shared [serializable] @$SSo22ClassWithBlockPropertyC09dependentC0ySSSgcSgvM :
// CHECK-SAME: $@yield_once @convention(method) (@guaranteed ClassWithBlockProperty) -> @yields @inout Optional<@callee_guaranteed (@guaranteed Optional<String>) -> ()>
| apache-2.0 | 9049f59a5bebf4123ed105e192d1ea19 | 71.840909 | 204 | 0.714197 | 3.829152 | false | false | false | false |
STShenZhaoliang/iOS-GuidesAndSampleCode | 精通Swift设计模式/Chapter 03/SportsStore/SportsStore/ViewController.swift | 1 | 3616 | import UIKit
class ProductTableCell : UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var stockStepper: UIStepper!
@IBOutlet weak var stockField: UITextField!
var productId:Int?;
}
class ViewController: UIViewController, UITableViewDataSource {
@IBOutlet weak var totalStockLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
var products = [
("Kayak", "A boat for one person", "Watersports", 275.0, 10),
("Lifejacket", "Protective and fashionable", "Watersports", 48.95, 14),
("Soccer Ball", "FIFA-approved size and weight", "Soccer", 19.5, 32),
("Corner Flags", "Give your playing field a professional touch",
"Soccer", 34.95, 1),
("Stadium", "Flat-packed 35,000-seat stadium", "Soccer", 79500.0, 4),
("Thinking Cap", "Improve your brain efficiency by 75%", "Chess", 16.0, 8),
("Unsteady Chair", "Secretly give your opponent a disadvantage",
"Chess", 29.95, 3),
("Human Chess Board", "A fun game for the family", "Chess", 75.0, 2),
("Bling-Bling King", "Gold-plated, diamond-studded King",
"Chess", 1200.0, 4)];
override func viewDidLoad() {
super.viewDidLoad()
displayStockTotal();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return products.count;
}
func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let product = products[indexPath.row];
let cell = tableView.dequeueReusableCellWithIdentifier("ProductCell")
as! ProductTableCell;
cell.productId = indexPath.row;
cell.nameLabel.text = product.0;
cell.descriptionLabel.text = product.1;
cell.stockStepper.value = Double(product.4);
cell.stockField.text = String(product.4);
return cell;
}
@IBAction func stockLevelDidChange(sender: AnyObject) {
if var currentCell = sender as? UIView {
while (true) {
currentCell = currentCell.superview!;
if let cell = currentCell as? ProductTableCell {
let id = cell.productId
if id > 0 {
var newStockLevel:Int?;
if let stepper = sender as? UIStepper {
newStockLevel = Int(stepper.value);
} else if let textfield = sender as? UITextField {
let newValue = Int(textfield.text!)
if newValue >= 0 {
newStockLevel = newValue;
}
}
if let level = newStockLevel {
products[id!].4 = level;
cell.stockStepper.value = Double(level);
cell.stockField.text = String(level);
}
}
break;
}
}
displayStockTotal();
}
}
func displayStockTotal() {
let stockTotal = products.reduce(0, combine: {(total, product) -> Int in return total + product.4});
totalStockLabel.text = "\(stockTotal) Products in Stock";
}
}
| mit | 64b5adb172996159e88c8b04f5ed7271 | 36.666667 | 108 | 0.541759 | 5.00831 | false | false | false | false |
seorenn/SRChoco | Source/SRAuth.swift | 1 | 952 | //
// SRAuth.swift
// SRChoco
//
// Created by Seorenn on 2015. 4. 15.
// Copyright (c) 2015 Seorenn. All rights reserved.
//
import LocalAuthentication
public class SRAuth {
public static let shared = SRAuth()
public var canAuthWithTouchID: Bool {
#if os(iOS)
let context = LAContext()
var error: NSError?
let result = context.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: &error)
if error == nil { return result }
else { return false }
#else
return false
#endif
}
public func authWithTouchID(reason: String, callback: ((_ auth: Bool) -> Void)?) {
#if os(iOS)
let context = LAContext()
context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason, reply: {
(result, error) -> Void in
DispatchQueue.main.async {
callback?(result)
}
})
#endif
}
}
| mit | f2604a0c6690adf576e7e709523657b3 | 22.8 | 109 | 0.62605 | 4.269058 | false | false | false | false |
JadenGeller/Spork | Sources/BufferingGenerator.swift | 1 | 4550 | //
// BufferingGenerator.swift
// Spork
//
// Created by Jaden Geller on 10/12/15.
//
//
// Allows any generator (even one that normally has reference-like semantics) to be forked
public final class BufferingGenerator<Element> {
internal let state: SharedGeneratorBufferState<Element>
// Note that it is illegal to call next on a generator after bridging it
public init<G: GeneratorType where G.Element == Element>(bridgedFromGenerator generator: G) {
state = SharedGeneratorBufferState(backing: generator)
state.registerListener(self)
}
internal init(state: SharedGeneratorBufferState<Element>, offset: Int) {
self.state = state
state.setFallbehind(offset, forListener: self)
}
deinit {
state.deregisterListener(self)
}
}
extension BufferingGenerator: GeneratorType {
public func next() -> Element? {
defer { state.decrementFallbehind(forListener: self) }
return peek()
}
}
extension BufferingGenerator: ForkableGeneratorType {
public func fork() -> BufferingGenerator<Element> {
return BufferingGenerator(state: state, offset: state.getFallbehind(forListener: self)!)
}
public func peek() -> Element? {
return state.element(forListener: self)
}
}
extension BufferingGenerator: Comparable {}
public func ==<Element>(lhs: BufferingGenerator<Element>, rhs: BufferingGenerator<Element>) -> Bool {
precondition(lhs.state === rhs.state, "Generators can only be compared if forked from a common generator.")
return lhs.state.getFallbehind(forListener: lhs) == rhs.state.getFallbehind(forListener: rhs)
}
public func <<Element>(lhs: BufferingGenerator<Element>, rhs: BufferingGenerator<Element>) -> Bool {
precondition(lhs.state === rhs.state, "Generators can only be compared if forked from a common generator.")
return lhs.state.getFallbehind(forListener: lhs) > rhs.state.getFallbehind(forListener: rhs)
}
// Shared state that keeps elements in its buffer only if they'll be needed
final class SharedGeneratorBufferState<Element> {
var generator: AnyGenerator<Element>
var buffer: [Element?] = [] // Rightmost values are the oldest
init<G: GeneratorType where G.Element == Element>(backing: G) {
generator = anyGenerator(backing)
}
// Represents negative buffer index of last requested element
var listenerFallbehinds: [ObjectIdentifier : Int] = [:]
var maxFallbehind: Int {
return buffer.count - 1
}
typealias Listener = BufferingGenerator<Element>
func getFallbehind(forListener listener: Listener) -> Int? {
return listenerFallbehinds[ObjectIdentifier(listener)]
}
func setFallbehind(fallbehind: Int?, forListener listener: Listener, trimmingBuffer: Bool = true) {
if let fallbehind = fallbehind {
assert(fallbehind <= maxFallbehind, "Cannot set buffer fallbehind past that of disposed element.")
listenerFallbehinds[ObjectIdentifier(listener)] = fallbehind
} else {
listenerFallbehinds.removeValueForKey(ObjectIdentifier(listener))
}
if trimmingBuffer { trimBuffer() } // Drop any elements that only this listener needed
}
func registerListener(listener: Listener) {
setFallbehind(-1, forListener: listener)
}
func deregisterListener(listener: Listener) {
setFallbehind(nil, forListener: listener)
}
func ensureBufferContainsElement(forListener listener: Listener) {
// Request next element and ensure its in the buffer
while getFallbehind(forListener: listener) < 0 {
// Update offsets since we're shifting the buffer
for (key, value) in listenerFallbehinds { listenerFallbehinds[key] = value + 1 }
buffer.insert(generator.next(), atIndex: 0)
}
}
func element(forListener listener: Listener) -> Element? {
ensureBufferContainsElement(forListener: listener)
return buffer[getFallbehind(forListener: listener)!]
}
func decrementFallbehind(forListener listener: Listener) {
setFallbehind(getFallbehind(forListener: listener)! - 1, forListener: listener)
}
func trimBuffer() {
// Remove fully consumed buffer elements
if let maxNecessaryFallbehind = listenerFallbehinds.values.maxElement() {
while maxFallbehind > maxNecessaryFallbehind {
buffer.removeLast()
}
}
}
}
| mit | 2c6225cc56e03b833b820fe76085e7fe | 35.99187 | 111 | 0.684176 | 4.527363 | false | false | false | false |
jindulys/Leetcode_Solutions_Swift | Sources/LinkedList/206_ReverseLinkedList.swift | 1 | 571 | //
// 206_ReverseLinkedList.swift
// LeetcodeSwift
//
// Created by yansong li on 2016-11-05.
// Copyright © 2016 YANSONG LI. All rights reserved.
//
import Foundation
/**
Title:206 Reverse LinkedList
URL: https://leetcode.com/problems/reverse-linked-list/
Space: O(1)
Time: O(N)
*/
class ReverseLinkedList_Solution {
func reverseList(_ head: ListNode?) -> ListNode? {
var temp: ListNode?
var first = head
while let validNode = first {
first = validNode.next
validNode.next = temp
temp = validNode
}
return temp
}
}
| mit | 72cd562b772b60613a6a1e695d72196d | 18.655172 | 56 | 0.657895 | 3.392857 | false | false | false | false |
tardieu/swift | stdlib/public/core/Misc.swift | 17 | 4074 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// Extern C functions
//===----------------------------------------------------------------------===//
// FIXME: Once we have an FFI interface, make these have proper function bodies
@_transparent
public // @testable
func _countLeadingZeros(_ value: Int64) -> Int64 {
return Int64(Builtin.int_ctlz_Int64(value._value, false._value))
}
/// Returns if `x` is a power of 2.
@_transparent
public // @testable
func _isPowerOf2(_ x: UInt) -> Bool {
if x == 0 {
return false
}
// Note: use unchecked subtraction because we have checked that `x` is not
// zero.
return x & (x &- 1) == 0
}
/// Returns if `x` is a power of 2.
@_transparent
public // @testable
func _isPowerOf2(_ x: Int) -> Bool {
if x <= 0 {
return false
}
// Note: use unchecked subtraction because we have checked that `x` is not
// `Int.min`.
return x & (x &- 1) == 0
}
#if _runtime(_ObjC)
@_transparent
public func _autorelease(_ x: AnyObject) {
Builtin.retain(x)
Builtin.autorelease(x)
}
#endif
/// Invoke `body` with an allocated, but uninitialized memory suitable for a
/// `String` value.
///
/// This function is primarily useful to call various runtime functions
/// written in C++.
func _withUninitializedString<R>(
_ body: (UnsafeMutablePointer<String>) -> R
) -> (R, String) {
let stringPtr = UnsafeMutablePointer<String>.allocate(capacity: 1)
let bodyResult = body(stringPtr)
let stringResult = stringPtr.move()
stringPtr.deallocate(capacity: 1)
return (bodyResult, stringResult)
}
// FIXME(ABI)#51 : this API should allow controlling different kinds of
// qualification separately: qualification with module names and qualification
// with type names that we are nested in.
// But we can place it behind #if _runtime(_Native) and remove it from ABI on
// Apple platforms, deferring discussions mentioned above.
@_silgen_name("swift_getTypeName")
public func _getTypeName(_ type: Any.Type, qualified: Bool)
-> (UnsafePointer<UInt8>, Int)
/// Returns the demangled qualified name of a metatype.
public // @testable
func _typeName(_ type: Any.Type, qualified: Bool = true) -> String {
let (stringPtr, count) = _getTypeName(type, qualified: qualified)
return ._fromWellFormedCodeUnitSequence(UTF8.self,
input: UnsafeBufferPointer(start: stringPtr, count: count))
}
@_silgen_name("swift_getTypeByName")
func _getTypeByName(
_ name: UnsafePointer<UInt8>,
_ nameLength: UInt)
-> Any.Type?
/// Lookup a class given a name. Until the demangled encoding of type
/// names is stabilized, this is limited to top-level class names (Foo.bar).
public // SPI(Foundation)
func _typeByName(_ name: String) -> Any.Type? {
let nameUTF8 = Array(name.utf8)
return nameUTF8.withUnsafeBufferPointer { (nameUTF8) in
let type = _getTypeByName(nameUTF8.baseAddress!,
UInt(nameUTF8.endIndex))
return type
}
}
/// Returns `floor(log(x))`. This equals to the position of the most
/// significant non-zero bit, or 63 - number-of-zeros before it.
///
/// The function is only defined for positive values of `x`.
///
/// Examples:
///
/// floorLog2(1) == 0
/// floorLog2(2) == floorLog2(3) == 1
/// floorLog2(9) == floorLog2(15) == 3
///
/// TODO: Implement version working on Int instead of Int64.
@_transparent
public // @testable
func _floorLog2(_ x: Int64) -> Int {
_sanityCheck(x > 0, "_floorLog2 operates only on non-negative integers")
// Note: use unchecked subtraction because we this expression cannot
// overflow.
return 63 &- Int(_countLeadingZeros(x))
}
| apache-2.0 | 0efc3296d7ca56676659ab4e0811a6da | 31.592 | 80 | 0.650221 | 3.990206 | false | false | false | false |
tristanchu/FlavorFinder | FlavorFinder/FlavorFinder/LoginViewPage.swift | 1 | 4662 | //
// LoginViewPage.swift
// FlavorFinder
//
// Handles the login view
//
// Created by Courtney Ligh on 2/1/16.
// Copyright © 2016 TeamFive. All rights reserved.
//
import Foundation
import UIKit
import Parse
class LoginViewPage : UIViewController, UITextFieldDelegate {
// Navigation in containers (set during segue)
var buttonSegue : String!
// MARK: Properties
@IBOutlet weak var loginPromptLabel: UILabel!
var isValid: Bool = true
// Text fields:
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
// Buttons:
@IBOutlet weak var loginButton:UIButton!
@IBOutlet weak var sigupUpButton: UIButton!
// Pop up text:
let INCORRECT_U_OR_P_TITLE = "Incorrect Username or Password"
let INCORRECT_U_OR_P_MSG = "Username and Password do not match."
let INVALID_TITLE = "Invalid Username or Password"
let INVALID_MSG = "You must enter a valid username and password."
// Toast Text:
let LOGGED_IN_MESSAGE = "Logged in as " // + username dynamically
// MARK: Actions --------------------------------------------------
// Login button:
@IBAction func loginButtonAction(sender: UIButton) {
loginUser(usernameField.text, password: passwordField.text)
}
// Sign up button:
@IBAction func signUpButtonAction(sender: UIButton) {
if let parent = parentViewController as? ContainerViewController {
parent.segueIdentifierReceivedFromParent(buttonSegue)
}
}
// OVERRIDE FUNCTIONS ---------------------------------------------
/**
viewDidLoad
Controls visuals upon loading view.
*/
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.hidesBackButton = true
usernameField.delegate = self
passwordField.delegate = self
usernameField.setTextLeftPadding(5)
passwordField.setTextLeftPadding(5)
// button visuals:
setDefaultButtonUI(loginButton)
setSecondaryButtonUI(sigupUpButton)
}
/*
viewDidAppear
runs when view appears
*/
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
/**
loginUser
Checks input for user and pw fields as valid strings, authenticates
using Parse, then logs in user if successful.
@param: username - String! - string given in username input field
@param: password - String! - string given in password input field
*/
func loginUser(username: String!, password: String!) {
// Default to true:
isValid = true
// Validate username and password input:
if isInvalidUsername(username) {
usernameField.backgroundColor = backgroundColor_error
isValid = false
}
if isInvalidPassword(password) {
passwordField.backgroundColor = backgroundColor_error
isValid = false
}
if isValid {
// Authenticate user with Parse
PFUser.logInWithUsernameInBackground(
username!, password: password!) {
(user: PFUser?, error: NSError?) -> Void in
if user != nil {
// User exists - set user session
setUserSession(user!)
if let parentVC = self.parentViewController?.parentViewController as! LoginModuleParentViewController? {
parentVC.loginSucceeded()
// Test Toast:
let loginMsg = self.LOGGED_IN_MESSAGE + "\(username)"
parentVC.view.makeToast(loginMsg, duration: TOAST_DURATION, position: .Bottom)
print("SUCCESS: logged in")
} else {
print("ERROR: could not find user")
}
} else {
// Alert Username and Password pair does not exist.
alertPopup(self.INCORRECT_U_OR_P_TITLE,
msg: self.INCORRECT_U_OR_P_MSG as String,
actionTitle: OK_TEXT,
currController: self)
print("ERROR: username and password pair do not exist")
}
}
} else {
// Alert missing username or password fields:
alertPopup(self.INVALID_TITLE,
msg: self.INVALID_MSG as String,
actionTitle: OK_TEXT,
currController: self)
}
}
} | mit | fce26b3014ea3975bc5870eedf5449cd | 31.601399 | 128 | 0.573053 | 5.254791 | false | false | false | false |
crossroadlabs/Express | Express/HttpMethod.swift | 1 | 1117 | //===--- HttpMethod.swift -------------------------------------------------===//
//
//Copyright (c) 2015-2016 Daniel Leping (dileping)
//
//This file is part of Swift Express.
//
//Swift Express is free software: you can redistribute it and/or modify
//it under the terms of the GNU Lesser General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//Swift Express 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 Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public License
//along with Swift Express. If not, see <http://www.gnu.org/licenses/>.
//
//===----------------------------------------------------------------------===//
import Foundation
public enum HttpMethod : String {
case `Any` = "*"
case Get = "GET"
case Post = "POST"
case Put = "PUT"
case Delete = "DELETE"
case Patch = "PATCH"
}
| gpl-3.0 | 99fa286a18ee465bd939f530fc19809a | 35.032258 | 80 | 0.625783 | 4.522267 | false | false | false | false |
tianbinbin/DouYuShow | DouYuShow/DouYuShow/Classes/Main/Controller/CustomViewController.swift | 1 | 2153 | //
// CustomViewController.swift
// DouYuShow
//
// Created by 田彬彬 on 2017/6/17.
// Copyright © 2017年 田彬彬. All rights reserved.
//
import UIKit
class CustomViewController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
//1. 获取系统的pop 手势
guard let sysetmGes = interactivePopGestureRecognizer else {return}
//2. 获取手势添加到的view中
guard let gestView = sysetmGes.view else { return }
//3. 获取系统 target action
//3.1 利用运行时机制 查看所有的属性名称
// 系统没有把一个属性暴露给我们 而我们又想用它 就是通过截取
/*
var count:UInt32 = 0
// 通过属性类型 遍历所有的属性名称 ivars保存的是所有属性的地址
let ivars = class_copyIvarList(UIGestureRecognizer.self, &count)
for i in 0..<count{
let ivar = ivars?[Int(i)]
//1. 获取属性的名字
let name = ivar_getName(ivar)
//2. 将指针转换成字符串
print(String(cString: name!))
}
*/
let targets = sysetmGes.value(forKey: "_targets") as? [NSObject]
guard let targetObjc = targets?.first else {return}
print(targetObjc)
// 取出target
guard let tagert = targetObjc.value(forKey: "target") else{return}
// 取出action
// guard let action = targetObjc.value(forKey: "action") as? Selector else {return}
let action = Selector(("handleNavigationTransition:"))
// 创建自己的手势
let panGes = UIPanGestureRecognizer()
gestView.addGestureRecognizer(panGes)
panGes.addTarget(tagert, action: action)
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
viewController.hidesBottomBarWhenPushed = true
super.pushViewController(viewController, animated: animated)
}
}
| mit | cf9eb4a5738badea30610fb6d3e41557 | 27.029412 | 90 | 0.579224 | 4.538095 | false | false | false | false |
Estanque/RichEditorView | RichEditorView/Classes/RichEditorToolbar.swift | 2 | 5453 | //
// RichEditorToolbar.swift
//
// Created by Caesar Wirth on 4/2/15.
// Copyright (c) 2015 Caesar Wirth. All rights reserved.
//
import UIKit
/// RichEditorToolbarDelegate is a protocol for the RichEditorToolbar.
/// Used to receive actions that need extra work to perform (eg. display some UI)
@objc public protocol RichEditorToolbarDelegate: class {
/// Called when the Text Color toolbar item is pressed.
@objc optional func richEditorToolbarChangeTextColor(_ toolbar: RichEditorToolbar)
/// Called when the Background Color toolbar item is pressed.
@objc optional func richEditorToolbarChangeBackgroundColor(_ toolbar: RichEditorToolbar)
/// Called when the Insert Image toolbar item is pressed.
@objc optional func richEditorToolbarInsertImage(_ toolbar: RichEditorToolbar)
/// Called when the Insert Link toolbar item is pressed.
@objc optional func richEditorToolbarInsertLink(_ toolbar: RichEditorToolbar)
}
/// RichBarButtonItem is a subclass of UIBarButtonItem that takes a callback as opposed to the target-action pattern
@objcMembers open class RichBarButtonItem: UIBarButtonItem {
open var actionHandler: (() -> Void)?
public convenience init(image: UIImage? = nil, handler: (() -> Void)? = nil) {
self.init(image: image, style: .plain, target: nil, action: nil)
target = self
action = #selector(RichBarButtonItem.buttonWasTapped)
actionHandler = handler
}
public convenience init(title: String = "", handler: (() -> Void)? = nil) {
self.init(title: title, style: .plain, target: nil, action: nil)
target = self
action = #selector(RichBarButtonItem.buttonWasTapped)
actionHandler = handler
}
@objc func buttonWasTapped() {
actionHandler?()
}
}
/// RichEditorToolbar is UIView that contains the toolbar for actions that can be performed on a RichEditorView
@objcMembers open class RichEditorToolbar: UIView {
/// The delegate to receive events that cannot be automatically completed
open weak var delegate: RichEditorToolbarDelegate?
/// A reference to the RichEditorView that it should be performing actions on
open weak var editor: RichEditorView?
/// The list of options to be displayed on the toolbar
open var options: [RichEditorOption] = [] {
didSet {
updateToolbar()
}
}
/// The tint color to apply to the toolbar background.
open var barTintColor: UIColor? {
get { return backgroundToolbar.barTintColor }
set { backgroundToolbar.barTintColor = newValue }
}
private var toolbarScroll: UIScrollView
private var toolbar: UIToolbar
private var backgroundToolbar: UIToolbar
public override init(frame: CGRect) {
toolbarScroll = UIScrollView()
toolbar = UIToolbar()
backgroundToolbar = UIToolbar()
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
toolbarScroll = UIScrollView()
toolbar = UIToolbar()
backgroundToolbar = UIToolbar()
super.init(coder: aDecoder)
setup()
}
private func setup() {
autoresizingMask = .flexibleWidth
backgroundColor = .clear
backgroundToolbar.frame = bounds
backgroundToolbar.autoresizingMask = [.flexibleHeight, .flexibleWidth]
toolbar.autoresizingMask = .flexibleWidth
toolbar.backgroundColor = .clear
toolbar.setBackgroundImage(UIImage(), forToolbarPosition: .any, barMetrics: .default)
toolbar.setShadowImage(UIImage(), forToolbarPosition: .any)
toolbarScroll.frame = bounds
toolbarScroll.autoresizingMask = [.flexibleHeight, .flexibleWidth]
toolbarScroll.showsHorizontalScrollIndicator = false
toolbarScroll.showsVerticalScrollIndicator = false
toolbarScroll.backgroundColor = .clear
toolbarScroll.addSubview(toolbar)
addSubview(backgroundToolbar)
addSubview(toolbarScroll)
updateToolbar()
}
private func updateToolbar() {
var buttons = [UIBarButtonItem]()
for option in options {
let handler = { [weak self] in
if let strongSelf = self {
option.action(strongSelf)
}
}
if let image = option.image {
let button = RichBarButtonItem(image: image, handler: handler)
buttons.append(button)
} else {
let title = option.title
let button = RichBarButtonItem(title: title, handler: handler)
buttons.append(button)
}
}
toolbar.items = buttons
let defaultIconWidth: CGFloat = 28
let barButtonItemMargin: CGFloat = 11
let width: CGFloat = buttons.reduce(0) {sofar, new in
if let view = new.value(forKey: "view") as? UIView {
return sofar + view.frame.size.width + barButtonItemMargin
} else {
return sofar + (defaultIconWidth + barButtonItemMargin)
}
}
if width < frame.size.width {
toolbar.frame.size.width = frame.size.width
} else {
toolbar.frame.size.width = width
}
toolbar.frame.size.height = 44
toolbarScroll.contentSize.width = width
}
}
| bsd-3-clause | 00df9064a1d14e9814715778bd45bb1b | 33.955128 | 116 | 0.648084 | 5.28904 | false | false | false | false |
omarojo/MyC4FW | Pods/C4/C4/UI/StoredAnimation.swift | 2 | 3581 | // Copyright © 2014 C4
//
// 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
/// StoredAnimation is a concrete subclass of Animation.
///
/// A StoredAnimation object is able to apply a set of stored animation properties to an object.
///
/// This class is useful for serializing and deserializing animations.
public class StoredAnimation: Animation {
/// A dictionary of keys whose values will be applied to animatable properties of the receiver. The keys should map directly to the names of animatable properies.
public var values = [String: AnyObject]()
/// Initiates the changes specified in the receivers `animations` block.
/// - parameter object: An object to which the animations apply
public func animate(object: NSObject) {
let disable = ShapeLayer.disableActions
ShapeLayer.disableActions = false
var timing: CAMediaTimingFunction
var options: UIViewAnimationOptions = [UIViewAnimationOptions.beginFromCurrentState]
switch curve {
case .Linear:
options = [options, .curveLinear]
timing = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
case .EaseOut:
options = [options, .curveEaseOut]
timing = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
case .EaseIn:
options = [options, .curveEaseIn]
timing = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
case .EaseInOut:
options = [options, .curveEaseIn, .curveEaseOut]
timing = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
}
autoreverses == true ? options.formUnion(.autoreverse) : options.subtract(.autoreverse)
repeatCount > 0 ? options.formUnion(.repeat) : options.subtract(.repeat)
UIView.animate(withDuration: duration, delay: 0, options: options, animations: {
ViewAnimation.stack.append(self)
UIView.setAnimationRepeatCount(Float(self.repeatCount))
CATransaction.begin()
CATransaction.setAnimationDuration(self.duration)
CATransaction.setAnimationTimingFunction(timing)
CATransaction.setCompletionBlock({
self.postCompletedEvent()
})
for (key, value) in self.values {
object.setValue(value, forKeyPath: key)
}
CATransaction.commit()
ViewAnimation.stack.removeLast()
}, completion:nil)
ShapeLayer.disableActions = disable
}
}
| mit | 3e1f1c39164b942cd746c12f593f01bb | 47.378378 | 166 | 0.701955 | 5.343284 | false | false | false | false |
kaojohnny/CoreStore | Sources/ObjectiveC/CSSelect.swift | 1 | 13961 | //
// CSSelect.swift
// CoreStore
//
// Copyright © 2016 John Rommel Estropia
//
// 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 CoreData
// MARK: - CSSelectTerm
/**
The `CSSelectTerm` serves as the Objective-C bridging type for `SelectTerm`.
- SeeAlso: `SelectTerm`
*/
@objc
public final class CSSelectTerm: NSObject, CoreStoreObjectiveCType {
/**
Provides a `CSSelectTerm` to a `CSSelect` clause for querying an entity attribute.
```
NSString *fullName = [CSCoreStore
queryValueFrom:[CSFrom entityClass:[MyPersonEntity class]]
select:CSSelectString(CSAttribute(@"fullname"))
fetchClauses:@[[CSWhere keyPath:@"employeeID" isEqualTo: @1111]]];
```
- parameter keyPath: the attribute name
*/
@objc
public convenience init(keyPath: KeyPath) {
self.init(.Attribute(keyPath))
}
/**
Provides a `CSSelectTerm` to a `CSSelect` clause for querying the average value of an attribute.
```
NSNumber *averageAge = [CSCoreStore
queryValueFrom:[CSFrom entityClass:[MyPersonEntity class]]
select:[CSSelect numberForTerm:[CSSelectTerm average:@"age" as:nil]]];
```
- parameter keyPath: the attribute name
- parameter `as`: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "average(<attributeName>)" is used
- returns: a `CSSelectTerm` to a `CSSelect` clause for querying the average value of an attribute
*/
@objc
public static func average(keyPath: KeyPath, `as` alias: KeyPath?) -> CSSelectTerm {
return self.init(.Average(keyPath, As: alias))
}
/**
Provides a `CSSelectTerm` to a `CSSelect` clause for a count query.
```
NSNumber *numberOfEmployees = [CSCoreStore
queryValueFrom:[CSFrom entityClass:[MyPersonEntity class]]
select:[CSSelect numberForTerm:[CSSelectTerm count:@"employeeID" as:nil]]];
```
- parameter keyPath: the attribute name
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "count(<attributeName>)" is used
- returns: a `SelectTerm` to a `Select` clause for a count query
*/
@objc
public static func count(keyPath: KeyPath, `as` alias: KeyPath?) -> CSSelectTerm {
return self.init(.Count(keyPath, As: alias))
}
/**
Provides a `CSSelectTerm` to a `CSSelect` clause for querying the maximum value for an attribute.
```
NSNumber *maximumAge = [CSCoreStore
queryValueFrom:[CSFrom entityClass:[MyPersonEntity class]]
select:[CSSelect numberForTerm:[CSSelectTerm maximum:@"age" as:nil]]];
```
- parameter keyPath: the attribute name
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "max(<attributeName>)" is used
- returns: a `CSSelectTerm` to a `CSSelect` clause for querying the maximum value for an attribute
*/
@objc
public static func maximum(keyPath: KeyPath, `as` alias: KeyPath?) -> CSSelectTerm {
return self.init(.Maximum(keyPath, As: alias))
}
/**
Provides a `CSSelectTerm` to a `CSSelect` clause for querying the minimum value for an attribute.
```
NSNumber *minimumAge = [CSCoreStore
queryValueFrom:[CSFrom entityClass:[MyPersonEntity class]]
select:[CSSelect numberForTerm:[CSSelectTerm minimum:@"age" as:nil]]];
```
- parameter keyPath: the attribute name
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "min(<attributeName>)" is used
- returns: a `CSSelectTerm` to a `CSSelect` clause for querying the minimum value for an attribute
*/
@objc
public static func minimum(keyPath: KeyPath, `as` alias: KeyPath?) -> CSSelectTerm {
return self.init(.Minimum(keyPath, As: alias))
}
/**
Provides a `CSSelectTerm` to a `CSSelect` clause for querying the sum value for an attribute.
```
NSNumber *totalAge = [CSCoreStore
queryValueFrom:[CSFrom entityClass:[MyPersonEntity class]]
select:[CSSelect numberForTerm:[CSSelectTerm sum:@"age" as:nil]]];
```
- parameter keyPath: the attribute name
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "sum(<attributeName>)" is used
- returns: a `CSSelectTerm` to a `CSSelect` clause for querying the sum value for an attribute
*/
@objc
public static func sum(keyPath: KeyPath, `as` alias: KeyPath?) -> CSSelectTerm {
return self.init(.Sum(keyPath, As: alias))
}
/**
Provides a `CSSelectTerm` to a `CSSelect` clause for querying the `NSManagedObjectID`.
```
NSManagedObjectID *objectID = [CSCoreStore
queryValueFrom:[CSFrom entityClass:[MyPersonEntity class]]
select:[CSSelect objectIDForTerm:[CSSelectTerm objectIDAs:nil]]
fetchClauses:@[[CSWhere keyPath:@"employeeID" isEqualTo: @1111]]];
```
- parameter keyPath: the attribute name
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "objecID" is used
- returns: a `SelectTerm` to a `Select` clause for querying the sum value for an attribute
*/
@objc
public static func objectIDAs(alias: KeyPath? = nil) -> CSSelectTerm {
return self.init(.ObjectID(As: alias))
}
// MARK: NSObject
public override var hash: Int {
return self.bridgeToSwift.hashValue
}
public override func isEqual(object: AnyObject?) -> Bool {
guard let object = object as? CSSelectTerm else {
return false
}
return self.bridgeToSwift == object.bridgeToSwift
}
// MARK: CoreStoreObjectiveCType
public let bridgeToSwift: SelectTerm
public init(_ swiftValue: SelectTerm) {
self.bridgeToSwift = swiftValue
super.init()
}
}
// MARK: - SelectTerm
extension SelectTerm: CoreStoreSwiftType {
// MARK: CoreStoreSwiftType
public typealias ObjectiveCType = CSSelectTerm
}
// MARK: - CSSelect
/**
The `CSSelect` serves as the Objective-C bridging type for `Select`.
- SeeAlso: `Select`
*/
@objc
public final class CSSelect: NSObject {
/**
Creates a `CSSelect` clause for querying `NSNumber` values.
```
NSNumber *maxAge = [CSCoreStore
queryValueFrom:CSFromClass([MyPersonEntity class])
select:CSSelectNumber(CSAggregateMax(@"age"))
// ...
```
- parameter term: the `CSSelectTerm` specifying the attribute/aggregate value to query
*/
public convenience init(numberTerm: CSSelectTerm) {
self.init(Select<NSNumber>(numberTerm.bridgeToSwift))
}
/**
Creates a `CSSelect` clause for querying `NSDecimalNumber` values.
```
NSDecimalNumber *averagePrice = [CSCoreStore
queryValueFrom:CSFromClass([MyPersonEntity class])
select:CSSelectDecimal(CSAggregateAverage(@"price"))
// ...
```
- parameter term: the `CSSelectTerm` specifying the attribute/aggregate value to query
*/
public convenience init(decimalTerm: CSSelectTerm) {
self.init(Select<NSDecimalNumber>(decimalTerm.bridgeToSwift))
}
/**
Creates a `CSSelect` clause for querying `NSString` values.
```
NSString *fullname = [CSCoreStore
queryValueFrom:CSFromClass([MyPersonEntity class])
select:CSSelectString(CSAttribute(@"fullname"))
// ...
```
- parameter term: the `CSSelectTerm` specifying the attribute/aggregate value to query
*/
public convenience init(stringTerm: CSSelectTerm) {
self.init(Select<NSString>(stringTerm.bridgeToSwift))
}
/**
Creates a `CSSelect` clause for querying `NSDate` values.
```
NSDate *lastUpdate = [CSCoreStore
queryValueFrom:CSFromClass([MyPersonEntity class])
select:CSSelectDate(CSAggregateMax(@"updatedDate"))
// ...
```
- parameter term: the `CSSelectTerm` specifying the attribute/aggregate value to query
*/
public convenience init(dateTerm: CSSelectTerm) {
self.init(Select<NSDate>(dateTerm.bridgeToSwift))
}
/**
Creates a `CSSelect` clause for querying `NSData` values.
```
NSData *imageData = [CSCoreStore
queryValueFrom:CSFromClass([MyPersonEntity class])
select:CSSelectData(CSAttribute(@"imageData"))
// ...
```
- parameter term: the `CSSelectTerm` specifying the attribute/aggregate value to query
*/
public convenience init(dataTerm: CSSelectTerm) {
self.init(Select<NSData>(dataTerm.bridgeToSwift))
}
/**
Creates a `CSSelect` clause for querying `NSManagedObjectID` values.
```
NSManagedObjectID *objectID = [CSCoreStore
queryValueFrom:CSFromClass([MyPersonEntity class])
select:CSSelectObjectID()
// ...
```
- parameter term: the `CSSelectTerm` specifying the attribute/aggregate value to query
*/
public convenience init(objectIDTerm: ()) {
self.init(Select<NSManagedObjectID>(.ObjectID()))
}
/**
Creates a `CSSelect` clause for querying `NSDictionary` of an entity's attribute keys and values.
```
NSDictionary *keyValues = [CSCoreStore
queryValueFrom:[CSFrom entityClass:[MyPersonEntity class]]
select:[CSSelect dictionaryForTerm:[CSSelectTerm maximum:@"age" as:nil]]];
```
- parameter term: the `CSSelectTerm` specifying the attribute/aggregate value to query
- returns: a `CSSelect` clause for querying an entity attribute
*/
public static func dictionaryForTerm(term: CSSelectTerm) -> CSSelect {
return self.init(Select<NSDictionary>(term.bridgeToSwift))
}
/**
Creates a `CSSelect` clause for querying `NSDictionary` of an entity's attribute keys and values.
```
NSDictionary *keyValues = [CSCoreStore
queryValueFrom:[CSFrom entityClass:[MyPersonEntity class]]
select:[CSSelect dictionaryForTerms:@[
[CSSelectTerm attribute:@"name" as:nil],
[CSSelectTerm attribute:@"age" as:nil]
]]];
```
- parameter terms: the `CSSelectTerm`s specifying the attribute/aggregate values to query
- returns: a `CSSelect` clause for querying an entity attribute
*/
public static func dictionaryForTerms(terms: [CSSelectTerm]) -> CSSelect {
return self.init(Select<NSDictionary>(terms.map { $0.bridgeToSwift }))
}
// MARK: NSObject
public override var hash: Int {
return self.attributeType.hashValue
^ self.selectTerms.map { $0.hashValue }.reduce(0, combine: ^)
}
public override func isEqual(object: AnyObject?) -> Bool {
guard let object = object as? CSSelect else {
return false
}
return self.attributeType == object.attributeType
&& self.selectTerms == object.selectTerms
}
public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)"
}
// MARK: CoreStoreObjectiveCType
public init<T: SelectValueResultType>(_ swiftValue: Select<T>) {
self.attributeType = T.attributeType
self.selectTerms = swiftValue.selectTerms
self.bridgeToSwift = swiftValue
super.init()
}
public init<T: SelectResultType>(_ swiftValue: Select<T>) {
self.attributeType = .UndefinedAttributeType
self.selectTerms = swiftValue.selectTerms
self.bridgeToSwift = swiftValue
super.init()
}
// MARK: Internal
internal let attributeType: NSAttributeType
internal let selectTerms: [SelectTerm]
// MARK: Private
private let bridgeToSwift: CoreStoreDebugStringConvertible
}
// MARK: - Select
extension Select: CoreStoreSwiftType {
// MARK: CoreStoreSwiftType
public var bridgeToObjectiveC: CSSelect {
return CSSelect(self)
}
}
| mit | 418d4e36dccc2bf8ceabca36c9f13723 | 32.801453 | 193 | 0.650358 | 4.810476 | false | false | false | false |
tjw/swift | validation-test/compiler_crashers_2_fixed/0126-sr5905.swift | 16 | 864 | // RUN: %target-swift-frontend %s -emit-ir -o /dev/null
protocol VectorIndex {
associatedtype Vector8 : Vector where Vector8.Index == Self, Vector8.Element == UInt8
}
enum VectorIndex1 : VectorIndex {
case i0
typealias Vector8 = Vector1<UInt8>
}
protocol Vector {
associatedtype Index: VectorIndex
associatedtype Element
init(elementForIndex: (Index) -> Element)
subscript(index: Index) -> Element { get set }
}
struct Vector1<Element> : Vector {
//typealias Index = VectorIndex1 // Uncomment this line to workaround bug.
var e0: Element
init(elementForIndex: (VectorIndex1) -> Element) {
e0 = elementForIndex(.i0)
}
subscript(index: Index) -> Element {
get { return e0 }
set { e0 = newValue }
}
}
extension Vector where Index == VectorIndex1 {
init(_ e0: Element) { fatalError() }
}
| apache-2.0 | 3e6ea568eaec08296b4443e8f2ce138a | 29.857143 | 89 | 0.665509 | 3.789474 | false | false | false | false |
Takanu/Pelican | Sources/Pelican/API/Types/Stickers/MaskPosition.swift | 1 | 1353 | //
// MaskPosition.swift
// Pelican
//
// Created by Takanu Kyriako on 21/12/2017.
//
import Foundation
/**
Defines a point and set of coordinate and scaling parameters to determine where and how a sticker should be placed when added to an image.
*/
public class MaskPosition: Codable {
/// The part of the face relative to which the mask should be placed.
public var point: MaskPositionPoint
/// The offset by X-axis measured in widths of the mask scaled to the face size, from left to right. For example, choosing -1.0 will place mask just to the left of the default mask position.
public var offsetX: Float
/// The offset by Y-axis measured in heights of the mask scaled to the face size, from top to bottom. For example, 1.0 will place the mask just below the default mask position.
public var offsetY: Float
/// How much the mask will be scaled by when used. Eg. 2.0 will double the scale of the mask.
public var maskScale: Float
/// Coding keys to map values when Encoding and Decoding.
enum CodingKeys: String, CodingKey {
case point
case offsetX = "x_shift"
case offsetY = "y_shift"
case maskScale = "scale"
}
public init(point: MaskPositionPoint, offsetX: Float, offsetY: Float, maskScale: Float) {
self.point = point
self.offsetX = offsetX
self.offsetY = offsetY
self.maskScale = maskScale
}
}
| mit | 5b95eb22397323554a1ec1e26e15fad3 | 31.214286 | 191 | 0.728751 | 3.811268 | false | false | false | false |
missiondata/transit | transit/transit/Dictionary+Swifter.swift | 1 | 2732 | //
// Dictionary+Swifter.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Dictionary {
func filter(_ predicate: (Element) -> Bool) -> Dictionary {
var filteredDictionary = Dictionary()
for element in self where predicate(element) {
filteredDictionary[element.key] = element.value
}
return filteredDictionary
}
var queryString: String {
var parts = [String]()
for (key, value) in self {
let query: String = "\(key)=\(value)"
parts.append(query)
}
return parts.joined(separator: "&")
}
/**
func urlEncodedQueryString(using encoding: String.Encoding) -> String {
var parts = [String]()
for (key, value) in self {
let keyString = "\(key)".urlEncodedString()
let valueString = "\(value)".urlEncodedString(keyString == "status")
let query: String = "\(keyString)=\(valueString)"
parts.append(query)
}
return parts.joined(separator: "&")
}
*/
func stringifiedDictionary() -> Dictionary<String, String> {
var dict = [String: String]()
for (key, value) in self {
dict[String(describing: key)] = String(describing: value)
}
return dict
}
}
infix operator +|
func +| <K,V>(left: Dictionary<K,V>, right: Dictionary<K,V>) -> Dictionary<K,V> {
var map = Dictionary<K,V>()
for (k, v) in left {
map[k] = v
}
for (k, v) in right {
map[k] = v
}
return map
}
| mit | 67b1d100f464651a25477be32f79216b | 31.915663 | 81 | 0.625915 | 4.350318 | false | false | false | false |
jefflovejapan/CIFilterKit | CIFilterKitTests/DistortionEffectFilterTests.swift | 1 | 4349 | //
// DistortionEffectFilterTests.swift
// CIFilterKit
//
// Created by Jeffrey Blagdon on 5/27/15.
// Copyright (c) 2015 Jeffrey Blagdon. All rights reserved.
//
import Quick
import Nimble
import CIFilterKit
class DistortionEffectFilterTests: QuickSpec {
override func spec() {
var kevinBaconImg : UIImage!
var kevinBaconCiImage: CIImage!
beforeEach {
let filePath = NSBundle(forClass: self.classForCoder).pathForResource("bacon", ofType: "jpg")!
let imgData = NSData(contentsOfFile: filePath)!
kevinBaconImg = UIImage(data: imgData)!
expect(kevinBaconImg).toNot(beNil())
kevinBaconCiImage = CIImage(CGImage: kevinBaconImg.CGImage!)
expect(kevinBaconCiImage).toNot(beNil())
}
describe("The BumpDistortion filter") {
it("should be able to filter a picture of Kevin Bacon") {
let options = BumpDistortionOptions(inputCenter:XYPosition(x: 400.0, y: 600.0), inputRadius: 300.0, inputScale: 1.0)
let aFilter = BumpDistortion(options)
expect(aFilter(kevinBaconCiImage)).toNot(beNil())
}
}
describe("The BumpDistortionLinear filter") {
it("should be able to filter a picture of Kevin Bacon") {
let options = BumpDistortionLinearOptions(inputCenter:XYPosition(x: 400.0, y: 600.0), inputRadius: 500.0, inputAngle: 1.5, inputScale:0.5)
let aFilter = BumpDistortionLinear(options)
expect(aFilter(kevinBaconCiImage)).toNot(beNil())
}
}
describe("The CirlceSplashDistortion filter") {
it("should be able to filter a picture of Kevin Bacon") {
let options = CircleSplashDistortionOptions(inputCenter:XYPosition(x: 400.0, y: 600.0), inputRadius: 500.0)
let aFilter = CircleSplashDistortion(options)
let outImg = aFilter(kevinBaconCiImage)
expect(outImg).toNot(beNil())
}
}
describe("The GlassDistortion filter") {
it("should be able to filter a picture of Kevin Bacon") {
let options = GlassDistortionOptions(inputCenter:XYPosition(x: 400.0, y: 600.0), inputScale: 200.0)
let aFilter = GlassDistortion(kevinBaconCiImage, options:options)
expect(aFilter(kevinBaconCiImage)).toNot(beNil())
}
}
describe("The HoleDistortion filter") {
it("should be able to filter a picture of Kevin Bacon") {
let options = HoleDistortionOptions(inputCenter:XYPosition(x: 400.0, y: 600.0), inputRadius:200.0)
let aFilter = HoleDistortion(options)
expect(aFilter(kevinBaconCiImage)).toNot(beNil())
}
}
describe("The LightTunnel filter") {
it("should be able to filter a picture of Kevin Bacon") {
let options = LightTunnelOptions(inputCenter:XYPosition(x: 400.0, y: 600.0),inputRotation: 0.75, inputRadius:200.0)
let aFilter = LightTunnel(options)
expect(aFilter(kevinBaconCiImage)).toNot(beNil())
}
}
describe("The PinchDistortion filter") {
it("should be able to filter a picture of Kevin Bacon") {
let options = PinchDistortionOptions(inputCenter:XYPosition(x: 400.0, y: 600.0),inputRadius:200.0, inputScale: 0.5)
let aFilter = PinchDistortion(options)
expect(aFilter(kevinBaconCiImage)).toNot(beNil())
}
}
describe("The TwirlDistortion filter") {
it("should be able to filter a picture of Kevin Bacon") {
let options = TwirlDistortionOptions()
let aFilter = TwirlDistortion(options)
expect(aFilter(kevinBaconCiImage)).toNot(beNil())
}
}
describe("The VortexDistortion filter") {
it("should be able to filter a picture of Kevin Bacon") {
let options = VortexDistortionOptions(inputCenter:XYPosition(x: 400.0, y: 600.0),inputRadius:400.0, inputAngle: 56.55)
let aFilter = VortexDistortion(options)
expect(aFilter(kevinBaconCiImage)).toNot(beNil())
}
}
}
}
| mit | ef28d7d9575aa2ab955d25f53e2effae | 47.322222 | 154 | 0.606346 | 4.327363 | false | false | false | false |
onevcat/CotEditor | CotEditor/Sources/IncompatibleCharacter.swift | 1 | 3659 | //
// IncompatibleCharacter.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2016-05-28.
//
// ---------------------------------------------------------------------------
//
// © 2004-2007 nakamuxu
// © 2014-2022 1024jp
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
struct IncompatibleCharacter: Equatable {
let character: Character
let convertedCharacter: String?
let location: Int
let lineNumber: Int
var range: NSRange { NSRange(location: self.location, length: self.character.utf16.count) }
}
// MARK: -
extension String {
/// list-up characters cannot be converted to the passed-in encoding
///
/// - Throws: `CancellationError`
func scanIncompatibleCharacters(with encoding: String.Encoding) throws -> [IncompatibleCharacter] {
guard !self.canBeConverted(to: encoding) else { return [] }
guard
let data = self.data(using: encoding, allowLossyConversion: true), // lossy conversion must always success
let convertedString = String(data: data, encoding: encoding)
else { assertionFailure(); return [] }
try Task.checkCancellation()
if self.length == convertedString.length, self.length > 10_000 {
return try self.quickIncompatibleFind(with: convertedString)
}
return try convertedString.difference(from: self).removals.lazy
.map { (change) in
guard case let .remove(offset, character, _) = change else { preconditionFailure() }
try Task.checkCancellation()
let converted: String? = String(character)
.data(using: encoding, allowLossyConversion: true)
.flatMap { String(data: $0, encoding: encoding) }
let location = self.index(self.startIndex, offsetBy: offset).utf16Offset(in: self)
return IncompatibleCharacter(character: character,
convertedCharacter: converted,
location: location,
lineNumber: self.lineNumber(at: location))
}
}
// MARK: Private Methods
private func quickIncompatibleFind(with convertedString: String) throws -> [IncompatibleCharacter] {
try zip(self, convertedString).enumerated().lazy
.filter { $1.0 != $1.1 }
.map { (offset, characters) in
let location = self.index(self.startIndex, offsetBy: offset).utf16Offset(in: self)
try Task.checkCancellation()
return IncompatibleCharacter(character: characters.0,
convertedCharacter: String(characters.1),
location: location,
lineNumber: self.lineNumber(at: location))
}
}
}
| apache-2.0 | 985d4384b19f4251edae74372137440d | 35.207921 | 119 | 0.567132 | 5.121849 | false | false | false | false |
Zig1375/MySQL | Sources/SwiftMySQL/Core/MysqlDebug.swift | 2 | 503 | import Foundation
public struct MysqlDebug : CustomStringConvertible {
public let error : String?;
public let errno : UInt32?;
public let sql : String;
init(sql : String, errno : UInt32? = nil, error : String? = nil) {
self.sql = sql;
self.errno = errno;
self.error = error;
}
public var description : String {
if (self.error != nil) {
return "\(sql) => \(self.error!) (\(self.errno!))";
}
return "\(sql)";
}
}
| mit | b66cf3f80f2e24bacd9d637e9f97b2c8 | 22.952381 | 70 | 0.544732 | 3.992063 | false | false | false | false |
Shvier/QuickPlayer-Swift | QuickPlayer/QuickPlayer/Extension/URL+Extension.swift | 1 | 805 | //
// URL+Extension.swift
// QuickPlayer
//
// Created by Shvier on 12/04/2017.
// Copyright © 2017 Shvier. All rights reserved.
//
import Foundation
let customScheme = "streaming"
let httpScheme = "http"
//let httpsScheme = "https"
extension URL {
func customSchemeURL() -> URL {
var components = URLComponents(url: self, resolvingAgainstBaseURL: false)
components?.scheme = customScheme
return (components?.url)!
}
func originalSchemeURL() -> URL {
var components = URLComponents(url: self, resolvingAgainstBaseURL: false)
// if QuickPlayerManager.sharedInstance.httpsMode {
// components?.scheme = httpsScheme
// } else {
components?.scheme = httpScheme
// }
return (components?.url)!
}
}
| mit | da9ada0220b599829d88149650231855 | 24.935484 | 81 | 0.635572 | 4.231579 | false | false | false | false |
brentsimmons/Frontier | BeforeTheRename/UserTalk/UserTalk/Compiler/Parser.swift | 1 | 4173 | //
// Parser.swift
// UserTalk
//
// Created by Brent Simmons on 5/2/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
import FrontierData
struct Parser {
var currentNode = CodeTreeNode(nodeType: moduleOp)
let tokensWithPosition: [TokenWithPosition]
var currentTokenIndex = 0
var ctLoops = 0
var insideLoop: Bool {
get {
return ctLoops > 0
}
}
var currentTokenWithPosition: TokenWithPosition {
get {
return tokensWithPosition[currentTokenIndex]
}
}
var currentToken: Token {
get {
return tokenAtIndex(currentTokenIndex)
}
}
var currentTextPosition: TextPosition {
get {
return currentTokenWithPosition.position
}
}
init(_ tokensWithPosition: [TokenWithPosition]) {
assert(!tokensWithPosition.isEmpty)
self.tokensWithPosition = tokensWithPosition
}
static func errorWithToken(_ token: TokenWithPosition, _ error: LangErrorType) -> LangError {
return LangError(error, textPosition: token.position)
}
static func illegalTokenError(_ token: TokenWithPosition) -> LangError {
return errorWithToken(token, .illegalToken)
}
func illegalTokenError() -> LangError {
return Parser.illegalTokenError(currentTokenWithPosition)
}
func tokenAtIndex(_ ix: Int) -> Token? {
if ix >= tokensWithPosition.count {
return nil
}
return tokensWithPosition[ix].token
}
func popToken() -> Token? {
if currentTokenIndex + 1 >= tokens.count {
return nil
}
currentTokenIndex = currentTokenIndex + 1
return currentToken
}
func peekNextToken() -> Token? {
return tokenAtIndex(currentTokenIndex + 1)
}
func peekNextTokenIs(_ token: Token) -> Bool {
guard let nextToken = peekNextToken() else {
return false
}
return nextToken == token
}
func peekPreviousToken() -> Token? {
if currentTokenIndex < 1 {
return nil
}
return tokenAtIndex(currentTokenIndex - 1)
}
func peekPreviousTokenIs(_ token: Token) -> Bool {
guard let previousToken = peekPreviousToken() else {
return false
}
return previousToken == token
}
func parseNextToken() throws -> Bool {
// Returns false when finished.
guard let token = popToken() else {
return false
}
do {
if currentTokenIsAtBeginningOfStatement() {
switch(token.type) {
case breakOp:
try parseBreak()
}
}
}
catch { throw error }
return true
}
func parseConstant() {
}
func parseBlock() throws -> CodeTreeNode {
}
func parseBreak() throws {
pushSimpleOperation(.breakOp)
do {
try skipEmptyParensIfNeeded() // break() is allowed in OrigFrontier
try advanceToBeginningOfNextStatement()
}
catch { throw error }
}
func parseReturn() throws {
let returnTextPosition = textPosition
let expressionNode = try parseExpressionUntilEndOfStatement()
pushUnaryOperation(.returnOp, returnTextPosition, expressionNode)
}
func parseExpressionUntilEndOfStatement() throws -> CodeTreeNode {
guard let token = popToken() else {
return
}
}
func currentTokenIsAtBeginningOfStatement() {
if currentTokenIndex < 1 {
return true
}
let previousToken = peekPreviousToken()!
return previousToken.isEndOfStatement()
}
func skipEmptyParensIfNeeded() throws {
if !peekNextTokenIs(.leftParenToken) {
return
}
popToken()
if !peekNextTokenIs(.rightParenToken) {
throw illegalTokenError()
}
popToken()
}
func advanceToEndOfStatement() throws {
guard let token = popToken() else {
return
}
if token != .semicolonToken {
throw illegalTokenError()
}
}
func pushUnaryOperation(_ operation: CodeTreeNodeType, _ textPosition: TextPosition, _ expressionNode: CodeTreeNode) {
let node = UnaryOperationNode(.returnOp, textPosition, expressionNode)
push(node)
}
func pushSimpleOperation(_ operation: CodeTreeNodeType) {
let operationNode = SimpleOperationNode(operation, currentTextPosition)
pushNode(operationNode)
}
func push(_ node: CodeTreeNode) {
currentNode.link = node
node.prevLink = currentNode
currentNode = node
}
}
private extension Token {
func isEndOfStatement() -> Bool {
return self == .semicolonToken
}
}
| gpl-2.0 | ccd201b86a4faa8536a0207d66aa5904 | 17.218341 | 119 | 0.707814 | 3.685512 | false | false | false | false |
mastahyeti/SoftU2FTool | SoftU2FTool/Counter.swift | 2 | 2574 | //
// Counter.swift
// SoftU2F
//
// Created by Benjamin P Toews on 3/12/18.
//
import Foundation
class Counter {
private static let service = "Soft U2F"
private static let serviceLen = UInt32(service.utf8.count)
private static let account = "counter"
private static let accountLen = UInt32(account.utf8.count)
private static let mtx = Mutex()
static var next: UInt32 {
mtx.lock()
defer { mtx.unlock() }
let c = current ?? 0
current = c + 1
return c
}
// assumes mtx is already locked
static var current: UInt32? {
get {
var valLen: UInt32 = 0
var val: UnsafeMutableRawPointer? = nil
let err = SecKeychainFindGenericPassword(nil, serviceLen, service, accountLen, account, &valLen, &val, nil)
if err != errSecSuccess {
if err != errSecItemNotFound {
print("Error from keychain: \(err)")
}
return nil
}
if val == nil { return nil }
defer { SecKeychainItemFreeContent(nil, val) }
guard let strVal = NSString(bytes: val!, length: Int(valLen), encoding: String.Encoding.utf8.rawValue) as String? else {
return nil
}
return UInt32(strVal)
}
set {
let err: OSStatus
if let val: UInt32 = newValue {
let strVal = String(val)
let strValLen = UInt32(strVal.utf8.count)
if let it = item {
err = SecKeychainItemModifyContent(it, nil, strValLen, strVal)
} else {
err = SecKeychainAddGenericPassword(nil, serviceLen, service, accountLen, account, strValLen, strVal, nil)
}
} else {
if let it = item {
err = SecKeychainItemDelete(it)
} else {
return
}
}
if err != errSecSuccess {
print("Error from keychain: \(err)")
}
}
}
// assumes mtx is already locked
private static var item: SecKeychainItem? {
var it: SecKeychainItem? = nil
let err = SecKeychainFindGenericPassword(nil, serviceLen, service, accountLen, account, nil, nil, &it)
if err != errSecSuccess {
if err != errSecItemNotFound {
print("Error from keychain: \(err)")
}
return nil
}
return it
}
}
| mit | 1b08d85b47c9b8682771482be0958d14 | 28.25 | 132 | 0.520202 | 4.547703 | false | false | false | false |
mohsinalimat/MusicPlayerTransition | MusicPlayerTransition/MusicPlayerTransition/ARNTransitionAnimator.swift | 1 | 16388 | //
// ARNTransitionAnimator.swift
// ARNTransitionAnimator
//
// Created by xxxAIRINxxx on 2015/02/26.
// Copyright (c) 2015 xxxAIRINxxx. All rights reserved.
//
import UIKit
import UIKit.UIGestureRecognizerSubclass
public enum ARNTransitionAnimatorDirection: Int {
case Top
case Bottom
case Left
case Right
}
public enum ARNTransitionAnimatorOperation: Int {
case None
case Push
case Pop
case Present
case Dismiss
}
public class ARNTransitionAnimator: UIPercentDrivenInteractiveTransition {
// animation setting
public var usingSpringWithDamping : CGFloat = 1.0
public var transitionDuration : NSTimeInterval = 0.5
public var initialSpringVelocity : CGFloat = 0.1
// interactive gesture
public weak var gestureTargetView : UIView? {
willSet {
self.unregisterPanGesture()
}
didSet {
self.registerPanGesture()
}
}
public var panCompletionThreshold : CGFloat = 100.0
public var direction : ARNTransitionAnimatorDirection = .Bottom
public var contentScrollView : UIScrollView? {
didSet {
if let _contentScrollView = self.contentScrollView {
self.tmpBounces = _contentScrollView.bounces
}
}
}
public var interactiveType : ARNTransitionAnimatorOperation = .None {
didSet {
if self.interactiveType == .None {
self.unregisterPanGesture()
} else {
self.registerPanGesture()
}
}
}
// handlers
public var presentationBeforeHandler : ((containerView: UIView, transitionContext: UIViewControllerContextTransitioning) ->())?
public var presentationAnimationHandler : ((containerView: UIView, percentComplete: CGFloat) ->())?
public var presentationCancelAnimationHandler : ((containerView: UIView) ->())?
public var presentationCompletionHandler : ((containerView: UIView, completeTransition: Bool) ->())?
public var dismissalBeforeHandler : ((containerView: UIView, transitionContext: UIViewControllerContextTransitioning) ->())?
public var dismissalAnimationHandler : ((containerView: UIView, percentComplete: CGFloat) ->())?
public var dismissalCancelAnimationHandler : ((containerView: UIView) ->())?
public var dismissalCompletionHandler : ((containerView: UIView, completeTransition: Bool) ->())?
// private
private weak var fromVC : UIViewController!
private weak var toVC : UIViewController!
private var operationType : ARNTransitionAnimatorOperation
private var isPresenting : Bool = true
private var gesture : UIPanGestureRecognizer?
private var transitionContext : UIViewControllerContextTransitioning?
private var panLocationStart : CGFloat = 0.0
private var isTransitioning : Bool = false
private var tmpBounces: Bool = true
deinit {
self.unregisterPanGesture()
}
// MARK: Constructor
public init(operationType: ARNTransitionAnimatorOperation, fromVC: UIViewController, toVC: UIViewController) {
self.operationType = operationType
self.fromVC = fromVC
self.toVC = toVC
switch (self.operationType) {
case .Push, .Present:
self.isPresenting = true
case .Pop, .Dismiss:
self.isPresenting = false
case .None:
break
}
}
// MARK: Private Methods
private func registerPanGesture() {
self.unregisterPanGesture()
self.gesture = UIPanGestureRecognizer(target: self, action: "handlePan:")
self.gesture!.delegate = self
self.gesture!.maximumNumberOfTouches = 1
if let _gestureTargetView = self.gestureTargetView {
_gestureTargetView.addGestureRecognizer(self.gesture!)
} else {
switch (self.interactiveType) {
case .Push, .Present:
self.fromVC.view.addGestureRecognizer(self.gesture!)
case .Pop, .Dismiss:
self.toVC.view.addGestureRecognizer(self.gesture!)
case .None:
break
}
}
}
private func unregisterPanGesture() {
if let _gesture = self.gesture {
if let _view = _gesture.view {
_view.removeGestureRecognizer(_gesture)
}
_gesture.delegate = nil
}
self.gesture = nil
}
private func fireBeforeHandler(containerView: UIView, transitionContext: UIViewControllerContextTransitioning) {
if self.isPresenting {
self.presentationBeforeHandler?(containerView: containerView, transitionContext: transitionContext)
} else {
self.dismissalBeforeHandler?(containerView: containerView, transitionContext: transitionContext)
}
}
private func fireAnimationHandler(containerView: UIView, percentComplete: CGFloat) {
if self.isPresenting {
self.presentationAnimationHandler?(containerView: containerView, percentComplete: percentComplete)
} else {
self.dismissalAnimationHandler?(containerView: containerView, percentComplete: percentComplete)
}
}
private func fireCancelAnimationHandler(containerView: UIView) {
if self.isPresenting {
self.presentationCancelAnimationHandler?(containerView: containerView)
} else {
self.dismissalCancelAnimationHandler?(containerView: containerView)
}
}
private func fireCompletionHandler(containerView: UIView, completeTransition: Bool) {
if self.isPresenting {
self.presentationCompletionHandler?(containerView: containerView, completeTransition: completeTransition)
} else {
self.dismissalCompletionHandler?(containerView: containerView, completeTransition: completeTransition)
}
}
private func animateWithDuration(duration: NSTimeInterval, containerView: UIView, completeTransition: Bool, completion: (() -> Void)?) {
UIView.animateWithDuration(
duration,
delay: 0,
usingSpringWithDamping: self.usingSpringWithDamping,
initialSpringVelocity: self.initialSpringVelocity,
options: .CurveEaseOut,
animations: {
if completeTransition {
self.fireAnimationHandler(containerView, percentComplete: 1.0)
} else {
self.fireCancelAnimationHandler(containerView)
}
}, completion: { finished in
self.fireCompletionHandler(containerView, completeTransition: completeTransition)
completion?()
})
}
// MARK: Gesture
func handlePan(recognizer: UIPanGestureRecognizer) {
var window : UIWindow? = nil
switch (self.interactiveType) {
case .Push, .Present:
window = self.fromVC.view.window
case .Pop, .Dismiss:
window = self.toVC.view.window
case .None:
return
}
var location = recognizer.locationInView(window)
location = CGPointApplyAffineTransform(location, CGAffineTransformInvert(recognizer.view!.transform))
var velocity = recognizer .velocityInView(window)
velocity = CGPointApplyAffineTransform(velocity, CGAffineTransformInvert(recognizer.view!.transform))
if recognizer.state == .Began {
switch (self.direction) {
case .Top, .Bottom:
self.panLocationStart = location.y
case .Left, .Right:
self.panLocationStart = location.x
}
if let _contentScrollView = self.contentScrollView {
if _contentScrollView.contentOffset.y <= 0.0 {
self.startGestureTransition()
_contentScrollView.bounces = false
}
} else {
self.startGestureTransition()
}
} else if recognizer.state == .Changed {
var bounds = CGRectZero
switch (self.interactiveType) {
case .Push, .Present:
bounds = self.fromVC.view.bounds
case .Pop, .Dismiss:
bounds = self.toVC.view.bounds
case .None:
break
}
var animationRatio: CGFloat = 0.0
switch self.direction {
case .Top:
animationRatio = (self.panLocationStart - location.y) / CGRectGetHeight(bounds)
case .Bottom:
animationRatio = (location.y - self.panLocationStart) / CGRectGetHeight(bounds)
case .Left:
animationRatio = (self.panLocationStart - location.x) / CGRectGetWidth(bounds)
case .Right:
animationRatio = (location.x - self.panLocationStart) / CGRectGetWidth(bounds)
}
if let _contentScrollView = self.contentScrollView {
if self.isTransitioning == false && _contentScrollView.contentOffset.y <= 0 {
self.startGestureTransition()
self.contentScrollView!.bounces = false
} else {
self.updateInteractiveTransition(animationRatio)
}
} else {
self.updateInteractiveTransition(animationRatio)
}
} else if recognizer.state == .Ended {
var velocityForSelectedDirection: CGFloat = 0.0
switch (self.direction) {
case .Top, .Bottom:
velocityForSelectedDirection = velocity.y
case .Left, .Right:
velocityForSelectedDirection = velocity.x
}
if velocityForSelectedDirection > self.panCompletionThreshold && (self.direction == .Right || self.direction == .Bottom) {
self.finishInteractiveTransition()
} else if velocityForSelectedDirection < -self.panCompletionThreshold && (self.direction == .Left || self.direction == .Top) {
self.finishInteractiveTransition()
} else {
self.cancelInteractiveTransition()
}
self.resetGestureTransitionSetting()
} else {
self.resetGestureTransitionSetting()
self.cancelInteractiveTransition()
}
}
func startGestureTransition() {
if self.isTransitioning == false {
self.isTransitioning = true
switch (self.interactiveType) {
case .Push:
self.fromVC.navigationController?.pushViewController(self.toVC, animated: true)
case .Present:
self.fromVC.presentViewController(self.toVC, animated: true, completion: nil)
case .Pop:
self.toVC.navigationController?.popViewControllerAnimated(true)
case .Dismiss:
self.toVC.dismissViewControllerAnimated(true, completion: nil)
case .None:
break
}
}
}
func resetGestureTransitionSetting() {
self.isTransitioning = false
if let _contentScrollView = self.contentScrollView {
_contentScrollView.bounces = self.tmpBounces
}
}
}
// MARK: UIViewControllerAnimatedTransitioning
extension ARNTransitionAnimator: UIViewControllerAnimatedTransitioning {
public func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
return self.transitionDuration
}
public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView()
self.transitionContext = transitionContext
self.fireBeforeHandler(containerView, transitionContext: transitionContext)
self.animateWithDuration(
self.transitionDuration(transitionContext),
containerView: containerView,
completeTransition: true) {
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
}
}
public func animationEnded(transitionCompleted: Bool) {
self.transitionContext = nil
}
}
// MARK: UIViewControllerTransitioningDelegate
extension ARNTransitionAnimator: UIViewControllerTransitioningDelegate {
public func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.isPresenting = true
return self
}
public func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.isPresenting = false
return self
}
public func interactionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if self.gesture != nil && (self.interactiveType == .Push || self.interactiveType == .Present) {
self.isPresenting = true
return self
}
return nil
}
public func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if self.gesture != nil && (self.interactiveType == .Pop || self.interactiveType == .Dismiss) {
self.isPresenting = false
return self
}
return nil
}
}
// MARK: UIViewControllerInteractiveTransitioning
extension ARNTransitionAnimator: UIViewControllerInteractiveTransitioning {
public override func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!
let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!
let containerView = transitionContext.containerView()
self.transitionContext = transitionContext
self.fireBeforeHandler(containerView, transitionContext: transitionContext)
}
}
// MARK: UIPercentDrivenInteractiveTransition
extension ARNTransitionAnimator {
public override func updateInteractiveTransition(percentComplete: CGFloat) {
if let transitionContext = self.transitionContext {
let containerView = transitionContext.containerView()
self.fireAnimationHandler(containerView, percentComplete: percentComplete)
}
}
public override func finishInteractiveTransition() {
if let transitionContext = self.transitionContext {
let containerView = transitionContext.containerView()
self.animateWithDuration(
self.transitionDuration(transitionContext),
containerView: containerView,
completeTransition: true) {
transitionContext.completeTransition(true)
}
}
}
public override func cancelInteractiveTransition() {
if let transitionContext = self.transitionContext {
let containerView = transitionContext.containerView()
self.animateWithDuration(
self.transitionDuration(transitionContext),
containerView: containerView,
completeTransition: false) {
transitionContext.completeTransition(false)
}
}
}
}
// MARK: UIGestureRecognizerDelegate
extension ARNTransitionAnimator: UIGestureRecognizerDelegate {
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return self.contentScrollView != nil ? true : false
}
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailByGestureRecognizer
otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
}
| mit | 4790331304dd8cacab39f6f04d564560 | 36.935185 | 224 | 0.643031 | 6.144732 | false | false | false | false |
castillejoale/Bluefruit_LE_Connect_v2_Minimized_UART | bluefruitconnect/Platform/iOS/Controllers/Dfu/DfuDialogViewController.swift | 1 | 1638 | //
// DfuDialogViewController.swift
// Bluefruit Connect
//
// Created by Antonio García on 09/02/16.
// Copyright © 2016 Adafruit. All rights reserved.
//
import UIKit
protocol DfuDialogViewControllerDelegate: class {
func onUpdateDialogCancel()
}
class DfuDialogViewController: UIViewController {
@IBOutlet weak var progressLabel: UILabel!
@IBOutlet weak var progressIndicator: UIProgressView!
@IBOutlet weak var progressPercentageLabel: UILabel!
@IBOutlet weak var backgroundView: UIView!
@IBOutlet weak var cancelButton: UIButton!
weak var delegate : DfuDialogViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
cancelButton.hidden = true
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// Fade-in background
backgroundView.alpha = 0
UIView.animateWithDuration(0.5, animations: { [unowned self] () -> Void in
self.backgroundView.alpha = 1
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setProgressText(text : String) {
progressLabel.text = text
}
func setProgress(value : Double) {
cancelButton.hidden = value <= 0
progressIndicator.progress = Float(value/100.0)
progressPercentageLabel.text = String(format: "%1.0f%%", value);
}
@IBAction func onClickCancel(sender: AnyObject) {
delegate?.onUpdateDialogCancel()
}
}
| mit | e1c5d9b78dcb824f5b17308c35bbda47 | 25.819672 | 82 | 0.655868 | 4.972644 | false | false | false | false |
princedev/Template_swift | Template/AppDelegate.swift | 1 | 7585 | //
// AppDelegate.swift
// Template
//
// Created by Weasley Qi on 16/7/12.
// Copyright © 2016年 Weasley Qi. All rights reserved.
//
import UIKit
import Alamofire
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UIAlertViewDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
//iOS 8+ 注册推送
let notificationTypes: UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]
let pushNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
application.registerUserNotificationSettings(pushNotificationSettings)
application.registerForRemoteNotifications()
//iOS 9+ 配置3DTouch
if #available (iOS 9.1,*){
configShortCutItems()
}
//检查更新
checkForUpdate()
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:.
}
//注册推送成功获取设备号
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let token : String = deviceToken.description.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "<>"))
//获取到token
MTLog("token==\(token)")
}
//注册推送失败
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
MTLog(error.localizedDescription)
}
//收到推送消息时调用该方法进行处理
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
MTLog("userInfo==\(userInfo)")
}
//检查更新
func checkForUpdate(){
Alamofire.request(.GET, checkVersionUrl)
.response { (request, response, data, error) in
if(data!.length == 0 || error != nil){
MTLog("connError==\(error!.localizedDescription)")
}else{
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject] {
MTLog(json)
if let d = data{
let jsonstring = NSString(data: d, encoding: NSUTF8StringEncoding)! as String
dispatch_async(dispatch_get_main_queue(), { () -> Void in
MTLog("jsonstring==\(jsonstring)")
//TODO 从json中获取服务器端版本号,以下ver需要赋值
let ver = "1.2"
//compare versions
if ver.compare(mainVersion) == NSComparisonResult.OrderedDescending {
let alertView = UIAlertView.init(title: "Update", message: "New version for update", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "OK")
alertView.show()
}
})
}
}
} catch let err as NSError {
MTLog(err.localizedDescription)
}
}
}
}
func alertView(alertView:UIAlertView, clickedButtonAtIndex buttonIndex: Int){
if(buttonIndex == 1){
UIApplication.sharedApplication().openURL(NSURL(string: downloadUrl)!)
}
else {}
}
//检查更新end
//配置3DTouch
@available(iOS 9.1, *)
func configShortCutItems(){
var shortcutItemArray = [UIApplicationShortcutItem]()
//TODO 自定义菜单样式 icon:设置图标 userInfo:参数字典
let icon1 = UIApplicationShortcutIcon.init(type: UIApplicationShortcutIconType.Favorite)
let userInfo1 : Dictionary<String,String> = ["key1":"value1"];
let icon2 = UIApplicationShortcutIcon.init(type: UIApplicationShortcutIconType.Share)
let userInfo2 : Dictionary<String,String> = ["key2":"value2"];
let ShortcutItem1 = UIApplicationShortcutItem.init(type: "Item1", localizedTitle: "Subject1", localizedSubtitle: "SubTitle1", icon: icon1, userInfo: userInfo1)
let ShortcutItem2 = UIApplicationShortcutItem.init(type: "Item2", localizedTitle: "Subject2", localizedSubtitle: "SubTitle2", icon: icon2, userInfo: userInfo2)
shortcutItemArray.append(ShortcutItem1)
shortcutItemArray.append(ShortcutItem2)
UIApplication.sharedApplication().shortcutItems = shortcutItemArray
}
//Action For ShortcutItem
@available(iOS 9, *)
func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) {
switch shortcutItem.type {
case "Item1":
MTLog("shortcutItem: \(shortcutItem.userInfo)")
//TODO 根据shortcutItem的类型 添加处理事件
case "Item2":
MTLog("shortcutItem: \(shortcutItem.userInfo)")
//TODO 调用分享视图
let items = ["3D Touch Share"]
let activityVC = UIActivityViewController(
activityItems: items,
applicationActivities: nil)
self.window?.rootViewController?.presentViewController(activityVC, animated: true, completion: { () -> Void in
})
default:
break
}
}
//配置3DTouch end
}
| mit | c0c36e3a78e1cd24ff3a4caae34625e8 | 44.190184 | 285 | 0.629378 | 5.701238 | false | false | false | false |
anilkumarbp/ringcentral-swift-v2 | RingCentral/Subscription/Subscription.swift | 1 | 11333 | //
// Subscription.swift
// RingCentral
//
// Created by Anil Kumar BP on 2/10/16.
// Copyright © 2016 Anil Kumar BP. All rights reserved.
//
import Foundation
import PubNub
import CryptoSwift
public class Subscription: NSObject, PNObjectEventListener {
public static var EVENT_NOTIFICATION: String = "notification"
public static var EVENT_REMOVE_SUCCESS: String = "removeSuccess"
public static var EVENT_RENEW_SUCCESS: String = "removeError"
public static var EVENT_RENEW_ERROR: String = "renewError"
public static var EVENT_SUBSCRIBE_SUCCESS: String = "subscribeSuccess"
public static var EVENT_SUBSCRIBE_ERROR: String = "subscribeError"
/// Fields of subscription
let platform: Platform!
var pubnub: PubNub?
var eventFilters: [String] = []
var _keepPolling: Bool = false
var subscription: ISubscription?
var function: ((arg: String) -> Void) = {(arg) in }
/// Initializes a subscription with Platform
///
/// - parameter platform: Authorized platform
public init(platform: Platform) {
self.platform = platform
}
/// Structure holding information about how PubNub is delivered
struct IDeliveryMode {
var transportType: String = "PubNub"
var encryption: Bool = false
var address: String = ""
var subscriberKey: String = ""
var secretKey: String?
var encryptionKey: String = ""
}
/// Structure holding information about the details of PubNub
struct ISubscription {
var eventFilters: [String] = []
var expirationTime: String = ""
var expiresIn: NSNumber = 0
var deliveryMode: IDeliveryMode = IDeliveryMode()
var id: String = ""
var creationTime: String = ""
var status: String = ""
var uri: String = ""
}
/// Returns PubNub object
///
/// - returns: PubNub object
public func getPubNub() -> PubNub? {
return pubnub
}
/// Returns the platform
///
/// - returns: Platform
public func getPlatform() -> Platform {
return platform
}
/// Adds event for PubNub
///
/// - parameter events: List of events to add
/// - returns: Subscription
public func addEvents(events: [String]) -> Subscription {
for event in events {
self.eventFilters.append(event)
}
return self
}
/// Sets events for PubNub (deletes all previous ones)
///
/// - parameter events: List of events to set
/// - returns: Subscription
public func setevents(events: [String]) -> Subscription {
self.eventFilters = events
return self
}
/// Returns all the event filters
///
/// - returns: [String] of all the event filters
private func getFullEventFilters() -> [String] {
return self.eventFilters
}
/// Registers for a new subscription or renews an old one
///
/// - parameter options: List of options for PubNub
public func register(options: [String: AnyObject] = [String: AnyObject](), completion: (apiresponse: ApiResponse?,exception: NSException?) -> Void) {
if (isSubscribed()) {
return renew(options) {
(r,e) in
completion(apiresponse: r,exception: e)
}
} else {
return subscribe(options) {
(r,e) in
completion(apiresponse: r,exception: e)
}
}
}
/// Renews the subscription
///
/// - parameter options: List of options for PubNub
public func renew(options: [String: AnyObject], completion: (apiresponse: ApiResponse?,exception: NSException?) -> Void) {
// include PUT instead of the apiCall
platform.put("/subscription/" + subscription!.id,
body: [
"eventFilters": getFullEventFilters()
]) {
(apiresponse,exception) in
let dictionary = apiresponse!.getDict()
if let _ = dictionary["errorCode"] {
self.subscribe(options){
(r,e) in
completion(apiresponse: r,exception: e)
}
} else {
self.subscription!.expiresIn = dictionary["expiresIn"] as! NSNumber
self.subscription!.expirationTime = dictionary["expirationTime"] as! String
}
}
}
/// Subscribes to a channel with given events
///
/// - parameter options: Options for PubNub
public func subscribe(options: [String: AnyObject], completion: (apiresponse: ApiResponse?,exception: NSException?) -> Void) {
// Create Subscription
platform.post("/subscription",
body: [
"eventFilters": getFullEventFilters(),
"deliveryMode": [
"transportType": "PubNub",
"encryption": "false"
]
]) {
(apiresponse,exception) in
let dictionary = apiresponse!.getDict()
print("The subscription dictionary is :", dictionary, terminator: "")
var sub = ISubscription()
sub.eventFilters = dictionary["eventFilters"] as! [String]
self.eventFilters = dictionary["eventFilters"] as! [String]
sub.expirationTime = dictionary["expirationTime"] as! String
sub.expiresIn = dictionary["expiresIn"] as! NSNumber
sub.id = dictionary["id"] as! String
sub.creationTime = dictionary["creationTime"] as! String
sub.status = dictionary["status"] as! String
sub.uri = dictionary["uri"] as! String
self.subscription = sub
var del = IDeliveryMode()
let dictDelivery = dictionary["deliveryMode"] as! NSDictionary
del.transportType = dictDelivery["transportType"] as! String
del.encryption = dictDelivery["encryption"] as! Bool
del.address = dictDelivery["address"] as! String
del.subscriberKey = dictDelivery["subscriberKey"] as! String
del.secretKey = dictDelivery["secretKey"] as? String
del.encryptionKey = dictDelivery["encryptionKey"] as! String
self.subscription!.deliveryMode = del
self.subscribeAtPubnub()
}
}
/// Sets a method that will run after every PubNub callback
///
/// - parameter functionHolder: Function to be ran after every PubNub callback
public func setMethod(functionHolder: ((arg: String) -> Void)) {
self.function = functionHolder
}
/// Checks if currently subscribed
///
/// - returns: Bool of if currently subscribed
public func isSubscribed() -> Bool {
if let sub = self.subscription {
let dil = sub.deliveryMode
return dil.subscriberKey != "" && dil.address != ""
}
return false
}
/// Emits events
public func emit(event: String) -> AnyObject {
return ""
}
/// Updates the subscription with the one passed in
///
/// - parameter subscription: New subscription passed in
private func updateSubscription(subscription: ISubscription) {
self.subscription = subscription
}
/// Unsubscribes from subscription
private func unsubscribe() {
if let channel = subscription?.deliveryMode.address {
pubnub?.unsubscribeFromChannelGroups([channel], withPresence: true)
}
if let sub = subscription {
// delete the subscription
platform.delete("/subscription/" + sub.id) {
(transaction) in
self.subscription = nil
self.eventFilters = []
self.pubnub = nil
}
}
}
/// Subscribes to a channel given the settings
private func subscribeAtPubnub() {
let config = PNConfiguration( publishKey: "", subscribeKey: subscription!.deliveryMode.subscriberKey)
self.pubnub = PubNub.clientWithConfiguration(config)
self.pubnub?.addListener(self)
self.pubnub?.subscribeToChannels([subscription!.deliveryMode.address], withPresence: true)
}
/// Notifies
private func notify() {
}
/// Method that PubNub calls when receiving a message back from Subscription
///
/// - parameter client: The client of the receiver
/// - parameter message: Message being received back
public func client(client: PubNub!, didReceiveMessage message: PNMessageResult!) {
let base64Message = message.data.message as! String
let base64Key = self.subscription!.deliveryMode.encryptionKey
_ = [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00] as [UInt8]
_ = AES.randomIV(AES.blockSize)
do {
let decrypted = try AES(key: base64ToByteArray(base64Key), iv: [0x00], blockMode: .ECB).decrypt(base64ToByteArray(base64Message), padding: PKCS7())
let endMarker = NSData(bytes: (decrypted as [UInt8]!), length: decrypted.count)
if let str: String = NSString(data: endMarker, encoding: NSUTF8StringEncoding) as? String {
self.function(arg: str)
} else {
NSException(name: "Error", reason: "Error", userInfo: nil).raise()
}
} catch {
print("error")
}
}
/// Converts base64 to byte array
///
/// - parameter base64String: base64 String to be converted
/// - returns: [UInt8] byte array
private func base64ToByteArray(base64String: String) -> [UInt8] {
let nsdata: NSData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0))!
var bytes = [UInt8](count: nsdata.length, repeatedValue: 0)
nsdata.getBytes(&bytes, length: nsdata.length)
return bytes
}
/// Converts byte array to base64
///
/// - parameter bytes: byte array to be converted
/// - returns: String of the base64
private func byteArrayToBase64(bytes: [UInt8]) -> String {
let nsdata = NSData(bytes: bytes, length: bytes.count)
let base64Encoded = nsdata.base64EncodedStringWithOptions([]);
return base64Encoded;
}
/// Converts a dictionary represented as a String into a NSDictionary
///
/// - parameter string: Dictionary represented as a String
/// - returns: NSDictionary of the String representation of a Dictionary
private func stringToDict(string: String) -> NSDictionary {
let data: NSData = string.dataUsingEncoding(NSUTF8StringEncoding)!
return (try! NSJSONSerialization.JSONObjectWithData(data, options: [])) as! NSDictionary
}
}
| mit | 097857fbf0a2175d347bf93afe54dd83 | 36.276316 | 159 | 0.579333 | 4.920538 | false | false | false | false |
bazelbuild/tulsi | src/TulsiGenerator/CommandLineSplitter.swift | 2 | 1880 | // Copyright 2016 The Tulsi 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.
import Foundation
/// Splits a string containing commandline arguments into an array of strings suitable for use by
/// Process.
class CommandLineSplitter {
let scriptPath: String
init() {
scriptPath = Bundle(for: type(of: self)).path(forResource: "command_line_splitter",
ofType: "sh")!
}
/// WARNING: This method utilizes a shell instance to evaluate the commandline and may have side
/// effects.
func splitCommandLine(_ commandLine: String) -> [String]? {
if commandLine.isEmpty { return [] }
var splitCommands: [String]? = nil
let semaphore = DispatchSemaphore(value: 0)
let process = ProcessRunner.createProcess(scriptPath, arguments: [commandLine]) {
completionInfo in
defer { semaphore.signal() }
guard completionInfo.terminationStatus == 0,
let stdout = NSString(data: completionInfo.stdout, encoding: String.Encoding.utf8.rawValue) else {
return
}
let split = stdout.components(separatedBy: CharacterSet.newlines)
splitCommands = [String](split.dropLast())
}
process.launch()
_ = semaphore.wait(timeout: DispatchTime.distantFuture)
return splitCommands
}
}
| apache-2.0 | 1a2061c4a79c708f4cf3b8a389561ceb | 35.862745 | 110 | 0.681915 | 4.653465 | false | false | false | false |
russbishop/swift | stdlib/public/core/StringLegacy.swift | 1 | 12601 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
extension String {
/// Creates a string representing the given character repeated the specified
/// number of times.
///
/// For example, use this initializer to create a string with ten `"0"`
/// characters in a row.
///
/// let zeroes = String("0" as Character, count: 10)
/// print(zeroes)
/// // Prints "0000000000"
public init(repeating repeatedValue: Character, count: Int) {
let s = String(repeatedValue)
self = String(_storage: _StringBuffer(
capacity: s._core.count * count,
initialSize: 0,
elementWidth: s._core.elementWidth))
for _ in 0..<count {
self += s
}
}
/// Creates a string representing the given Unicode scalar repeated the
/// specified number of times.
///
/// For example, use this initializer to create a string with ten `"0"`
/// scalars in a row.
///
/// let zeroes = String("0" as UnicodeScalar, count: 10)
/// print(zeroes)
/// // Prints "0000000000"
public init(repeating repeatedValue: UnicodeScalar, count: Int) {
self = String._fromWellFormedCodeUnitSequence(
UTF32.self,
input: repeatElement(repeatedValue.value, count: count))
}
public var _lines : [String] {
return _split(separator: "\n")
}
public func _split(separator: UnicodeScalar) -> [String] {
let scalarSlices = unicodeScalars.split { $0 == separator }
return scalarSlices.map { String($0) }
}
/// A Boolean value indicating whether a string has no characters.
public var isEmpty: Bool {
return _core.count == 0
}
}
extension String {
public init(_ _c: UnicodeScalar) {
self = String(repeating: _c, count: 1)
}
}
#if _runtime(_ObjC)
/// Determines if `theString` starts with `prefix` comparing the strings under
/// canonical equivalence.
@_silgen_name("swift_stdlib_NSStringHasPrefixNFD")
func _stdlib_NSStringHasPrefixNFD(_ theString: AnyObject, _ prefix: AnyObject) -> Bool
@_silgen_name("swift_stdlib_NSStringHasPrefixNFDPointer")
func _stdlib_NSStringHasPrefixNFDPointer(_ theString: OpaquePointer, _ prefix: OpaquePointer) -> Bool
/// Determines if `theString` ends with `suffix` comparing the strings under
/// canonical equivalence.
@_silgen_name("swift_stdlib_NSStringHasSuffixNFD")
func _stdlib_NSStringHasSuffixNFD(_ theString: AnyObject, _ suffix: AnyObject) -> Bool
@_silgen_name("swift_stdlib_NSStringHasSuffixNFDPointer")
func _stdlib_NSStringHasSuffixNFDPointer(_ theString: OpaquePointer, _ suffix: OpaquePointer) -> Bool
extension String {
/// Returns a Boolean value indicating whether the string begins with the
/// specified prefix.
///
/// The comparison is both case sensitive and Unicode safe. The
/// case-sensitive comparison will only match strings whose corresponding
/// characters have the same case.
///
/// let cafe = "Café du Monde"
///
/// // Case sensitive
/// print(cafe.hasPrefix("café"))
/// // Prints "false"
///
/// The Unicode-safe comparison matches Unicode scalar values rather than the
/// code points used to compose them. The example below uses two strings
/// with different forms of the `"é"` character---the first uses the composed
/// form and the second uses the decomposed form.
///
/// // Unicode safe
/// let composedCafe = "Café"
/// let decomposedCafe = "Cafe\u{0301}"
///
/// print(cafe.hasPrefix(composedCafe))
/// // Prints "true"
/// print(cafe.hasPrefix(decomposedCafe))
/// // Prints "true"
///
/// - Parameter prefix: A possible prefix to test against this string.
/// Passing an empty string (`""`) as `prefix` always results in `false`.
/// - Returns: `true` if the string begins with `prefix`, otherwise, `false`.
public func hasPrefix(_ prefix: String) -> Bool {
let selfCore = self._core
let prefixCore = prefix._core
if selfCore.hasContiguousStorage && prefixCore.hasContiguousStorage {
if selfCore.isASCII && prefixCore.isASCII {
// Prefix longer than self.
let prefixCount = prefixCore.count
if prefixCount > selfCore.count || prefixCount == 0 {
return false
}
return Int(_swift_stdlib_memcmp(
selfCore.startASCII, prefixCore.startASCII, prefixCount)) == 0
}
let lhsStr = _NSContiguousString(selfCore)
let rhsStr = _NSContiguousString(prefixCore)
return lhsStr._unsafeWithNotEscapedSelfPointerPair(rhsStr) {
return _stdlib_NSStringHasPrefixNFDPointer($0, $1)
}
}
return _stdlib_NSStringHasPrefixNFD(
self._bridgeToObjectiveCImpl(), prefix._bridgeToObjectiveCImpl())
}
/// Returns a Boolean value indicating whether the string ends with the
/// specified suffix.
///
/// The comparison is both case sensitive and Unicode safe. The
/// case-sensitive comparison will only match strings whose corresponding
/// characters have the same case.
///
/// let plans = "Let's meet at the café"
///
/// // Case sensitive
/// print(plans.hasSuffix("Café"))
/// // Prints "false"
///
/// The Unicode-safe comparison matches Unicode scalar values rather than the
/// code points used to compose them. The example below uses two strings
/// with different forms of the `"é"` character---the first uses the composed
/// form and the second uses the decomposed form.
///
/// // Unicode safe
/// let composedCafe = "café"
/// let decomposedCafe = "cafe\u{0301}"
///
/// print(plans.hasSuffix(composedCafe))
/// // Prints "true"
/// print(plans.hasSuffix(decomposedCafe))
/// // Prints "true"
///
/// - Parameter suffix: A possible suffix to test against this string.
/// Passing an empty string (`""`) as `suffix` always results in `false`.
/// - Returns: `true` if the string ends with `suffix`, otherwise, `false`.
public func hasSuffix(_ suffix: String) -> Bool {
let selfCore = self._core
let suffixCore = suffix._core
if selfCore.hasContiguousStorage && suffixCore.hasContiguousStorage {
if selfCore.isASCII && suffixCore.isASCII {
// Prefix longer than self.
let suffixCount = suffixCore.count
let selfCount = selfCore.count
if suffixCount > selfCount || suffixCount == 0 {
return false
}
return Int(_swift_stdlib_memcmp(
selfCore.startASCII + (selfCount - suffixCount),
suffixCore.startASCII, suffixCount)) == 0
}
let lhsStr = _NSContiguousString(selfCore)
let rhsStr = _NSContiguousString(suffixCore)
return lhsStr._unsafeWithNotEscapedSelfPointerPair(rhsStr) {
return _stdlib_NSStringHasSuffixNFDPointer($0, $1)
}
}
return _stdlib_NSStringHasSuffixNFD(
self._bridgeToObjectiveCImpl(), suffix._bridgeToObjectiveCImpl())
}
}
#else
// FIXME: Implement hasPrefix and hasSuffix without objc
// rdar://problem/18878343
#endif
// Conversions to string from other types.
extension String {
// FIXME: can't just use a default arg for radix below; instead we
// need these single-arg overloads <rdar://problem/17775455>
/// Creates a string representing the given value in base 10.
///
/// The following example converts the maximal `Int` value to a string and
/// prints its length:
///
/// let max = String(Int.max)
/// print("\(max) has \(max.utf16.count) digits.")
/// // Prints "9223372036854775807 has 19 digits."
public init<T : _SignedInteger>(_ v: T) {
self = _int64ToString(v.toIntMax())
}
/// Creates a string representing the given value in base 10.
///
/// The following example converts the maximal `UInt` value to a string and
/// prints its length:
///
/// let max = String(UInt.max)
/// print("\(max) has \(max.utf16.count) digits.")
/// // Prints "18446744073709551615 has 20 digits."
public init<T : UnsignedInteger>(_ v: T) {
self = _uint64ToString(v.toUIntMax())
}
/// Creates a string representing the given value in the specified base.
///
/// Numerals greater than 9 are represented as Roman letters. These letters
/// start with `"A"` if `uppercase` is `true`; otherwise, with `"a"`.
///
/// let v = 999_999
/// print(String(v, radix: 2))
/// // Prints "11110100001000111111"
///
/// print(String(v, radix: 16))
/// // Prints "f423f"
/// print(String(v, radix: 16, uppercase: true))
/// // Prints "F423F"
///
/// - Parameters:
/// - value: The value to convert to a string.
/// - radix: The base to use for the string representation. `radix` must be
/// at least 2 and at most 36.
/// - uppercase: Pass `true` to use uppercase letters to represent numerals
/// greater than 9, or `false` to use lowercase letters. The default is
/// `false`.
public init<T : _SignedInteger>(
_ value: T, radix: Int, uppercase: Bool = false
) {
_precondition(radix > 1, "Radix must be greater than 1")
self = _int64ToString(
value.toIntMax(), radix: Int64(radix), uppercase: uppercase)
}
/// Creates a string representing the given value in the specified base.
///
/// Numerals greater than 9 are represented as Roman letters. These letters
/// start with `"A"` if `uppercase` is `true`; otherwise, with `"a"`.
///
/// let v: UInt = 999_999
/// print(String(v, radix: 2))
/// // Prints "11110100001000111111"
///
/// print(String(v, radix: 16))
/// // Prints "f423f"
/// print(String(v, radix: 16, uppercase: true))
/// // Prints "F423F"
///
/// - Parameters:
/// - value: The value to convert to a string.
/// - radix: The base to use for the string representation. `radix` must be
/// at least 2 and at most 36.
/// - uppercase: Pass `true` to use uppercase letters to represent numerals
/// greater than 9, or `false` to use lowercase letters. The default is
/// `false`.
public init<T : UnsignedInteger>(
_ value: T, radix: Int, uppercase: Bool = false
) {
_precondition(radix > 1, "Radix must be greater than 1")
self = _uint64ToString(
value.toUIntMax(), radix: Int64(radix), uppercase: uppercase)
}
}
extension String {
/// Split the given string at the given delimiter character, returning the
/// strings before and after that character (neither includes the character
/// found) and a boolean value indicating whether the delimiter was found.
public func _splitFirst(separator delim: UnicodeScalar)
-> (before: String, after: String, wasFound : Bool)
{
let rng = unicodeScalars
for i in rng.indices {
if rng[i] == delim {
return (String(rng[rng.startIndex..<i]),
String(rng[rng.index(after: i)..<rng.endIndex]),
true)
}
}
return (self, "", false)
}
/// Split the given string at the first character for which the given
/// predicate returns true. Returns the string before that character, the
/// character that matches, the string after that character,
/// and a boolean value indicating whether any character was found.
public func _splitFirstIf(_ predicate: @noescape (UnicodeScalar) -> Bool)
-> (before: String, found: UnicodeScalar, after: String, wasFound: Bool)
{
let rng = unicodeScalars
for i in rng.indices {
if predicate(rng[i]) {
return (String(rng[rng.startIndex..<i]),
rng[i],
String(rng[rng.index(after: i)..<rng.endIndex]),
true)
}
}
return (self, "🎃", String(), false)
}
}
extension String {
@available(*, unavailable, message: "Renamed to init(repeating:count:) and reordered parameters")
public init(count: Int, repeatedValue c: Character) {
Builtin.unreachable()
}
@available(*, unavailable, message: "Renamed to init(repeating:count:) and reordered parameters")
public init(count: Int, repeatedValue c: UnicodeScalar) {
Builtin.unreachable()
}
}
| apache-2.0 | d207d8b4f91d7564b7aa1a68ffc25e76 | 36.138643 | 101 | 0.639237 | 4.29107 | false | false | false | false |
sihekuang/SKUIComponents | SKUIComponents/Classes/SKRoundedFilledView.swift | 1 | 1435 | //
// SKRoundedFilledView.swift
// SKUIComponents
//
// Created by Daniel Lee on 12/28/17.
//
import UIKit
@IBDesignable
open class SKRoundedFilledView: UIView{
@IBInspectable
open var cornerRadius: CGFloat = 0
@IBInspectable
open var fillColor: UIColor?
// Shadow
@IBInspectable
open var showShadow: Bool = false
@IBInspectable
open var shadowOffsetX: CGFloat = 0
@IBInspectable
open var shadowOffsetY: CGFloat = 0
@IBInspectable
open var shadowRadius: CGFloat = 3
@IBInspectable
open var outlineShadowColor: UIColor = UIColor.black
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override open func draw(_ rect: CGRect) {
// Drawing code
let bgColor = self.fillColor
let radius = self.cornerRadius
let bezierPath = UIBezierPath(roundedRect: rect, cornerRadius: radius)
if showShadow{
SKUIHelper.drawShadow(view: self, bezierPath: bezierPath, cornerRadius: radius, shadowOffsetX: shadowOffsetX, shadowOffsetY: shadowOffsetY, shadowRadius: shadowRadius, color: outlineShadowColor)
}
bgColor?.setFill()
bezierPath.fill()
}
override open func layoutSubviews() {
super.layoutSubviews()
setNeedsDisplay()
}
}
| mit | a4e0890cc2152a0380f03dabe31e589d | 25.090909 | 206 | 0.655749 | 5.218182 | false | false | false | false |
fespinoza/linked-ideas-osx | LinkedIdeas-Shared/Sources/Models/DocumentData.swift | 1 | 1621 | //
// DocumentData.swift
// LinkedIdeas
//
// Created by Felipe Espinoza on 01/05/2016.
// Copyright © 2016 Felipe Espinoza Dev. All rights reserved.
//
import Foundation
private extension String {
static let conceptsKey = "concepts"
static let linksKey = "links"
}
public class DocumentData: NSObject, NSCoding {
public let concepts: [Concept]
public let links: [Link]
override public init() {
self.concepts = []
self.links = []
super.init()
}
public init(concepts: [Concept], links: [Link]) {
self.concepts = concepts
self.links = links
super.init()
}
required public init?(coder aDecoder: NSCoder) {
guard let concepts = aDecoder.decodeObject(forKey: .conceptsKey) as? [Concept],
let links = aDecoder.decodeObject(forKey: .linksKey) as? [Link] else {
return nil
}
self.concepts = concepts
self.links = links
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(self.concepts, forKey: .conceptsKey)
aCoder.encode(self.links, forKey: .linksKey)
}
}
//class Graph: NSObject, NSCoding {
// var concepts = [Concept]()
// var links = [Link]()
//
// required init?(coder aDecoder: NSCoder) {
//
// guard let concepts = aDecoder.decodeObject(forKey: "concepts") as? [Concept],
// let links = aDecoder.decodeObject(forKey: "links") as? [Link]
// else {
// return nil
// }
//
// self.concepts = concepts
// self.links = links
// }
//
// func encode(with aCoder: NSCoder) {
// aCoder.encode(concepts, forKey: "concepts")
// aCoder.encode(links, forKey: "links")
// }
//
//}
| mit | a47d14397f260397116eba9a779509e0 | 22.478261 | 83 | 0.638272 | 3.491379 | false | false | false | false |
victorchee/Vocabulary | Vocabulary/Vocabulary/AppDelegate.swift | 1 | 6006 | //
// AppDelegate.swift
// Vocabulary
//
// Created by qihaijun on 11/10/15.
// Copyright © 2015 VictorChee. 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:.
}
// 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.victorchee.Vocabulary" 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("Vocabulary", 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 | 8adbf0811aa91d5af56c60e999622136 | 54.091743 | 291 | 0.715237 | 5.945545 | false | false | false | false |
Toldy/Clock-In | ClockIn/Views/Custom Views/HoursWorkedButton.swift | 1 | 2992 | //
// HoursWorkedButton.swift
// ClockIn
//
// Created by Julien Colin on 09/09/16.
// Copyright © 2016 Julien Colin. All rights reserved.
//
import UIKit
class HoursWorkedButton: MultipleStatesButton {
var minutesWorked: Int = 0 {
didSet {
super.reloadData()
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupDoubleStateButton()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupDoubleStateButton()
}
func setupDoubleStateButton() {
delegate = self
}
}
extension HoursWorkedButton: MultipleStatesButtonDelegate {
func multipleStatesButton(_ button: MultipleStatesButton, attributedTitleForState state: Int) -> NSAttributedString {
let style = NSMutableParagraphStyle()
style.alignment = NSTextAlignment.center
style.lineBreakMode = NSLineBreakMode.byWordWrapping
let font1 = UIFont.systemFont(ofSize: 15)
let font2 = UIFont.boldSystemFont(ofSize: 15)
let dict1 = [NSAttributedStringKey.foregroundColor: 🖌.lightGreyColor, NSAttributedStringKey.font: font1, NSAttributedStringKey.paragraphStyle: style]
let dict2 = [NSAttributedStringKey.foregroundColor: 🖌.materialRedColor, NSAttributedStringKey.font: font2, NSAttributedStringKey.paragraphStyle: style]
let attributedString = NSMutableAttributedString()
if state == 0 {
let daysWorked = self.minutesWorked / (60 * 24)
let hoursWorked = self.minutesWorked % (60 * 24) / 60
let minutesWorked = self.minutesWorked % 60
if daysWorked != 0 {
attributedString.append(NSAttributedString(string: "\(daysWorked)", attributes: dict2))
attributedString.append(NSAttributedString(string: "j ", attributes: dict1))
}
attributedString.append(NSAttributedString(string: String(format: "%02d", hoursWorked), attributes: dict2))
attributedString.append(NSAttributedString(string: "h ", attributes: dict1))
attributedString.append(NSAttributedString(string: String(format: "%02d", minutesWorked), attributes: dict2))
attributedString.append(NSAttributedString(string: "m", attributes: dict1))
} else {
let hoursWorked = self.minutesWorked / 60
let minutesWorked = self.minutesWorked % 60
attributedString.append(NSAttributedString(string: String(format: "%02d", hoursWorked), attributes: dict2))
attributedString.append(NSAttributedString(string: "h ", attributes: dict1))
attributedString.append(NSAttributedString(string: String(format: "%02d", minutesWorked), attributes: dict2))
attributedString.append(NSAttributedString(string: "m", attributes: dict1))
}
return attributedString
}
func numberOfStatesInButton(_ button: MultipleStatesButton) -> Int { return 2 }
}
| mit | 17ba66649d578f7ca7ecbb80b22ed3a8 | 37.766234 | 159 | 0.677387 | 4.730586 | false | false | false | false |
kay-kim/stitch-examples | todo/ios/Pods/ExtendedJson/ExtendedJson/ExtendedJson/Source/Bson/Coders.swift | 1 | 41449 | //
// Coders.swift
// ExtendedJson
//
// Created by Jason Flax on 10/24/17.
// Copyright © 2017 MongoDB. All rights reserved.
//
import Foundation
fileprivate let positiveInfinity = "∞"
fileprivate let negativeInfinity = "-∞"
fileprivate let nan = "NaN"
fileprivate func unwrap<T>(_ value: T?, codingPath: [CodingKey]) throws -> T {
guard let value = value else {
throw DecodingError.valueNotFound(T.self, DecodingError.Context(codingPath: codingPath, debugDescription: "Value of type \(T.self) was not found"))
}
return value
}
public class BSONEncoder {
struct CodingKeys {
static let shouldIncludeSourceMap = CodingUserInfoKey(rawValue: "withSourceMap")!
}
public func encode(_ value: Encodable) throws -> Document {
let encoder = _BSONEncoder()
try value.encode(to: encoder)
return encoder.target.document
}
public func encode<T>(_ value: T,
shouldIncludeSourceMap: Bool) throws -> Data where T : Encodable {
let encoder = JSONEncoder()
encoder.nonConformingFloatEncodingStrategy =
JSONEncoder.NonConformingFloatEncodingStrategy.convertToString(positiveInfinity: positiveInfinity,
negativeInfinity: negativeInfinity,
nan: nan)
encoder.userInfo[CodingKeys.shouldIncludeSourceMap] = shouldIncludeSourceMap
switch value {
case let val as Double:
return try encoder.encode(val.toExtendedJson as! [String: String])
case let val as Int:
return try encoder.encode(val.toExtendedJson as! [String: String])
case let val as Int32:
return try encoder.encode(val.toExtendedJson as! [String: String])
case let val as Int64:
return try encoder.encode(val.toExtendedJson as! [String: String])
case let val as Decimal:
return try encoder.encode(val.toExtendedJson as! [String: String])
case let val as Date:
return try encoder.encode(val.toExtendedJson as! [String: String])
default:
return try encoder.encode(value)
}
}
public init() {}
}
fileprivate class _BSONEncoder : Encoder, _BSONCodingPathContaining {
enum Target {
case document(Document)
case primitive(get: () -> ExtendedJsonRepresentable?,
set: (ExtendedJsonRepresentable?) -> ())
var document: Document {
get {
switch self {
case .document(let doc): return doc
case .primitive(let get, _): return get() as? Document ?? Document()
}
}
set {
switch self {
case .document: self = .document(newValue)
case .primitive(_, let set): set(newValue)
}
}
}
var primitive: ExtendedJsonRepresentable? {
get {
switch self {
case .document(let doc): return doc
case .primitive(let get, _): return get()
}
}
set {
switch self {
case .document: self = .document(newValue as! Document)
case .primitive(_, let set): set(newValue)
}
}
}
}
var target: Target
var codingPath: [CodingKey]
var userInfo: [CodingUserInfoKey : Any] = [:]
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> {
let container = _BSONKeyedEncodingContainer<Key>(encoder: self)
return KeyedEncodingContainer(container)
}
func unkeyedContainer() -> UnkeyedEncodingContainer {
return _BSONUnkeyedEncodingContainer(encoder: self)
}
func singleValueContainer() -> SingleValueEncodingContainer {
return _BSONSingleValueEncodingContainer(encoder: self)
}
init(codingPath: [CodingKey] = [], target: Target = .document([:])) {
self.codingPath = codingPath
self.target = target
}
// MARK: - Value conversion
func convert(_ value: Bool) throws -> ExtendedJsonRepresentable { return value }
func convert(_ value: Int) throws -> ExtendedJsonRepresentable { return value }
func convert(_ value: Int8) throws -> ExtendedJsonRepresentable { return Int32(value) }
func convert(_ value: Int16) throws -> ExtendedJsonRepresentable { return Int32(value) }
func convert(_ value: Int32) throws -> ExtendedJsonRepresentable { return value }
func convert(_ value: Int64) throws -> ExtendedJsonRepresentable { return Int(value) }
func convert(_ value: UInt8) throws -> ExtendedJsonRepresentable { return Int32(value) }
func convert(_ value: UInt16) throws -> ExtendedJsonRepresentable { return Int32(value) }
func convert(_ value: UInt32) throws -> ExtendedJsonRepresentable { return Int(value) }
func convert(_ value: Float) throws -> ExtendedJsonRepresentable { return Double(value) }
func convert(_ value: Decimal) throws -> ExtendedJsonRepresentable { return value }
func convert(_ value: Double) throws -> ExtendedJsonRepresentable { return value }
func convert(_ value: String) throws -> ExtendedJsonRepresentable { return value }
func convert(_ value: UInt) throws -> ExtendedJsonRepresentable {
guard value < Int.max else {
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath, debugDescription: "Value exceeds \(Int.max) which is the BSON Int limit"))
}
return Int(value)
}
func convert(_ value: UInt64) throws -> ExtendedJsonRepresentable {
// BSON only supports 64 bit platforms where UInt64 is the same size as Int64
return try convert(UInt(value))
}
func encode<T : Encodable>(_ value: T) throws -> ExtendedJsonRepresentable? {
if let primitive = value as? ExtendedJsonRepresentable {
return primitive
} else {
var primitive: ExtendedJsonRepresentable? = nil
let encoder = _BSONEncoder(target: .primitive(get: { primitive }, set: { primitive = $0 }))
try value.encode(to: encoder)
return primitive
}
}
}
fileprivate class _BSONKeyedEncodingContainer<K : CodingKey> : KeyedEncodingContainerProtocol, _BSONCodingPathContaining {
let encoder: _BSONEncoder
var codingPath: [CodingKey]
init(encoder: _BSONEncoder) {
self.encoder = encoder
self.codingPath = encoder.codingPath
}
func encode<T>(_ value: T, forKey key: K) throws where T : Encodable {
try with(pushedKey: key) {
encoder.target.document[key.stringValue] = try encoder.encode(value)
}
}
func encodeNil(forKey key: K) throws {
with(pushedKey: key) {
encoder.target.document[key.stringValue] = nil
}
}
private func nestedEncoder(forKey key: CodingKey) -> _BSONEncoder {
return self.encoder.with(pushedKey: key) {
return _BSONEncoder(codingPath: self.encoder.codingPath, target: .primitive(get: { self.encoder.target.document[key.stringValue] }, set: { self.encoder.target.document[key.stringValue] = $0 }))
}
}
func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: K) -> KeyedEncodingContainer<NestedKey> {
let encoder = nestedEncoder(forKey: key)
return encoder.container(keyedBy: keyType)
}
func nestedUnkeyedContainer(forKey key: K) -> UnkeyedEncodingContainer {
let encoder = nestedEncoder(forKey: key)
return encoder.unkeyedContainer()
}
func superEncoder() -> Encoder {
return nestedEncoder(forKey: _BSONSuperKey.super)
}
func superEncoder(forKey key: K) -> Encoder {
return nestedEncoder(forKey: key)
}
typealias Key = K
}
fileprivate struct _BSONUnkeyedEncodingContainer : UnkeyedEncodingContainer {
var count: Int {
return encoder.target.document.count
}
var encoder: _BSONEncoder
var codingPath: [CodingKey] {
get {
return encoder.codingPath
}
set {
encoder.codingPath = newValue
}
}
init(encoder: _BSONEncoder) {
self.encoder = encoder
if (self.encoder.target.document.count == 0) {
self.encoder.target.document = [:] // array
}
}
private func nestedEncoder() -> _BSONEncoder {
let index = self.encoder.target.document.count
self.encoder.target.document[String(index)] = Document()
return _BSONEncoder(codingPath: codingPath, target: .primitive(get: { self.encoder.target.document[String(index)] }, set: { self.encoder.target.document[String(index)] = $0 }))
}
func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> {
let encoder = nestedEncoder()
let container = _BSONKeyedEncodingContainer<NestedKey>(encoder: encoder)
return KeyedEncodingContainer(container)
}
func nestedUnkeyedContainer() -> UnkeyedEncodingContainer {
let encoder = nestedEncoder()
return _BSONUnkeyedEncodingContainer(encoder: encoder)
}
func superEncoder() -> Encoder {
// TODO: Check: is this OK?
return nestedEncoder()
}
func encode(_ value: Bool) throws { try encoder.target.document[String(describing: index)] = (encoder.convert(value)) }
func encode(_ value: Int) throws { try encoder.target.document[String(describing: index)] = (encoder.convert(value)) }
func encode(_ value: Int8) throws { try encoder.target.document[String(describing: index)] = (encoder.convert(value)) }
func encode(_ value: Int16) throws { try encoder.target.document[String(describing: index)] = encoder.convert(value) }
func encode(_ value: Int32) throws { try encoder.target.document[String(describing: index)] = encoder.convert(value) }
func encode(_ value: Int64) throws { try encoder.target.document[String(describing: index)] = encoder.convert(value) }
func encode(_ value: UInt) throws { try encoder.target.document[String(describing: index)] = encoder.convert(value) }
func encode(_ value: UInt8) throws { try encoder.target.document[String(describing: index)] = encoder.convert(value) }
func encode(_ value: UInt16) throws { try encoder.target.document[String(describing: index)] = encoder.convert(value) }
func encode(_ value: UInt32) throws { try encoder.target.document[String(describing: index)] = encoder.convert(value) }
func encode(_ value: UInt64) throws { try encoder.target.document[String(describing: index)] = encoder.convert(value) }
func encode(_ value: String) throws { try encoder.target.document[String(describing: index)] = encoder.convert(value) }
func encode(_ value: Float) throws { try encoder.target.document[String(describing: index)] = encoder.convert(value) }
func encode(_ value: Decimal) throws { try encoder.target.document[String(describing: index)] = encoder.convert(value) }
func encode(_ value: Double) throws { try encoder.target.document[String(describing: index)] = encoder.convert(value) }
func encode<T : Encodable>(_ value: T) throws { try encoder.target.document[String(describing: index)] = (unwrap(encoder.encode(value), codingPath: codingPath)) }
mutating func encodeNil() throws { encoder.target.document[String(describing: index)] = Null() }
}
fileprivate struct _BSONSingleValueEncodingContainer : SingleValueEncodingContainer {
let encoder: _BSONEncoder
let codingPath: [CodingKey]
init(encoder: _BSONEncoder) {
self.encoder = encoder
self.codingPath = encoder.codingPath
}
func encodeNil() throws { encoder.target.primitive = nil }
func encode(_ value: Bool) throws { try encoder.target.primitive = encoder.convert(value) }
func encode(_ value: Int) throws { try encoder.target.primitive = encoder.convert(value) }
func encode(_ value: Int8) throws { try encoder.target.primitive = encoder.convert(value) }
func encode(_ value: Int16) throws { try encoder.target.primitive = encoder.convert(value) }
func encode(_ value: Int32) throws { try encoder.target.primitive = encoder.convert(value) }
func encode(_ value: Int64) throws { try encoder.target.primitive = encoder.convert(value) }
func encode(_ value: UInt8) throws { try encoder.target.primitive = encoder.convert(value) }
func encode(_ value: UInt16) throws { try encoder.target.primitive = encoder.convert(value) }
func encode(_ value: UInt32) throws { try encoder.target.primitive = encoder.convert(value) }
func encode(_ value: Float) throws { try encoder.target.primitive = encoder.convert(value) }
func encode(_ value: Decimal) throws { try encoder.target.primitive = encoder.convert(value) }
func encode(_ value: Double) throws {
try encoder.with(replacedPath: codingPath) {
try encoder.target.primitive = encoder.convert(value)
}
}
func encode(_ value: String) throws { try encoder.target.primitive = encoder.convert(value) }
func encode(_ value: UInt) throws { try encoder.target.primitive = encoder.convert(value) }
func encode(_ value: UInt64) throws { try encoder.target.primitive = encoder.convert(value) }
func encode<T>(_ value: T) throws where T : Encodable { try encoder.target.primitive = encoder.encode(value) }
}
public class BSONDecoder {
public func decode<T : Decodable>(_ type: T.Type,
from document: Document) throws -> T {
let decoder = _BSONDecoder(target: .document(document))
return try T(from: decoder)
}
public func decode<T>(_ type: T.Type,
from data: Data,
hasSourceMap: Bool) throws -> T where T: Decodable {
switch type {
case let superType as ExtendedJsonRepresentable.Type:
if hasSourceMap { fallthrough }
guard let t = try superType.fromExtendedJson(
xjson: try JSONSerialization.jsonObject(with: data,
options: .allowFragments)) as? T else {
throw BsonError.parseValueFailure(value: data, attemptedType: type)
}
return t
default:
let decoder = JSONDecoder()
decoder.nonConformingFloatDecodingStrategy =
JSONDecoder.NonConformingFloatDecodingStrategy.convertFromString(positiveInfinity: positiveInfinity,
negativeInfinity: negativeInfinity,
nan: nan)
return try decoder.decode(type, from: data)
}
}
public init() {}
}
fileprivate class _BSONDecoder: Decoder, _BSONCodingPathContaining {
enum Target {
case document(Document)
case primitive(get: () -> ExtendedJsonRepresentable?)
case storedExtendedJsonRepresentable(ExtendedJsonRepresentable?)
var document: Document {
get {
switch self {
case .document(let doc): return doc
case .primitive(let get): return get() as? Document ?? Document()
case .storedExtendedJsonRepresentable(let val): return val as? Document ?? Document()
}
}
}
var primitive: ExtendedJsonRepresentable? {
get {
switch self {
case .document(let doc): return doc
case .primitive(let get): return get()
case .storedExtendedJsonRepresentable(let val): return val
}
}
}
}
let target: Target
var codingPath: [CodingKey]
var userInfo: [CodingUserInfoKey : Any] = [:]
init(codingPath: [CodingKey] = [], target: Target) {
self.target = target
self.codingPath = codingPath
}
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key : CodingKey {
let container = _BSONKeyedDecodingContainer<Key>(decoder: self, codingPath: self.codingPath)
return KeyedDecodingContainer(container)
}
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
return _BSONUnkeyedDecodingContainer(decoder: self)
}
func singleValueContainer() throws -> SingleValueDecodingContainer {
return _BSONSingleValueDecodingContainer(codingPath: self.codingPath, decoder: self)
}
/// Performs the given closure with the given key pushed onto the end of the current coding path.
///
/// - parameter key: The key to push. May be nil for unkeyed containers.
/// - parameter work: The work to perform with the key in the path.
func with<T>(pushedKey key: CodingKey, _ work: () throws -> T) rethrows -> T {
self.codingPath.append(key)
let ret: T = try work()
self.codingPath.removeLast()
return ret
}
// MARK: - Value conversion
func unwrap<T : ExtendedJsonRepresentable>(_ value: ExtendedJsonRepresentable?) throws -> T {
guard let primitiveValue = value, !(primitiveValue is NSNull) else {
throw DecodingError.valueNotFound(T.self,
DecodingError.Context(codingPath: codingPath,
debugDescription: "Value not found - expected value of type \(T.self), found null / nil"))
}
guard let tValue = primitiveValue as? T else {
throw DecodingError.typeMismatch(T.self,
DecodingError.Context(codingPath: codingPath,
debugDescription: "Type mismatch - expected value of type \(T.self), found \(type(of: primitiveValue))"))
}
return tValue
}
func unwrap(_ value: ExtendedJsonRepresentable?) throws -> Int32 {
guard let primitiveValue = value, !(primitiveValue is NSNull) else {
throw DecodingError.valueNotFound(Int32.self, DecodingError.Context(codingPath: codingPath, debugDescription: "Value not found - expected value of type \(Int32.self), found null / nil"))
}
switch primitiveValue {
case let number as Int32:
return number
case let number as Int:
guard number >= Int32.min && number <= Int32.max else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "BSON number <\(number)> does not fit in \(Int32.self)"))
}
return Int32(number) as Int32
case let number as Double:
guard number >= Double(Int32.min) && number <= Double(Int32.max) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "BSON number <\(number)> does not fit in \(Int32.self)"))
}
return Int32(number) as Int32
default:
throw DecodingError.typeMismatch(Int32.self, DecodingError.Context(codingPath: codingPath, debugDescription: "Type mismatch - expected value of type \(Int32.self), found \(type(of: primitiveValue))"))
}
}
func unwrap(_ value: ExtendedJsonRepresentable?) throws -> Int {
guard let primitiveValue = value, !(primitiveValue is NSNull) else {
throw DecodingError.valueNotFound(Int.self, DecodingError.Context(codingPath: codingPath, debugDescription: "Value not found - expected value of type \(Int.self), found null / nil"))
}
switch primitiveValue {
case let number as Int32:
return Int(number) as Int
case let number as Int:
return number
case let number as Double:
guard number >= Double(Int.min) && number <= Double(Int.max) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "BSON number <\(number)> does not fit in \(Int.self)"))
}
return Int(number) as Int
default:
throw DecodingError.typeMismatch(Int.self, DecodingError.Context(codingPath: codingPath, debugDescription: "Type mismatch - expected value of type \(Int.self), found \(type(of: primitiveValue))"))
}
}
func unwrap(_ value: ExtendedJsonRepresentable?) throws -> Double {
guard let primitiveValue = value, !(primitiveValue is NSNull) else {
throw DecodingError.valueNotFound(Double.self, DecodingError.Context(codingPath: codingPath, debugDescription: "Value not found - expected value of type \(Double.self), found null / nil"))
}
switch primitiveValue {
case let number as Int32:
return Double(number)
case let number as Int:
return Double(number)
case let number as Double:
return number
default:
throw DecodingError.typeMismatch(Double.self, DecodingError.Context(codingPath: codingPath, debugDescription: "Type mismatch - expected value of type \(Double.self), found \(type(of: primitiveValue))"))
}
}
func unwrap(_ value: ExtendedJsonRepresentable?) throws -> Bool {
guard let primitiveValue = value, !(primitiveValue is NSNull) else {
throw DecodingError.valueNotFound(Bool.self, DecodingError.Context(codingPath: codingPath, debugDescription: "Value not found - expected value of type \(Bool.self), found null / nil"))
}
guard let bool = primitiveValue as? Bool else {
throw DecodingError.typeMismatch(Bool.self, DecodingError.Context(codingPath: codingPath, debugDescription: "Type mismatch - expected value of type \(Bool.self), found \(type(of: primitiveValue))"))
}
return bool
}
func unwrap(_ value: ExtendedJsonRepresentable?) throws -> Int8 {
let number: Int32 = try unwrap(value)
guard number >= Int8.min && number <= Int8.max else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "BSON number <\(number)> does not fit in \(Int8.self)"))
}
return Int8(number)
}
func unwrap(_ value: ExtendedJsonRepresentable?) throws -> Int16 {
let number: Int32 = try unwrap(value)
guard number >= Int16.min && number <= Int16.max else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "BSON number <\(number)> does not fit in \(Int16.self)"))
}
return Int16(number)
}
func unwrap(_ value: ExtendedJsonRepresentable?) throws -> Int64 {
guard let primitiveValue = value, !(primitiveValue is NSNull) else {
throw DecodingError.valueNotFound(Int.self, DecodingError.Context(codingPath: codingPath, debugDescription: "Value not found - expected value of type \(Int.self), found null / nil"))
}
switch primitiveValue {
case let number as Int64:
return number
default:
throw DecodingError.typeMismatch(Double.self, DecodingError.Context(codingPath: codingPath, debugDescription: "Type mismatch - expected value of type \(Double.self), found \(type(of: primitiveValue))"))
}
}
func unwrap(_ value: ExtendedJsonRepresentable?) throws -> UInt8 {
let number: Int32 = try unwrap(value)
guard number >= UInt8.min && number <= UInt8.max else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "BSON number <\(number)> does not fit in \(UInt8.self)"))
}
return UInt8(number)
}
func unwrap(_ value: ExtendedJsonRepresentable?) throws -> UInt16 {
let number: Int32 = try unwrap(value)
guard number >= UInt16.min && number <= UInt16.max else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "BSON number <\(number)> does not fit in \(UInt16.self)"))
}
return UInt16(number)
}
func unwrap(_ value: ExtendedJsonRepresentable?) throws -> UInt32 {
let number: Int = try unwrap(value)
guard number >= UInt32.min && number <= UInt32.max else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "BSON number <\(number)> does not fit in \(UInt32.self)"))
}
return UInt32(number)
}
func unwrap(_ value: ExtendedJsonRepresentable?) throws -> Float {
// TODO: Check losing precision like JSONEncoder
let number: Double = try unwrap(value)
return Float(number)
}
func unwrap(_ value: ExtendedJsonRepresentable?) throws -> Decimal {
guard let primitiveValue = value, !(primitiveValue is NSNull) else {
throw DecodingError.valueNotFound(Int.self, DecodingError.Context(codingPath: codingPath, debugDescription: "Value not found - expected value of type \(Int.self), found null / nil"))
}
switch primitiveValue {
case let number as Decimal:
return number
default:
throw DecodingError.typeMismatch(Double.self, DecodingError.Context(codingPath: codingPath, debugDescription: "Type mismatch - expected value of type \(Double.self), found \(type(of: primitiveValue))"))
}
}
func unwrap(_ value: ExtendedJsonRepresentable?) throws -> UInt {
let number: Int = try unwrap(value)
guard number <= UInt.max else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath, debugDescription: "BSON number <\(number)> does not fit in \(UInt.self)"))
}
return UInt(number)
}
func unwrap(_ value: ExtendedJsonRepresentable?) throws -> UInt64 {
let number: UInt = try unwrap(value)
// BSON only supports 64 bit platforms where UInt64 is the same size as UInt
return UInt64(number)
}
func decode<T>(_ value: ExtendedJsonRepresentable?) throws -> T where T : Decodable {
guard let value = value else {
throw DecodingError.valueNotFound(T.self,
DecodingError.Context(codingPath: codingPath,
debugDescription: "Value not found - expected value of type \(T.self), found null / nil"))
}
switch T.self {
case is Document.Type:
return try ExtendedJson.unwrap(unwrap(value), codingPath: codingPath) as Document as! T
case is BSONArray.Type:
return try ExtendedJson.unwrap(unwrap(value), codingPath: codingPath) as BSONArray as! T
case is ObjectId.Type:
return try ExtendedJson.unwrap(unwrap(value), codingPath: codingPath) as ObjectId as! T
case is Symbol.Type:
return try ExtendedJson.unwrap(unwrap(value), codingPath: codingPath) as Symbol as! T
case is Binary.Type:
return try ExtendedJson.unwrap(unwrap(value), codingPath: codingPath) as Binary as! T
case is Code.Type:
return try ExtendedJson.unwrap(unwrap(value), codingPath: codingPath) as Code as! T
case is DBPointer.Type:
return try ExtendedJson.unwrap(unwrap(value), codingPath: codingPath) as DBPointer as! T
case is DBRef.Type:
return try ExtendedJson.unwrap(unwrap(value), codingPath: codingPath) as DBRef as! T
case is Timestamp.Type:
return try ExtendedJson.unwrap(unwrap(value), codingPath: codingPath) as Timestamp as! T
case is Undefined.Type:
return try ExtendedJson.unwrap(unwrap(value), codingPath: codingPath) as Undefined as! T
case is MaxKey.Type:
return try ExtendedJson.unwrap(unwrap(value), codingPath: codingPath) as MaxKey as! T
case is MinKey.Type:
return try ExtendedJson.unwrap(unwrap(value), codingPath: codingPath) as MinKey as! T
case is Date.Type:
return try ExtendedJson.unwrap(unwrap(value), codingPath: codingPath) as Date as! T
case is Decimal.Type:
return try unwrap(value) as Decimal as! T
case is NSNull.Type:
return Null() as! T
case is RegularExpression.Type:
return try ExtendedJson.unwrap(unwrap(value), codingPath: codingPath) as RegularExpression as! T
default: break
}
let decoder = _BSONDecoder(target: .storedExtendedJsonRepresentable(value))
return try T(from: decoder)
}
}
fileprivate struct _BSONKeyedDecodingContainer<Key : CodingKey> : KeyedDecodingContainerProtocol {
let decoder: _BSONDecoder
var codingPath: [CodingKey]
var allKeys: [Key] {
return decoder.target.document.orderedKeys.flatMap { Key(stringValue: $0 as! String) }
}
func decodeNil(forKey key: Key) throws -> Bool {
return decoder.target.document[key.stringValue] == nil
}
func contains(_ key: Key) -> Bool {
return decoder.target.document[key.stringValue] != nil
}
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool {
return try decoder.with(pushedKey: key) {
return try decoder.unwrap(decoder.target.document[key.stringValue])
}
}
func decode(_ type: Int.Type, forKey key: Key) throws -> Int {
return try decoder.with(pushedKey: key) {
return try decoder.unwrap(decoder.target.document[key.stringValue])
}
}
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 {
return try decoder.with(pushedKey: key) {
return try decoder.unwrap(decoder.target.document[key.stringValue])
}
}
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 {
return try decoder.with(pushedKey: key) {
return try decoder.unwrap(decoder.target.document[key.stringValue])
}
}
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 {
return try decoder.with(pushedKey: key) {
return try decoder.unwrap(decoder.target.document[key.stringValue])
}
}
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 {
return try decoder.with(pushedKey: key) {
return try decoder.unwrap(decoder.target.document[key.stringValue])
}
}
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt {
return try decoder.with(pushedKey: key) {
return try decoder.unwrap(decoder.target.document[key.stringValue])
}
}
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 {
return try decoder.with(pushedKey: key) {
return try decoder.unwrap(decoder.target.document[key.stringValue])
}
}
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 {
return try decoder.with(pushedKey: key) {
return try decoder.unwrap(decoder.target.document[key.stringValue])
}
}
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 {
return try decoder.with(pushedKey: key) {
return try decoder.unwrap(decoder.target.document[key.stringValue])
}
}
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 {
return try decoder.with(pushedKey: key) {
return try decoder.unwrap(decoder.target.document[key.stringValue])
}
}
func decode(_ type: Float.Type, forKey key: Key) throws -> Float {
return try decoder.with(pushedKey: key) {
return try decoder.unwrap(decoder.target.document[key.stringValue])
}
}
func decode(_ type: Decimal.Type, forKey key: Key) throws -> Decimal {
return try decoder.with(pushedKey: key) {
return try decoder.unwrap(decoder.target.document[key.stringValue])
}
}
func decode(_ type: Double.Type, forKey key: Key) throws -> Double {
return try decoder.with(pushedKey: key) {
return try decoder.unwrap(decoder.target.document[key.stringValue])
}
}
func decode(_ type: String.Type, forKey key: Key) throws -> String {
return try decoder.with(pushedKey: key) {
return try decoder.unwrap(decoder.target.document[key.stringValue])
}
}
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable {
return try decoder.with(pushedKey: key) {
return try decoder.decode(decoder.target.document[key.stringValue])
}
}
private func nestedDecoder(forKey key: CodingKey) -> _BSONDecoder {
return decoder.with(pushedKey: key) {
return _BSONDecoder(codingPath: self.decoder.codingPath, target: .primitive(get: { self.decoder.target.document[key.stringValue] }))
}
}
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
return try nestedDecoder(forKey: key).container(keyedBy: type)
}
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
return try nestedDecoder(forKey: key).unkeyedContainer()
}
func superDecoder() throws -> Decoder {
return nestedDecoder(forKey: _BSONSuperKey.super)
}
func superDecoder(forKey key: Key) throws -> Decoder {
return nestedDecoder(forKey: key)
}
}
fileprivate class _BSONUnkeyedDecodingContainer : UnkeyedDecodingContainer, _BSONCodingPathContaining {
let decoder: _BSONDecoder
var codingPath: [CodingKey]
init(decoder: _BSONDecoder) {
self.decoder = decoder
self.codingPath = decoder.codingPath
}
var count: Int? { return decoder.target.document.count }
var currentIndex: Int = 0
var isAtEnd: Bool {
return currentIndex >= self.count!
}
func next() -> ExtendedJsonRepresentable? {
let value = decoder.target.document[decoder.target.document.orderedKeys[currentIndex] as! String]
currentIndex += 1
return value
}
func assertNotAtEnd(_ type: Any.Type) throws {
guard !isAtEnd else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Unkeyed decoding container is at end"))
}
}
/// Decodes a null value.
///
/// If the value is not null, does not increment currentIndex.
///
/// - returns: Whether the encountered value was null.
/// - throws: `DecodingError.valueNotFound` if there are no more values to decode.
func decodeNil() throws -> Bool {
try assertNotAtEnd(NSNull.self)
if decoder.target.document[decoder.target.document.orderedKeys[currentIndex] as! String] == nil {
currentIndex += 1
return true
} else {
return false
}
}
func decode(_ type: Bool.Type) throws -> Bool {
return try decoder.unwrap(next())
}
func decode(_ type: Int.Type) throws -> Int {
return try decoder.unwrap(next())
}
func decode(_ type: Int8.Type) throws -> Int8 {
return try decoder.unwrap(next())
}
func decode(_ type: Int16.Type) throws -> Int16 {
return try decoder.unwrap(next())
}
func decode(_ type: Int32.Type) throws -> Int32 {
return try decoder.unwrap(next())
}
func decode(_ type: Int64.Type) throws -> Int64 {
return try decoder.unwrap(next())
}
func decode(_ type: UInt.Type) throws -> UInt {
return try decoder.unwrap(next())
}
func decode(_ type: UInt8.Type) throws -> UInt8 {
return try decoder.unwrap(next())
}
func decode(_ type: UInt16.Type) throws -> UInt16 {
return try decoder.unwrap(next())
}
func decode(_ type: UInt32.Type) throws -> UInt32 {
return try decoder.unwrap(next())
}
func decode(_ type: UInt64.Type) throws -> UInt64 {
return try decoder.unwrap(next())
}
func decode(_ type: Float.Type) throws -> Float {
return try decoder.unwrap(next())
}
func decode(_ type: Decimal.Type) throws -> Decimal {
return try decoder.unwrap(next())
}
func decode(_ type: Double.Type) throws -> Double {
return try decoder.unwrap(next())
}
func decode(_ type: String.Type) throws -> String {
return try decoder.unwrap(next())
}
func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
return try decoder.decode(next())
}
func nestedDecoder() throws -> _BSONDecoder {
return try decoder.with(pushedKey: _BSONUnkeyedIndexKey(index: self.currentIndex)) {
guard !isAtEnd else {
throw DecodingError.valueNotFound(Decoder.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Cannot get nested decoder -- unkeyed container is at end."))
}
let value = next()
return _BSONDecoder(target: .storedExtendedJsonRepresentable(value))
}
}
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> {
return try nestedDecoder().container(keyedBy: type)
}
func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
return try nestedDecoder().unkeyedContainer()
}
func superDecoder() throws -> Decoder {
return try nestedDecoder()
}
}
fileprivate struct _BSONSingleValueDecodingContainer : SingleValueDecodingContainer {
var codingPath: [CodingKey]
let decoder: _BSONDecoder
private func unwrap<T>(_ value: T?) throws -> T {
return try ExtendedJson.unwrap(value, codingPath: decoder.codingPath)
}
func decodeNil() -> Bool { return decoder.target.primitive == nil }
func decode(_ type: Bool.Type) throws -> Bool { return try decoder.unwrap(decoder.target.primitive) }
func decode(_ type: Int.Type) throws -> Int { return try decoder.unwrap(decoder.target.primitive) }
func decode(_ type: Int8.Type) throws -> Int8 { return try decoder.unwrap(decoder.target.primitive) }
func decode(_ type: Int16.Type) throws -> Int16 { return try decoder.unwrap(decoder.target.primitive) }
func decode(_ type: Int32.Type) throws -> Int32 { return try decoder.unwrap(decoder.target.primitive) }
func decode(_ type: Int64.Type) throws -> Int64 { return try decoder.unwrap(decoder.target.primitive) }
func decode(_ type: UInt.Type) throws -> UInt { return try decoder.unwrap(decoder.target.primitive) }
func decode(_ type: UInt8.Type) throws -> UInt8 { return try decoder.unwrap(decoder.target.primitive) }
func decode(_ type: UInt16.Type) throws -> UInt16 { return try decoder.unwrap(decoder.target.primitive) }
func decode(_ type: UInt32.Type) throws -> UInt32 { return try decoder.unwrap(decoder.target.primitive) }
func decode(_ type: UInt64.Type) throws -> UInt64 { return try decoder.unwrap(decoder.target.primitive) }
func decode(_ type: Float.Type) throws -> Float { return try decoder.unwrap(decoder.target.primitive) }
func decode(_ type: Decimal.Type) throws -> Decimal { return try decoder.unwrap(decoder.target.primitive) }
func decode(_ type: Double.Type) throws -> Double { return try decoder.unwrap(decoder.target.primitive) }
func decode(_ type: String.Type) throws -> String { return try decoder.unwrap(decoder.target.primitive) }
func decode<T>(_ type: T.Type) throws -> T where T : Decodable { return try decoder.decode(decoder.target.primitive) }
}
// - MARK: Supporting Protocols
fileprivate protocol _BSONCodingPathContaining : class {
var codingPath: [CodingKey] { get set }
}
extension _BSONCodingPathContaining {
// MARK: - Coding Path Operations
/// Performs the given closure with the given key pushed onto the end of the current coding path.
///
/// - parameter key: The key to push. May be nil for unkeyed containers.
/// - parameter work: The work to perform with the key in the path.
func with<T>(pushedKey key: CodingKey, _ work: () throws -> T) rethrows -> T {
self.codingPath.append(key)
let ret: T = try work()
self.codingPath.removeLast()
return ret
}
func with<T>(replacedPath path: [CodingKey], _ work: () throws -> T) rethrows -> T {
let originalPath = self.codingPath
self.codingPath = path
let ret: T = try work()
self.codingPath = originalPath
return ret
}
}
// - MARK: Shared Super Key
fileprivate enum _BSONSuperKey : String, CodingKey {
case `super`
}
fileprivate struct _BSONUnkeyedIndexKey : CodingKey {
var index: Int
init(index: Int) {
self.index = index
}
var intValue: Int? {
return index
}
var stringValue: String {
return String(describing: index)
}
init?(intValue: Int) {
self.index = intValue
}
init?(stringValue: String) {
return nil
}
}
| apache-2.0 | 165f6ef5f5177f1143abde3a03872495 | 41.117886 | 214 | 0.641106 | 4.640985 | false | false | false | false |
azarovalex/Simple-Ciphers | Theory Of Information, Lab 1/ViewController.swift | 1 | 6389 | //
// ViewController.swift
// Theory Of Information, Lab 1
//
// Created by Alex Azarov on 15/09/2017.
// Copyright © 2017 Alex Azarov. All rights reserved.
//
import Cocoa
var path: String = ""
func browseFile() -> String {
let dialog = NSOpenPanel();
dialog.title = "Choose a .txt file";
dialog.showsResizeIndicator = true;
dialog.showsHiddenFiles = false;
dialog.canChooseDirectories = true;
dialog.canCreateDirectories = true;
dialog.allowsMultipleSelection = false;
dialog.allowedFileTypes = ["txt"];
if (dialog.runModal() == NSApplication.ModalResponse.OK) {
let result = dialog.url // Pathname of the file
if (result != nil) {
path = result!.path
return path
}
} else {
// User clicked on "Cancel"
return ""
}
return ""
}
class ViewController: NSViewController {
var fileURL = URL(fileURLWithPath: "/")
@IBOutlet weak var plaintextField: NSTextField!
@IBOutlet weak var railfenceField: NSTextField!
@IBOutlet weak var ciphertextField: NSTextField!
@IBOutlet weak var keysizeLabel: NSTextField!
@IBOutlet weak var keyField: NSTextField!
@IBOutlet weak var symbolsCheckbox: NSButton!
var ciphertext = ""
var plaintext = ""
var railfence = ""
var sizeofkey = 0
override func viewDidLoad() {
super.viewDidLoad()
symbolsCheckbox.state = .off
}
// FINISHED
@IBAction func loadText(_ sender: NSButton) {
fileURL = URL(fileURLWithPath: browseFile())
switch sender.tag {
case 1:
do {
plaintextField.stringValue = try String(contentsOf: fileURL)
} catch {
dialogError(question: "Failed reading from URL: \(fileURL)", text: "Error: " + error.localizedDescription)
}
case 2:
do {
ciphertextField.stringValue = try String(contentsOf: fileURL)
} catch {
dialogError(question: "Failed reading from URL: \(fileURL)", text: "Error: " + error.localizedDescription)
}
default:
break
}
}
@IBAction func storeText(_ sender: NSButton) {
fileURL = URL(fileURLWithPath: browseFile())
switch sender.tag {
case 1:
do {
try plaintextField.stringValue.write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
dialogError(question: "Failed writing to URL \(fileURL)", text: "Error: " + error.localizedDescription)
}
case 2:
do {
try ciphertextField.stringValue.write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
dialogError(question: "Failed writing to URL \(fileURL)", text: "Error: " + error.localizedDescription)
}
default:
break
}
}
// FINISHED
@IBAction func encodeBtnPressed(_ sender: Any) {
plaintext = plaintextField.stringValue
guard plaintext != "" else {
dialogError(question: "Your plaintext is an empty string!", text: "Error: Nothing to encipher.")
return
}
// Get sizeofkey
var keyStr = keyField.stringValue
keyStr = keyStr.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()
keyField.stringValue = keyStr
if (keyStr == "") {
dialogError(question: "Key field is empty!", text: "Error: Can not encipher without a key.")
return
}
sizeofkey = Int(keyStr)!
if (sizeofkey == 0) {
dialogError(question: "Not a valid key!", text: "Error: Can not encipher with zero hight.")
return
}
// Save special characters
// if symbolsCheckbox.state == .on {
plaintext = String(cString: SaveSpecialSymbols(plaintext))
// } else {
// plaintext = plaintext.components(separatedBy: CharacterSet.letters.inverted).joined()
// plaintextField.stringValue = plaintext
// }
// Draw the rail fence
railfence = String(cString: MakeRailFence(plaintext, Int32(plaintext.count), Int32(sizeofkey)))
railfenceField.stringValue = railfence
// Load special characters and display ciphertext
ciphertext = String(cString: Encipher(railfence, Int32(plaintext.count)))
if symbolsCheckbox.state == .on {
// ciphertext = String(cString: ReturnSpecialSymbols(ciphertext))
}
ciphertextField.stringValue = ciphertext
}
@IBAction func decodeBtnPressed(_ sender: Any) {
ciphertext = ciphertextField.stringValue
guard ciphertext != "" else {
dialogError(question: "Your ciphertext is an empy string!", text: "Error: Nothing to encipher.")
return
}
// Get sizeofkey
var keyStr = keyField.stringValue
keyStr = keyStr.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()
keyField.stringValue = keyStr
if (keyStr == "") {
dialogError(question: "Key field is empty!", text: "Error: Can not decipher without a key.")
return
}
sizeofkey = Int(keyStr)!
if (sizeofkey == 0) {
dialogError(question: "Not a valid key!", text: "Error: Can not decipher with zero hight.")
return
}
if symbolsCheckbox.state == .on {
ciphertext = String(cString: SaveSpecialSymbols(ciphertext))
} else {
ciphertext = ciphertext.components(separatedBy: CharacterSet.letters.inverted).joined()
ciphertextField.stringValue = ciphertext
}
plaintext = String(cString: Decipher(ciphertext, Int32(sizeofkey)));
if symbolsCheckbox.state == .on {
plaintext = String(cString: ReturnSpecialSymbols(plaintext))
}
plaintextField.stringValue = plaintext
railfence = String(cString: MakeRailFence(plaintext, Int32(plaintext.count), Int32(sizeofkey)))
railfenceField.stringValue = railfence
}
}
| mit | 07347202c3f0d108a40308b36372ef64 | 32.978723 | 122 | 0.584534 | 4.967341 | false | false | false | false |
hujiaweibujidao/Gank | Gank/Class/Gank/AHClassWebViewController.swift | 1 | 10890 | //
// AHClassWebViewController.swift
// Gank
//
// Created by AHuaner on 2016/12/20.
// Copyright © 2016年 CoderAhuan. All rights reserved.
//
import UIKit
import WebKit
class AHClassWebViewController: BaseWebViewController {
// MARK: - property
fileprivate var contentOffsetY: CGFloat = 0.0
fileprivate var oldContentOffsetY: CGFloat = 0.0
fileprivate var newContentOffsetY: CGFloat = 0.0
fileprivate var isDismissAnimation: Bool = true
fileprivate var isCustomTranstion: Bool = false
var currentCompleted: CGFloat = 0.0
var gankModel: GankModel?
// 文章是否被收藏
fileprivate var isCollected: Bool = false
// MARK: - control
// 弹窗
fileprivate lazy var moreView: AHMoreView = {
let moreView = AHMoreView.moreView()
let W = kScreen_W / 2
let H = CGFloat(moreView.titles.count * 44 + 15)
moreView.alpha = 0.01
moreView.frame = CGRect(x: kScreen_W - W - 3, y: 50, width: W, height: H)
return moreView
}()
// 蒙版
fileprivate var maskBtnView: UIButton = {
let maskBtnView = UIButton()
maskBtnView.frame = kScreen_BOUNDS
maskBtnView.backgroundColor = UIColor.clear
return maskBtnView
}()
// MARK: - life cycle
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
isCustomTranstion = false
self.navigationController?.delegate = self
tabBarController?.tabBar.isHidden = true
UIApplication.shared.statusBarStyle = .lightContent
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.delegate = nil
if isCustomTranstion { return }
tabBarController?.tabBar.isHidden = false
let snapView = navigationController?.view.superview?.viewWithTag(3333)
let maskView = navigationController?.view.superview?.viewWithTag(4444)
snapView?.removeFromSuperview()
maskView?.removeFromSuperview()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
deinit {
webView.scrollView.delegate = nil
}
// MARK: - event && methods
fileprivate func setupUI() {
self.title = "加载中..."
webView.scrollView.delegate = self
let oriImage = UIImage(named: "icon_more")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
navigationItem.rightBarButtonItem = UIBarButtonItem(image: oriImage, style: .plain, target: self, action: #selector(moreClick))
maskBtnView.addTarget(self, action: #selector(dismissMoreView), for: .touchUpInside)
moreView.tableViewdidSelectClouse = { [unowned self] (indexPath) in
self.dismissMoreView()
switch indexPath.row {
case 0: // 收藏
self.collectGankAction()
case 1: // 分享
self.shareEvent()
case 2: // 复制链接
let pasteboard = UIPasteboard.general
pasteboard.string = self.urlString!
ToolKit.showSuccess(withStatus: "复制成功")
case 3: // Safari打开
guard let urlString = self.urlString else { return }
guard let url = URL(string: urlString) else { return }
UIApplication.shared.openURL(url)
default: break
}
}
}
// 检验文章是否已被收藏
fileprivate func cheakIsCollected() {
let query: BmobQuery = BmobQuery(className: "Collect")
let array = [["userId": User.info?.objectId], ["gankId": gankModel?.id]]
query.addTheConstraintByAndOperation(with: array)
query.findObjectsInBackground { (array, error) in
// 加载失败
if error != nil { return }
guard let ganksArr = array else { return }
if ganksArr.count == 1 { // 已收藏
self.moreView.gankBe(collected: true)
self.isCollected = true
self.gankModel?.objectId = (ganksArr.first as! BmobObject).objectId
} else { // 未收藏
self.moreView.gankBe(collected: false)
self.isCollected = false
self.gankModel?.objectId = nil
}
guard let nav = self.navigationController else { return }
nav.view.insertSubview(self.maskBtnView, aboveSubview: self.webView)
nav.view.insertSubview(self.moreView, aboveSubview: self.webView)
UIView.animate(withDuration: 0.25) {
self.moreView.alpha = 1
}
}
}
func moreClick() {
cheakIsCollected()
}
func dismissMoreView() {
maskBtnView.removeFromSuperview()
UIView.animate(withDuration: 0.25, animations: {
self.moreView.alpha = 0.01
}) { (_) in
self.moreView.removeFromSuperview()
}
}
// 点击收藏
func collectGankAction() {
if User.info == nil { // 未登录状态
//
isCustomTranstion = true
let loginVC = AHLoginViewController()
let nav = UINavigationController(rootViewController: loginVC)
present(nav, animated: true, completion: nil)
return
}
ToolKit.checkUserLoginedWithOtherDevice {
// 登录状态
// 取消收藏
if self.isCollected {
ToolKit.show(withStatus: "正在取消收藏")
let gank: BmobObject = BmobObject(outDataWithClassName: "Collect", objectId: self.gankModel?.objectId)
gank.deleteInBackground { (isSuccessful, error) in
if isSuccessful { // 删除成功
ToolKit.showSuccess(withStatus: "已取消收藏")
self.isCollected = false
self.moreView.gankBe(collected: false)
} else {
AHLog(error!)
ToolKit.showError(withStatus: "取消收藏失败")
}
}
return
}
// 收藏
let gankInfo = BmobObject(className: "Collect")
gankInfo?.setObject(User.info!.objectId, forKey: "userId")
gankInfo?.setObject(User.info!.mobilePhoneNumber, forKey: "userPhone")
if let gankModel = self.gankModel {
gankInfo?.setObject(gankModel.id, forKey: "gankId")
gankInfo?.setObject(gankModel.desc, forKey: "gankDesc")
gankInfo?.setObject(gankModel.type, forKey: "gankType")
gankInfo?.setObject(gankModel.user, forKey: "gankUser")
gankInfo?.setObject(gankModel.publishedAt, forKey: "gankPublishAt")
gankInfo?.setObject(gankModel.url, forKey: "gankUrl")
}
gankInfo?.saveInBackground(resultBlock: { (isSuccessful, error) in
if error != nil { // 收藏失败
AHLog(error!)
ToolKit.showError(withStatus: "收藏失败")
} else { // 收藏成功
ToolKit.showSuccess(withStatus: "收藏成功")
self.isCollected = true
self.moreView.gankBe(collected: true)
}
})
}
}
fileprivate func shareEvent() {
UMSocialUIManager.showShareMenuViewInWindow { (platformType, userInfo) in
let messageObject = UMSocialMessageObject()
let shareObject = UMShareWebpageObject.shareObject(withTitle: "Gank", descr: self.gankModel?.desc, thumImage: UIImage(named: "icon108"))
shareObject?.webpageUrl = self.gankModel?.url
messageObject.shareObject = shareObject
UMSocialManager.default().share(to: platformType, messageObject: messageObject, currentViewController: self) { (data, error) in
if error == nil {
AHLog(data)
} else {
AHLog("分享失败\(error!)")
}
}
}
}
}
// MARK: - UIScrollViewDelegate
extension AHClassWebViewController: UIScrollViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
contentOffsetY = scrollView.contentOffset.y
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// scrollView还在加载的时候系统会自动调用scrollViewDidScroll
// 我们要的是scrollView加载好以后再执行下面的代码
if scrollView.contentSize == CGSize.zero { return }
newContentOffsetY = scrollView.contentOffset.y
if newContentOffsetY > oldContentOffsetY && oldContentOffsetY > contentOffsetY {
// setToolViewHidden(true)
// self.navigationController?.setNavigationBarHidden(true, animated: true)
} else if newContentOffsetY < oldContentOffsetY && oldContentOffsetY < contentOffsetY {
// setToolViewHidden(false)
// self.navigationController?.setNavigationBarHidden(false, animated: true)
}
let begainY = scrollView.contentSize.height - scrollView.Height
let offsetY = min(0, begainY - scrollView.contentOffset.y)
view.Y = offsetY
// 拖拽比例
self.currentCompleted = min(max(0, fabs(offsetY) / 200), 1);
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
oldContentOffsetY = scrollView.contentOffset.y
if currentCompleted > 0.35 {
if let navigationController = self.navigationController {
isDismissAnimation = false
navigationController.popViewController(animated: true)
}
}
}
}
// MARK: - UINavigationControllerDelegate
extension AHClassWebViewController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
switch operation {
case .pop:
isCustomTranstion = true
if isDismissAnimation {
return AHClosePopTranstion()
} else {
return AHPopTranstion()
}
default:
return nil
}
}
}
| mit | 4dae58a19681f209efbb973584452ea1 | 35.930314 | 246 | 0.58732 | 5.267893 | false | false | false | false |
hyperoslo/CalendarKit | Source/Timeline/TimelineView.swift | 1 | 19028 | import UIKit
public protocol TimelineViewDelegate: AnyObject {
func timelineView(_ timelineView: TimelineView, didTapAt date: Date)
func timelineView(_ timelineView: TimelineView, didLongPressAt date: Date)
func timelineView(_ timelineView: TimelineView, didTap event: EventView)
func timelineView(_ timelineView: TimelineView, didLongPress event: EventView)
}
public final class TimelineView: UIView {
public weak var delegate: TimelineViewDelegate?
public var date = Date() {
didSet {
setNeedsLayout()
}
}
private var currentTime: Date {
return Date()
}
private var eventViews = [EventView]()
public private(set) var regularLayoutAttributes = [EventLayoutAttributes]()
public private(set) var allDayLayoutAttributes = [EventLayoutAttributes]()
public var layoutAttributes: [EventLayoutAttributes] {
set {
// update layout attributes by separating allday from non all day events
allDayLayoutAttributes.removeAll()
regularLayoutAttributes.removeAll()
for anEventLayoutAttribute in newValue {
let eventDescriptor = anEventLayoutAttribute.descriptor
if eventDescriptor.isAllDay {
allDayLayoutAttributes.append(anEventLayoutAttribute)
} else {
regularLayoutAttributes.append(anEventLayoutAttribute)
}
}
recalculateEventLayout()
prepareEventViews()
allDayView.events = allDayLayoutAttributes.map { $0.descriptor }
allDayView.isHidden = allDayLayoutAttributes.count == 0
allDayView.scrollToBottom()
setNeedsLayout()
}
get {
return allDayLayoutAttributes + regularLayoutAttributes
}
}
private var pool = ReusePool<EventView>()
public var firstEventYPosition: CGFloat? {
let first = regularLayoutAttributes.sorted{$0.frame.origin.y < $1.frame.origin.y}.first
guard let firstEvent = first else {return nil}
let firstEventPosition = firstEvent.frame.origin.y
let beginningOfDayPosition = dateToY(date)
return max(firstEventPosition, beginningOfDayPosition)
}
private lazy var nowLine: CurrentTimeIndicator = CurrentTimeIndicator()
private var allDayViewTopConstraint: NSLayoutConstraint?
private lazy var allDayView: AllDayView = {
let allDayView = AllDayView(frame: CGRect.zero)
allDayView.translatesAutoresizingMaskIntoConstraints = false
addSubview(allDayView)
self.allDayViewTopConstraint = allDayView.topAnchor.constraint(equalTo: topAnchor, constant: 0)
self.allDayViewTopConstraint?.isActive = true
allDayView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0).isActive = true
allDayView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0).isActive = true
return allDayView
}()
var allDayViewHeight: CGFloat {
return allDayView.bounds.height
}
var style = TimelineStyle()
private var horizontalEventInset: CGFloat = 3
public var fullHeight: CGFloat {
return style.verticalInset * 2 + style.verticalDiff * 24
}
public var calendarWidth: CGFloat {
return bounds.width - style.leadingInset
}
public private(set) var is24hClock = true {
didSet {
setNeedsDisplay()
}
}
public var calendar: Calendar = Calendar.autoupdatingCurrent {
didSet {
snappingBehavior = snappingBehaviorType.init(calendar)
nowLine.calendar = calendar
regenerateTimeStrings()
setNeedsLayout()
}
}
// TODO: Make a public API
public var snappingBehaviorType: EventEditingSnappingBehavior.Type = SnapTo15MinuteIntervals.self
lazy var snappingBehavior: EventEditingSnappingBehavior = snappingBehaviorType.init(calendar)
private var times: [String] {
return is24hClock ? _24hTimes : _12hTimes
}
private lazy var _12hTimes: [String] = TimeStringsFactory(calendar).make12hStrings()
private lazy var _24hTimes: [String] = TimeStringsFactory(calendar).make24hStrings()
private func regenerateTimeStrings() {
let factory = TimeStringsFactory(calendar)
_12hTimes = factory.make12hStrings()
_24hTimes = factory.make24hStrings()
}
public lazy var longPressGestureRecognizer = UILongPressGestureRecognizer(target: self,
action: #selector(longPress(_:)))
public lazy var tapGestureRecognizer = UITapGestureRecognizer(target: self,
action: #selector(tap(_:)))
private var isToday: Bool {
return calendar.isDateInToday(date)
}
// MARK: - Initialization
public init() {
super.init(frame: .zero)
frame.size.height = fullHeight
configure()
}
override public init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
private func configure() {
contentScaleFactor = 1
layer.contentsScale = 1
contentMode = .redraw
backgroundColor = .white
addSubview(nowLine)
// Add long press gesture recognizer
addGestureRecognizer(longPressGestureRecognizer)
addGestureRecognizer(tapGestureRecognizer)
}
// MARK: - Event Handling
@objc private func longPress(_ gestureRecognizer: UILongPressGestureRecognizer) {
if (gestureRecognizer.state == .began) {
// Get timeslot of gesture location
let pressedLocation = gestureRecognizer.location(in: self)
if let eventView = findEventView(at: pressedLocation) {
delegate?.timelineView(self, didLongPress: eventView)
} else {
delegate?.timelineView(self, didLongPressAt: yToDate(pressedLocation.y))
}
}
}
@objc private func tap(_ sender: UITapGestureRecognizer) {
let pressedLocation = sender.location(in: self)
if let eventView = findEventView(at: pressedLocation) {
delegate?.timelineView(self, didTap: eventView)
} else {
delegate?.timelineView(self, didTapAt: yToDate(pressedLocation.y))
}
}
private func findEventView(at point: CGPoint) -> EventView? {
for eventView in allDayView.eventViews {
let frame = eventView.convert(eventView.bounds, to: self)
if frame.contains(point) {
return eventView
}
}
for eventView in eventViews {
let frame = eventView.frame
if frame.contains(point) {
return eventView
}
}
return nil
}
/**
Custom implementation of the hitTest method is needed for the tap gesture recognizers
located in the AllDayView to work.
Since the AllDayView could be outside of the Timeline's bounds, the touches to the EventViews
are ignored.
In the custom implementation the method is recursively invoked for all of the subviews,
regardless of their position in relation to the Timeline's bounds.
*/
public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
for subview in allDayView.subviews {
if let subSubView = subview.hitTest(convert(point, to: subview), with: event) {
return subSubView
}
}
return super.hitTest(point, with: event)
}
// MARK: - Style
public func updateStyle(_ newStyle: TimelineStyle) {
style = newStyle
allDayView.updateStyle(style.allDayStyle)
nowLine.updateStyle(style.timeIndicator)
switch style.dateStyle {
case .twelveHour:
is24hClock = false
case .twentyFourHour:
is24hClock = true
default:
is24hClock = calendar.locale?.uses24hClock() ?? Locale.autoupdatingCurrent.uses24hClock()
}
backgroundColor = style.backgroundColor
setNeedsDisplay()
}
// MARK: - Background Pattern
public var accentedDate: Date?
override public func draw(_ rect: CGRect) {
super.draw(rect)
var hourToRemoveIndex = -1
var accentedHour = -1
var accentedMinute = -1
if let accentedDate = accentedDate {
accentedHour = snappingBehavior.accentedHour(for: accentedDate)
accentedMinute = snappingBehavior.accentedMinute(for: accentedDate)
}
if isToday {
let minute = component(component: .minute, from: currentTime)
let hour = component(component: .hour, from: currentTime)
if minute > 39 {
hourToRemoveIndex = hour + 1
} else if minute < 21 {
hourToRemoveIndex = hour
}
}
let mutableParagraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
mutableParagraphStyle.lineBreakMode = .byWordWrapping
mutableParagraphStyle.alignment = .right
let paragraphStyle = mutableParagraphStyle.copy() as! NSParagraphStyle
let attributes = [NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.foregroundColor: self.style.timeColor,
NSAttributedString.Key.font: style.font] as [NSAttributedString.Key : Any]
let scale = UIScreen.main.scale
let hourLineHeight = 1 / UIScreen.main.scale
let center: CGFloat
if Int(scale) % 2 == 0 {
center = 1 / (scale * 2)
} else {
center = 0
}
let offset = 0.5 - center
for (hour, time) in times.enumerated() {
let rightToLeft = UIView.userInterfaceLayoutDirection(for: semanticContentAttribute) == .rightToLeft
let hourFloat = CGFloat(hour)
let context = UIGraphicsGetCurrentContext()
context!.interpolationQuality = .none
context?.saveGState()
context?.setStrokeColor(style.separatorColor.cgColor)
context?.setLineWidth(hourLineHeight)
let xStart: CGFloat = {
if rightToLeft {
return bounds.width - 53
} else {
return 53
}
}()
let xEnd: CGFloat = {
if rightToLeft {
return 0
} else {
return bounds.width
}
}()
let y = style.verticalInset + hourFloat * style.verticalDiff + offset
context?.beginPath()
context?.move(to: CGPoint(x: xStart, y: y))
context?.addLine(to: CGPoint(x: xEnd, y: y))
context?.strokePath()
context?.restoreGState()
if hour == hourToRemoveIndex { continue }
let fontSize = style.font.pointSize
let timeRect: CGRect = {
var x: CGFloat
if rightToLeft {
x = bounds.width - 53
} else {
x = 2
}
return CGRect(x: x,
y: hourFloat * style.verticalDiff + style.verticalInset - 7,
width: style.leadingInset - 8,
height: fontSize + 2)
}()
let timeString = NSString(string: time)
timeString.draw(in: timeRect, withAttributes: attributes)
if accentedMinute == 0 {
continue
}
if hour == accentedHour {
var x: CGFloat
if UIView.userInterfaceLayoutDirection(for: semanticContentAttribute) == .rightToLeft {
x = bounds.width - (style.leadingInset + 7)
} else {
x = 2
}
let timeRect = CGRect(x: x, y: hourFloat * style.verticalDiff + style.verticalInset - 7 + style.verticalDiff * (CGFloat(accentedMinute) / 60),
width: style.leadingInset - 8, height: fontSize + 2)
let timeString = NSString(string: ":\(accentedMinute)")
timeString.draw(in: timeRect, withAttributes: attributes)
}
}
}
// MARK: - Layout
override public func layoutSubviews() {
super.layoutSubviews()
recalculateEventLayout()
layoutEvents()
layoutNowLine()
layoutAllDayEvents()
}
private func layoutNowLine() {
if !isToday {
nowLine.alpha = 0
} else {
bringSubviewToFront(nowLine)
nowLine.alpha = 1
let size = CGSize(width: bounds.size.width, height: 20)
let rect = CGRect(origin: CGPoint.zero, size: size)
nowLine.date = currentTime
nowLine.frame = rect
nowLine.center.y = dateToY(currentTime)
}
}
private func layoutEvents() {
if eventViews.isEmpty { return }
for (idx, attributes) in regularLayoutAttributes.enumerated() {
let descriptor = attributes.descriptor
let eventView = eventViews[idx]
eventView.frame = attributes.frame
var x: CGFloat
if UIView.userInterfaceLayoutDirection(for: semanticContentAttribute) == .rightToLeft {
x = bounds.width - attributes.frame.minX - attributes.frame.width
} else {
x = attributes.frame.minX
}
eventView.frame = CGRect(x: x,
y: attributes.frame.minY,
width: attributes.frame.width - style.eventGap,
height: attributes.frame.height - style.eventGap)
eventView.updateWithDescriptor(event: descriptor)
}
}
private func layoutAllDayEvents() {
//add day view needs to be in front of the nowLine
bringSubviewToFront(allDayView)
}
/**
This will keep the allDayView as a staionary view in its superview
- parameter yValue: since the superview is a scrollView, `yValue` is the
`contentOffset.y` of the scroll view
*/
public func offsetAllDayView(by yValue: CGFloat) {
if let topConstraint = self.allDayViewTopConstraint {
topConstraint.constant = yValue
layoutIfNeeded()
}
}
private func recalculateEventLayout() {
// only non allDay events need their frames to be set
let sortedEvents = self.regularLayoutAttributes.sorted { (attr1, attr2) -> Bool in
let start1 = attr1.descriptor.startDate
let start2 = attr2.descriptor.startDate
return start1 < start2
}
var groupsOfEvents = [[EventLayoutAttributes]]()
var overlappingEvents = [EventLayoutAttributes]()
for event in sortedEvents {
if overlappingEvents.isEmpty {
overlappingEvents.append(event)
continue
}
let longestEvent = overlappingEvents.sorted { (attr1, attr2) -> Bool in
var period = attr1.descriptor.datePeriod
let period1 = calendar.dateComponents([.second], from: period.lowerBound, to: period.upperBound).second!
period = attr2.descriptor.datePeriod
let period2 = calendar.dateComponents([.second], from: period.lowerBound, to: period.upperBound).second!
return period1 > period2
}
.first!
if style.eventsWillOverlap {
guard let earliestEvent = overlappingEvents.first?.descriptor.startDate else { continue }
let dateInterval = getDateInterval(date: earliestEvent)
if event.descriptor.datePeriod.contains(dateInterval.lowerBound) {
overlappingEvents.append(event)
continue
}
} else {
let lastEvent = overlappingEvents.last!
if (longestEvent.descriptor.datePeriod.overlaps(event.descriptor.datePeriod) && (longestEvent.descriptor.endDate != event.descriptor.startDate || style.eventGap <= 0.0)) ||
(lastEvent.descriptor.datePeriod.overlaps(event.descriptor.datePeriod) && (lastEvent.descriptor.endDate != event.descriptor.startDate || style.eventGap <= 0.0)) {
overlappingEvents.append(event)
continue
}
}
groupsOfEvents.append(overlappingEvents)
overlappingEvents = [event]
}
groupsOfEvents.append(overlappingEvents)
overlappingEvents.removeAll()
for overlappingEvents in groupsOfEvents {
let totalCount = CGFloat(overlappingEvents.count)
for (index, event) in overlappingEvents.enumerated() {
let startY = dateToY(event.descriptor.datePeriod.lowerBound)
let endY = dateToY(event.descriptor.datePeriod.upperBound)
let floatIndex = CGFloat(index)
let x = style.leadingInset + floatIndex / totalCount * calendarWidth
let equalWidth = calendarWidth / totalCount
event.frame = CGRect(x: x, y: startY, width: equalWidth, height: endY - startY)
}
}
}
private func prepareEventViews() {
pool.enqueue(views: eventViews)
eventViews.removeAll()
for _ in regularLayoutAttributes {
let newView = pool.dequeue()
if newView.superview == nil {
addSubview(newView)
}
eventViews.append(newView)
}
}
public func prepareForReuse() {
pool.enqueue(views: eventViews)
eventViews.removeAll()
setNeedsDisplay()
}
// MARK: - Helpers
public func dateToY(_ date: Date) -> CGFloat {
let provisionedDate = date.dateOnly(calendar: calendar)
let timelineDate = self.date.dateOnly(calendar: calendar)
var dayOffset: CGFloat = 0
if provisionedDate > timelineDate {
// Event ending the next day
dayOffset += 1
} else if provisionedDate < timelineDate {
// Event starting the previous day
dayOffset -= 1
}
let fullTimelineHeight = 24 * style.verticalDiff
let hour = component(component: .hour, from: date)
let minute = component(component: .minute, from: date)
let hourY = CGFloat(hour) * style.verticalDiff + style.verticalInset
let minuteY = CGFloat(minute) * style.verticalDiff / 60
return hourY + minuteY + fullTimelineHeight * dayOffset
}
public func yToDate(_ y: CGFloat) -> Date {
let timeValue = y - style.verticalInset
var hour = Int(timeValue / style.verticalDiff)
let fullHourPoints = CGFloat(hour) * style.verticalDiff
let minuteDiff = timeValue - fullHourPoints
let minute = Int(minuteDiff / style.verticalDiff * 60)
var dayOffset = 0
if hour > 23 {
dayOffset += 1
hour -= 24
} else if hour < 0 {
dayOffset -= 1
hour += 24
}
let offsetDate = calendar.date(byAdding: DateComponents(day: dayOffset),
to: date)!
let newDate = calendar.date(bySettingHour: hour,
minute: minute.clamped(to: 0...59),
second: 0,
of: offsetDate)
return newDate!
}
private func component(component: Calendar.Component, from date: Date) -> Int {
return calendar.component(component, from: date)
}
private func getDateInterval(date: Date) -> ClosedRange<Date> {
let earliestEventMintues = component(component: .minute, from: date)
let splitMinuteInterval = style.splitMinuteInterval
let minute = component(component: .minute, from: date)
let minuteRange = (minute / splitMinuteInterval) * splitMinuteInterval
let beginningRange = calendar.date(byAdding: .minute, value: -(earliestEventMintues - minuteRange), to: date)!
let endRange = calendar.date(byAdding: .minute, value: splitMinuteInterval, to: beginningRange)!
return beginningRange ... endRange
}
}
| mit | f02d75d380ecba39921fe6216dab66fc | 32.265734 | 180 | 0.654457 | 4.695953 | false | false | false | false |
Eonil/ClangWrapper.Swift | ClangWrapper/Cursor+CrossReferencing.swift | 1 | 2005 | //
// Cursor+CrossReferencing.swift
// ClangWrapper
//
// Created by Hoon H. on 2015/01/21.
// Copyright (c) 2015 Eonil. All rights reserved.
//
public extension Cursor {
/// Retrieve a name for the entity referenced by this cursor.
public var spelling:String {
get {
let s = clang_getCursorSpelling(raw)
let s1 = toSwiftString(s, disposeCXString: true)
return s1!
}
}
/// Retrieve the display name for the entity referenced by this cursor.
public var displayName:String? {
get {
let s = clang_getCursorDisplayName(raw)
let s1 = toSwiftString(s, disposeCXString: true)
return s1
}
}
/// For a cursor that is a reference, retrieve a cursor representing the entity that it references.
public var referenced:Cursor {
get {
let r = clang_getCursorReferenced(raw)
return Cursor(index: index, raw: r)
}
}
/// For a cursor that is either a reference to or a declaration of some entity, retrieve a cursor that describes the definition of that entity.
public var definition:Cursor {
get {
let r = clang_getCursorDefinition(raw)
return Cursor(index: index, raw: r)
}
}
/// Determine whether the declaration pointed to by this cursor is also a definition of that entity.
public var isDefinition:Bool {
get {
let r = clang_isCursorDefinition(raw)
return r != 0
}
}
/// Retrieve the canonical cursor corresponding to the given cursor.
public var canonicalCursor:Cursor {
get {
let r = clang_getCanonicalCursor(raw)
return Cursor(index: index, raw: r)
}
}
public var commentRange:SourceRange {
get {
let r = clang_Cursor_getCommentRange(raw)
return SourceRange(raw: r)
}
}
public var rawCommentText:String? {
get {
let s = clang_Cursor_getRawCommentText(raw)
let s1 = toSwiftString(s, disposeCXString: true)
return s1
}
}
public var briefCommentText:String? {
get {
let s = clang_Cursor_getBriefCommentText(raw)
let s1 = toSwiftString(s, disposeCXString: true)
return s1
}
}
} | mit | 4358928b3901b9dc980b65cf04338ad0 | 24.075 | 144 | 0.698753 | 3.028701 | false | false | false | false |
mogstad/liechtensteinklamm | example/ui_view+constraints.swift | 1 | 1782 | import UIKit
extension UIView {
func addConstraintsForFullscreenSubview(subview: UIView) {
subview.translatesAutoresizingMaskIntoConstraints = false
let horizontalContraint = NSLayoutConstraint.constraintsWithVisualFormat("H:|[subview]|",
options: .DirectionLeadingToTrailing,
metrics: nil,
views: ["subview" : subview])
let verticalContraint = NSLayoutConstraint.constraintsWithVisualFormat("V:|[subview]|",
options: .DirectionLeadingToTrailing,
metrics: nil,
views: ["subview" : subview])
self.addConstraints(horizontalContraint)
self.addConstraints(verticalContraint)
}
func addConstraintsForCenteredSubview(subview: UIView) {
subview.translatesAutoresizingMaskIntoConstraints = false
let verticalContraint = NSLayoutConstraint(
item: subview,
attribute: .CenterY,
relatedBy: .Equal,
toItem: self,
attribute: .CenterY,
multiplier: 1.0,
constant: 0)
let horizontalContraint = NSLayoutConstraint(
item: subview,
attribute: .CenterX,
relatedBy: .Equal,
toItem: self,
attribute: .CenterX,
multiplier: 1.0,
constant: 0)
let heightContraint = NSLayoutConstraint(
item: subview,
attribute: .Height,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1.0,
constant: CGRectGetHeight(subview.frame))
let widthContraint = NSLayoutConstraint(
item: subview,
attribute: .Width,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1.0,
constant: CGRectGetWidth(subview.frame))
self.addConstraints([horizontalContraint, verticalContraint, heightContraint, widthContraint])
}
}
| mit | a0251820422ab5b4df15fac21c735032 | 26 | 98 | 0.684624 | 5.180233 | false | false | false | false |
ChatSecure/ChatSecure-Push-iOS | ChatSecurePushExample/ChatSecurePushExample/ViewController.swift | 1 | 1038 | //
// ViewController.swift
// ChatSecurePushExample
//
// Created by David Chiles on 7/7/15.
// Copyright (c) 2015 David Chiles. All rights reserved.
//
import UIKit
import ChatSecure_Push_iOS
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var usernameTextField: UITextField!
@IBOutlet var passwordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.usernameTextField.delegate = self
self.passwordTextField.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return false
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? AccountDetailViewController {
if let username = self.usernameTextField.text {
vc.account = Account(username:username)
vc.password = self.passwordTextField.text
}
}
}
}
| gpl-3.0 | 271cbdb81d8033204a88860036e4736b | 26.315789 | 71 | 0.653179 | 5.1133 | false | false | false | false |
rudkx/swift | validation-test/compiler_crashers_2_fixed/0083-rdar31163470-2.swift | 1 | 607 | // RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-inferred-signatures=verify 2>&1 | %FileCheck %s
// RUN: %target-swift-frontend -primary-file %s -emit-ir -requirement-machine-inferred-signatures=verify
protocol C {
associatedtype I
}
protocol PST {
associatedtype LT : C
}
protocol SL {
associatedtype S : PST
}
struct PEN<_S : PST> : SL {
typealias S = _S
let l: _S.LT.I
}
struct PE<N : SL> {
let n: N
// CHECK-LABEL: .c@
// CHECK-NEXT: Generic signature: <N, S where N == PEN<S>, S : PST>
static func c<S>(_: PE<N>) where N == PEN<S> {}
}
| apache-2.0 | 8363ccca442f5af19ca0a958c496c5d3 | 22.346154 | 139 | 0.654036 | 2.97549 | false | false | false | false |
lanjing99/iOSByTutorials | iOS 8 by tutorials/Chapter 05 - Transition Coordinator Updates/KhromaLike/KhromaLike/DataLayer/ColorSwatch.swift | 1 | 2532 | /*
* Copyright (c) 2014 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
class ColorSwatch {
var name: String
var color: UIColor
private let formatString = "0.2"
init(name: String, color: UIColor) {
self.name = name
self.color = color
}
// Color string properties
var hexString: String {
return color.hexString()
}
var rgbString: String {
let rgbArray = color.rgbaArray() as! [Double]
return "(\(rgbArray[0].rw_format(formatString)), \(rgbArray[1].rw_format(formatString)), " +
"\(rgbArray[2].rw_format(formatString)))"
}
var cmykString: String {
let cmykArray = color.cmykArray() as! [Double]
return "(\(cmykArray[0].rw_format(formatString)), \(cmykArray[1].rw_format(formatString)), " +
"\(cmykArray[2].rw_format(formatString)), \(cmykArray[3].rw_format(formatString)))"
}
var hsbString: String {
let hsbArray = color.hsbaArray() as! [Double]
return "(\(hsbArray[0].rw_format(formatString)), \(hsbArray[1].rw_format(formatString)), " +
"\(hsbArray[2].rw_format(formatString)))"
}
var cielabString: String {
let cielabArray = color.CIE_LabArray() as! [Double]
return "(\(cielabArray[0].rw_format(formatString)), \(cielabArray[1].rw_format(formatString)), " +
"\(cielabArray[2].rw_format(formatString)))"
}
// Color scheme array function
func relatedColors() -> [UIColor] {
return self.color.colorSchemeOfType(ColorScheme.Analagous) as! [UIColor]
}
} | mit | a3a83fa1c2d1a73ba138a2e82d5748a5 | 34.676056 | 102 | 0.704186 | 3.925581 | false | false | false | false |
pj4533/OpenPics | Pods/AlamofireImage/Source/ImageCache.swift | 4 | 12738 | // ImageCache.swift
//
// Copyright (c) 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 Alamofire
import Foundation
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import Cocoa
#endif
// MARK: ImageCache
/// The `ImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache.
public protocol ImageCache {
/// Adds the image to the cache with the given identifier.
func addImage(image: Image, withIdentifier identifier: String)
/// Removes the image from the cache matching the given identifier.
func removeImageWithIdentifier(identifier: String) -> Bool
/// Removes all images stored in the cache.
func removeAllImages() -> Bool
/// Returns the image in the cache associated with the given identifier.
func imageWithIdentifier(identifier: String) -> Image?
}
/// The `ImageRequestCache` protocol extends the `ImageCache` protocol by adding methods for adding, removing and
/// fetching images from a cache given an `NSURLRequest` and additional identifier.
public protocol ImageRequestCache: ImageCache {
/// Adds the image to the cache using an identifier created from the request and additional identifier.
func addImage(image: Image, forRequest request: NSURLRequest, withAdditionalIdentifier identifier: String?)
/// Removes the image from the cache using an identifier created from the request and additional identifier.
func removeImageForRequest(request: NSURLRequest, withAdditionalIdentifier identifier: String?) -> Bool
/// Returns the image from the cache associated with an identifier created from the request and additional identifier.
func imageForRequest(request: NSURLRequest, withAdditionalIdentifier identifier: String?) -> Image?
}
// MARK: -
/// The `AutoPurgingImageCache` in an in-memory image cache used to store images up to a given memory capacity. When
/// the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously
/// purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the
/// internal access date of the image is updated.
public class AutoPurgingImageCache: ImageRequestCache {
private class CachedImage {
let image: Image
let identifier: String
let totalBytes: UInt64
var lastAccessDate: NSDate
init(_ image: Image, identifier: String) {
self.image = image
self.identifier = identifier
self.lastAccessDate = NSDate()
self.totalBytes = {
#if os(iOS) || os(tvOS) || os(watchOS)
let size = CGSize(width: image.size.width * image.scale, height: image.size.height * image.scale)
#elseif os(OSX)
let size = CGSize(width: image.size.width, height: image.size.height)
#endif
let bytesPerPixel: CGFloat = 4.0
let bytesPerRow = size.width * bytesPerPixel
let totalBytes = UInt64(bytesPerRow) * UInt64(size.height)
return totalBytes
}()
}
func accessImage() -> Image {
lastAccessDate = NSDate()
return image
}
}
// MARK: Properties
/// The current total memory usage in bytes of all images stored within the cache.
public var memoryUsage: UInt64 {
var memoryUsage: UInt64 = 0
dispatch_sync(synchronizationQueue) { memoryUsage = self.currentMemoryUsage }
return memoryUsage
}
/// The total memory capacity of the cache in bytes.
public let memoryCapacity: UInt64
/// The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory
/// capacity drops below this limit.
public let preferredMemoryUsageAfterPurge: UInt64
private let synchronizationQueue: dispatch_queue_t
private var cachedImages: [String: CachedImage]
private var currentMemoryUsage: UInt64
// MARK: Initialization
/**
Initialies the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage
after purge limit.
Please note, the memory capacity must always be greater than or equal to the preferred memory usage after purge.
- parameter memoryCapacity: The total memory capacity of the cache in bytes. `100 MB` by default.
- parameter preferredMemoryUsageAfterPurge: The preferred memory usage after purge in bytes. `60 MB` by default.
- returns: The new `AutoPurgingImageCache` instance.
*/
public init(memoryCapacity: UInt64 = 100 * 1024 * 1024, preferredMemoryUsageAfterPurge: UInt64 = 60 * 1024 * 1024) {
self.memoryCapacity = memoryCapacity
self.preferredMemoryUsageAfterPurge = preferredMemoryUsageAfterPurge
precondition(
memoryCapacity >= preferredMemoryUsageAfterPurge,
"The `memoryCapacity` must be greater than or equal to `preferredMemoryUsageAfterPurge`"
)
self.cachedImages = [:]
self.currentMemoryUsage = 0
self.synchronizationQueue = {
let name = String(format: "com.alamofire.autopurgingimagecache-%08%08", arc4random(), arc4random())
return dispatch_queue_create(name, DISPATCH_QUEUE_CONCURRENT)
}()
#if os(iOS)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "removeAllImages",
name: UIApplicationDidReceiveMemoryWarningNotification,
object: nil
)
#endif
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: Add Image to Cache
/**
Adds the image to the cache using an identifier created from the request and optional identifier.
- parameter image: The image to add to the cache.
- parameter request: The request used to generate the image's unique identifier.
- parameter identifier: The additional identifier to append to the image's unique identifier.
*/
public func addImage(image: Image, forRequest request: NSURLRequest, withAdditionalIdentifier identifier: String? = nil) {
let requestIdentifier = imageCacheKeyFromURLRequest(request, withAdditionalIdentifier: identifier)
addImage(image, withIdentifier: requestIdentifier)
}
/**
Adds the image to the cache with the given identifier.
- parameter image: The image to add to the cache.
- parameter identifier: The identifier to use to uniquely identify the image.
*/
public func addImage(image: Image, withIdentifier identifier: String) {
dispatch_barrier_async(synchronizationQueue) {
let cachedImage = CachedImage(image, identifier: identifier)
if let previousCachedImage = self.cachedImages[identifier] {
self.currentMemoryUsage -= previousCachedImage.totalBytes
}
self.cachedImages[identifier] = cachedImage
self.currentMemoryUsage += cachedImage.totalBytes
}
dispatch_barrier_async(synchronizationQueue) {
if self.currentMemoryUsage > self.memoryCapacity {
let bytesToPurge = self.currentMemoryUsage - self.preferredMemoryUsageAfterPurge
var sortedImages = [CachedImage](self.cachedImages.values)
sortedImages.sortInPlace {
let date1 = $0.lastAccessDate
let date2 = $1.lastAccessDate
return date1.timeIntervalSinceDate(date2) < 0.0
}
var bytesPurged = UInt64(0)
for cachedImage in sortedImages {
self.cachedImages.removeValueForKey(cachedImage.identifier)
bytesPurged += cachedImage.totalBytes
if bytesPurged >= bytesToPurge {
break
}
}
self.currentMemoryUsage -= bytesPurged
}
}
}
// MARK: Remove Image from Cache
/**
Removes the image from the cache using an identifier created from the request and optional identifier.
- parameter request: The request used to generate the image's unique identifier.
- parameter identifier: The additional identifier to append to the image's unique identifier.
- returns: `true` if the image was removed, `false` otherwise.
*/
public func removeImageForRequest(request: NSURLRequest, withAdditionalIdentifier identifier: String?) -> Bool {
let requestIdentifier = imageCacheKeyFromURLRequest(request, withAdditionalIdentifier: identifier)
return removeImageWithIdentifier(requestIdentifier)
}
/**
Removes the image from the cache matching the given identifier.
- parameter identifier: The unique identifier for the image.
- returns: `true` if the image was removed, `false` otherwise.
*/
public func removeImageWithIdentifier(identifier: String) -> Bool {
var removed = false
dispatch_barrier_async(synchronizationQueue) {
if let cachedImage = self.cachedImages.removeValueForKey(identifier) {
self.currentMemoryUsage -= cachedImage.totalBytes
removed = true
}
}
return removed
}
/**
Removes all images stored in the cache.
- returns: `true` if images were removed from the cache, `false` otherwise.
*/
@objc public func removeAllImages() -> Bool {
var removed = false
dispatch_sync(synchronizationQueue) {
if !self.cachedImages.isEmpty {
self.cachedImages.removeAll()
self.currentMemoryUsage = 0
removed = true
}
}
return removed
}
// MARK: Fetch Image from Cache
/**
Returns the image from the cache associated with an identifier created from the request and optional identifier.
- parameter request: The request used to generate the image's unique identifier.
- parameter identifier: The additional identifier to append to the image's unique identifier.
- returns: The image if it is stored in the cache, `nil` otherwise.
*/
public func imageForRequest(request: NSURLRequest, withAdditionalIdentifier identifier: String? = nil) -> Image? {
let requestIdentifier = imageCacheKeyFromURLRequest(request, withAdditionalIdentifier: identifier)
return imageWithIdentifier(requestIdentifier)
}
/**
Returns the image in the cache associated with the given identifier.
- parameter identifier: The unique identifier for the image.
- returns: The image if it is stored in the cache, `nil` otherwise.
*/
public func imageWithIdentifier(identifier: String) -> Image? {
var image: Image?
dispatch_sync(synchronizationQueue) {
if let cachedImage = self.cachedImages[identifier] {
image = cachedImage.accessImage()
}
}
return image
}
// MARK: Private - Helper Methods
private func imageCacheKeyFromURLRequest(
request: NSURLRequest,
withAdditionalIdentifier identifier: String?)
-> String
{
var key = request.URLString
if let identifier = identifier {
key += "-\(identifier)"
}
return key
}
}
| gpl-3.0 | 2144aa03e2ee4c44d0c827043c245442 | 37.6 | 126 | 0.667373 | 5.4693 | false | false | false | false |
tripleCC/GanHuoCode | GanHuo/Util/TPCJSPatchManager.swift | 1 | 4049 | //
// TPCJSPatchManager.swift
// JSPathManager
//
// Created by tripleCC on 16/4/21.
// Copyright © 2016年 tripleCC. All rights reserved.
//
import UIKit
import JSPatch
import Alamofire
class TPCJSPatchManager: NSObject {
struct Static {
static let TPCJSPatchManagerAllowMaxCrashTime = 1
static let TPCJSPatchManagerJSVersoinKey = "TPCJSPatchManagerJSVersoinKey"
static let TPCJSPatchManagerFetchDateKey = "TPCJSPatchManagerFetchDateKey"
static let TPCJSPatchManagerEvaluateJSFailTimeKey = "TPCJSPatchManagerEvaluateJSFailTimeKey"
static let TPCJSPatchFileName = "TPCJSPatchHotfix"
static let TPCJSPatchFileDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
}
private var jsVersion: String {
get {
return NSUserDefaults.standardUserDefaults().objectForKey(Static.TPCJSPatchManagerJSVersoinKey) as? String ?? "0"
}
set {
NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: Static.TPCJSPatchManagerJSVersoinKey)
}
}
private var evaluateJSFailTime: Int {
get {
return NSUserDefaults.standardUserDefaults().objectForKey(Static.TPCJSPatchManagerEvaluateJSFailTimeKey) as? Int ?? 0
}
set {
NSUserDefaults.standardUserDefaults().setInteger(newValue, forKey: Static.TPCJSPatchManagerEvaluateJSFailTimeKey)
}
}
private var fetchDate: NSDate? {
get {
return NSUserDefaults.standardUserDefaults().objectForKey(Static.TPCJSPatchManagerFetchDateKey) as? NSDate
}
set {
NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: Static.TPCJSPatchManagerFetchDateKey)
}
}
private var jsScriptPath: String {
return Static.TPCJSPatchFileDirectory + "/" + Static.TPCJSPatchFileName + ".js"
}
static let shareManager = TPCJSPatchManager()
func start() {
guard evaluateJSFailTime < Static.TPCJSPatchManagerAllowMaxCrashTime else { return }
startWithJSName(Static.TPCJSPatchFileName)
}
private func recordFailTimeWithAction(action: (() -> Void)) {
objc_sync_enter(self)
evaluateJSFailTime += 1
action()
evaluateJSFailTime -= 1
objc_sync_exit(self)
}
private func startWithJSName(name: String) {
do {
let jsScript = try String(contentsOfFile: jsScriptPath)
JPEngine.startEngine()
recordFailTimeWithAction {
JPEngine.evaluateScript(jsScript)
}
} catch {
print(error)
}
}
func handleJSPatchStatusWithURLString(URLString: String, duration: NSTimeInterval) {
let fetchStatusCompletion = { (version: String, jsPath: String) in
self.fetchDate = NSDate()
debugPrint(version, self.jsVersion)
if Float(version) > Float(self.jsVersion) {
TPCNetworkUtil.shareInstance.loadJSPatchFileWithURLString(jsPath, completion: { (jsScript) in
self.evaluateJSFailTime = 0
self.recordFailTimeWithAction {
JPEngine.evaluateScript(jsScript)
}
do {
try jsScript.writeToFile(self.jsScriptPath, atomically: true, encoding: NSUTF8StringEncoding)
self.jsVersion = version
} catch let error {
print(error)
}
})
}
}
func fetchJSPatchStatus() {
TPCNetworkUtil.shareInstance.loadJSPatchStatusWithURLString(URLString, completion: fetchStatusCompletion)
}
if let fetchDate = fetchDate {
if NSDate().timeIntervalSinceDate(fetchDate) > duration {
fetchJSPatchStatus()
}
} else {
fetchJSPatchStatus()
}
}
}
| mit | 25e88c31340b72af70691f89d100c909 | 34.80531 | 130 | 0.625803 | 4.880579 | false | false | false | false |
vibeswift/SXCTAssertions | Source/SXCTAssertions.swift | 1 | 3131 | //
// Copyright 2015 vibeswift, Carsten Klein
//
// 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.
//
//
// SXCTAssertions.swift
// SXCTAssertions
//
// Created by Carsten Klein on 15-03-22.
//
import Foundation
import XCTest
public func SXCTAssertThrows(
@autoclosure(escaping) expression: () -> Void, var message: String? = "",
file: String = __FILE__, line: UInt = __LINE__) {
if message == nil {
message = "expected exception."
}
if !_sxctThrows(expression) {
XCTFail(message!, file: file, line: line)
}
}
public func SXCTAssertThrowsSpecific(
@autoclosure(escaping) expression: () -> Void, exception: NSException.Type,
var message: String? = "", file: String = __FILE__, line: UInt = __LINE__) {
if message == nil {
message = "expected exception of type \(exception)."
}
if !_sxctThrowsSpecific(expression, exception) {
XCTFail(message!, file: file, line: line)
}
}
public func SXCTAssertThrowsSpecificNamed(
@autoclosure(escaping) expression: () -> Void, exception: NSException.Type,
name: String, var message: String? = "", file: String = __FILE__,
line: UInt = __LINE__) {
if message == nil {
message = "expected exception of type \(exception) with name \(name)."
}
if !_sxctThrowsSpecificNamed(expression, exception, name) {
XCTFail(message!, file: file, line: line)
}
}
public func SXCTAssertNoThrow(
@autoclosure(escaping) expression: () -> Void, var message: String? = "",
file: String = __FILE__, line: UInt = __LINE__) {
if message == nil {
message = "unexpected exception."
}
if _sxctThrows(expression) {
XCTFail(message!, file: file, line: line)
}
}
public func SXCTAssertNoThrowSpecific(
@autoclosure(escaping) expression: () -> Void, exception: NSException.Type,
var message: String? = "", file: String = __FILE__, line: UInt = __LINE__) {
if message == nil {
message = "unexpected exception of type \(exception)."
}
if _sxctThrowsSpecific(expression, exception) {
XCTFail(message!, file: file, line: line)
}
}
public func SXCTAssertNoThrowSpecificNamed(
@autoclosure(escaping) expression: () -> Void, exception: NSException.Type,
name: String, var message: String? = "", file: String = __FILE__,
line: UInt = __LINE__) {
if message == nil {
message = "unexpected exception of type \(exception) with name \(name)."
}
if _sxctThrowsSpecificNamed(expression, exception, name) {
XCTFail(message!, file: file, line: line)
}
}
| apache-2.0 | ee0a3443ef99644fb7a62e80ef4cd279 | 30.31 | 80 | 0.642287 | 3.953283 | false | false | false | false |
mlilback/rc2SwiftClient | Networking/ServerResponse.swift | 1 | 6917 | //
// ServerResponse.swift
//
// Copyright © 2016 Mark Lilback. This file is licensed under the ISC license.
//
import Foundation
import MJLLogger
import SwiftyUserDefaults
import Rc2Common
import Model
// MARK: Keys for UserDefaults
extension DefaultsKeys {
static let nextBatchId = DefaultsKey<Int>("NextBatchIdKey")
}
/// operations that can be performed on the server
public enum FileOperation: String {
case Remove = "rm", Rename = "rename", Duplicate = "duplicate"
}
public enum ServerResponse: Hashable {
case error(queryId: Int, error: String)
case echoQuery(queryId: Int, fileId: Int, query: String)
case execComplete(queryId: Int, batchId: Int, images: [SessionImage])
case results(queryId: Int, text: String)
case saveResponse(transId: String)
case fileChanged(changeType: String, fileId: Int, file: AppFile?)
case showOutput(queryId: Int, updatedFile: AppFile)
case variables(single: Bool, variables: [Variable])
case variablesDelta(assigned: [Variable], removed: [String])
case fileOperationResponse(transId: String, operation: FileOperation, result: Result<AppFile?, Rc2Error>)
public func isEcho() -> Bool {
if case .echoQuery = self { return true }
return false
}
// swiftlint:disable cyclomatic_complexity
static func parseResponse(_ jsonObj: JSON) -> ServerResponse? {
guard let msg = try? jsonObj.getString(at: "msg") else {
Log.warn("failed to parse 'msg' from server response", .session)
return nil
}
let queryId = jsonObj.getOptionalInt(at: "queryId") ?? 0
switch msg {
//TODO: once appserver updated, need to handle these separately instead of testing on images
case "results", "execComplete":
guard let imagesJson = try? jsonObj.getArray(at: "images") else {
return ServerResponse.results(queryId: queryId, text: jsonObj.getOptionalString(at: "string", or: ""))
}
//we override batchId because it is per-session, we need it unique across sessions
let batchId = max(UserDefaults.standard[.nextBatchId], 1)
let images = imagesJson.flatMap({ try? SessionImage(json: $0, batchId: batchId) })
UserDefaults.standard[.nextBatchId] = batchId + 1
return ServerResponse.execComplete(queryId: queryId, batchId: jsonObj.getOptionalInt(at: "imageBatchId", or: -1), images: images)
case "showOutput":
guard let sfile: AppFile = try? jsonObj.decode(at: "file") else {
Log.warn("failed to decode file parameter to showOutput response", .session)
return nil
}
return ServerResponse.showOutput(queryId: queryId, updatedFile: sfile)
case "error":
return ServerResponse.error(queryId: queryId, error: jsonObj.getOptionalString(at: "error", or: "unknown error"))
case "echo":
guard let fileId = try? jsonObj.getInt(at: "fileId"), let query = try? jsonObj.getString(at: "query") else
{
Log.warn("failed to parse echo response", .session)
return nil
}
return ServerResponse.echoQuery(queryId: queryId, fileId: fileId, query: query)
case "filechanged":
guard let ftype = try? jsonObj.getString(at: "type"), let fileId = try? jsonObj.getInt(at: "fileId") else
{
Log.warn("failed to parse filechanged response", .session)
return nil
}
let file: AppFile? = try? jsonObj.decode(at: "file")
return ServerResponse.fileChanged(changeType: ftype, fileId: fileId, file: file)
case "variables":
return parseVariables(jsonObj: jsonObj)
case "saveResponse":
//TODO: not looking at "success" and handling "error"
return ServerResponse.saveResponse(transId: jsonObj.getOptionalString(at: "transId", or: ""))
case "userid":
return nil //TODO: need to implement
case "fileOpResponse":
return parseFileOpResponse(jsonObj: jsonObj)
default:
Log.warn("unknown message from server:\(msg)", .session)
return nil
}
}
static func parseFileOpResponse(jsonObj: JSON) -> ServerResponse? {
guard let transId = try? jsonObj.getString(at: "transId"),
let opName = try? jsonObj.getString(at: "operation"),
let op = FileOperation(rawValue: opName),
let success = try? jsonObj.getBool(at: "success") else
{
return nil
}
var result: Result<AppFile?, Rc2Error>?
if success {
// (should be impossible since nil is acceptable)
// swiftlint:disable:next force_try
result = Result<AppFile?, Rc2Error>(value: try! jsonObj.decode(at: "file", alongPath: [.missingKeyBecomesNil, .nullBecomesNil], type: AppFile.self))
} else {
result = Result<AppFile?, Rc2Error>(error: parseRemoteError(jsonObj: try? jsonObj.getDictionary(at: "error")))
}
return ServerResponse.fileOperationResponse(transId: transId, operation: op, result: result!)
}
static func parseRemoteError(jsonObj: [String: JSON]?) -> Rc2Error {
guard let jdict = jsonObj, let code = try? jdict["errorCode"]?.getInt(),
let errorCode = code,
let message = try? jdict["errorMessage"]?.getString() ,
let errorMessage = message else
{
Log.warn("server error didn't include code and/or message", .network)
return Rc2Error(type: .websocket, explanation: "invalid server response")
}
let nestedError = WebSocketError(code: errorCode, message: errorMessage)
return Rc2Error(type: .websocket, nested: nestedError, explanation: errorMessage)
}
static func parseVariables(jsonObj: JSON) -> ServerResponse? {
do {
guard jsonObj.getOptionalBool(at: "delta") else {
let jsonArray = try jsonObj.getDictionary(at: "variables")
let vars: [Variable] = try jsonArray.map({ try Variable.variableForJson($0.value) })
return ServerResponse.variables(single: jsonObj.getOptionalBool(at: "single"), variables: vars)
}
let assigned: [Variable] = try jsonObj.getDictionary(at: "variables", "assigned").map({ try Variable.variableForJson($0.value) })
let removed: [String] = try jsonObj.decodedArray(at: "variables", "removed")
return ServerResponse.variablesDelta(assigned: assigned, removed: removed)
} catch {
Log.error("error parsing variable message: \(error)", .session)
}
return nil
}
}
public func == (a: ServerResponse, b: ServerResponse) -> Bool {
switch (a, b) {
case (.error(let q1, let e1), .error(let q2, let e2)):
return q1 == q2 && e1 == e2
case (.echoQuery(let q1, let f1, let s1), .echoQuery(let q2, let f2, let s2)):
return q1 == q2 && f1 == f2 && s1 == s2
case (.execComplete(let q1, let b1, let i1), .execComplete(let q2, let b2, let i2)):
return q1 == q2 && b1 == b2 && i1 == i2
case (.results(let q1, let t1), .results(let q2, let t2)):
return q1 == q2 && t1 == t2
case (.variables(let sn1, let v1), .variables(let sn2, let v2)):
return sn1 == sn2 && v1 == v2
case (.variablesDelta(let a1, let r1), .variablesDelta(let a2, let r2)):
return r1 == r2 && a1 == a2
case (.showOutput(let q1, let f1), .showOutput(let q2, let f2)):
return q1 == q2 && f1.fileId == f2.fileId && f1.version == f2.version
default:
return false
}
}
| isc | 2b31347eb49f92fc9b935fd32381f540 | 41.170732 | 151 | 0.699826 | 3.451098 | false | false | false | false |
zadr/conservatory | Code/Inputs/Cocoa/CGImageBridging.swift | 1 | 1608 | import CoreGraphics
import ImageIO
#if os(iOS)
import MobileCoreServices
#elseif os(OSX)
import CoreServices
#endif
extension CGImage: ImageViewable {
private func data(_ format: CFString) -> UnsafePointer<UInt8> {
let data = CFDataCreateMutable(nil, 0)
let destination = CGImageDestinationCreateWithData(data!, format, 1, nil)!
CGImageDestinationAddImage(destination, self, nil)
CGImageDestinationFinalize(destination)
return CFDataGetBytePtr(data)
}
public var bitmapView: UnsafePointer<UInt8> {
return data(kUTTypeBMP)
}
public var JPEGView: UnsafePointer<UInt8> {
return data(kUTTypeJPEG)
}
public var PNGView: UnsafePointer<UInt8> {
return data(kUTTypePNG)
}
}
extension Image {
public init(image: CGImage) {
// todo: support non-RGBA pixel ordering so these preconditions can go away
precondition(image.colorSpace?.model == .rgb, "Unable to initalize Image with non-RGB images")
precondition(image.alphaInfo == .premultipliedLast, "Unable to initalize Image without alpha component at end")
let data = image.dataProvider?.data
let bytes = CFDataGetBytePtr(data)
let size = Size(width: image.width, height: image.height)
self.init(data: bytes!, size: size)
}
}
public extension Image {
internal var CGImageView: CGImage {
let bytes = UnsafeMutableRawPointer(mutating: storage)
let context = CGContext(data: bytes, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: 4 * Int(size.width), space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)
return context!.makeImage()!
}
}
| bsd-2-clause | 4d8cf37c0bf937ff90112bfbc1e9f8e5 | 30.529412 | 238 | 0.761816 | 3.856115 | false | false | false | false |
idrisyildiz7/IOS-ToDoList | ToDoList/SimpleTodoList/SimpleTodoList/AddItemViewController.swift | 1 | 5479 | //
// AddItemViewController.swift
// SimpleTodoList
//
// Created by İDRİS YILDIZ on 25/12/14.
// Copyright (c) 2014 İDRİS YILDIZ. All rights reserved.
//
import UIKit
import EventKit
class AddItemViewController: UIViewController {
//Segue variables
var items: [ViewController.ToDoItems] = []
var selectedItemIndex:Int?
var titleString:String!
var backgroundColor:UIColor!
var selectedRow:Int?
//UI variables
@IBOutlet var forBackground: UIView!
@IBOutlet weak var descriptionLabel: UITextField!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var alarmSwitch: UISwitch!
@IBOutlet weak var calendarSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
title = titleString
forBackground.backgroundColor = backgroundColor?
if titleString != "Add" {
//Filling the data, if it is editing
alarmSwitch.setOn(items[selectedItemIndex!].Items[selectedRow!].alarmSwitch, animated: true)
datePicker.setDate(items[selectedItemIndex!].Items[selectedRow!].dateAndTime, animated: true)
descriptionLabel.text = items[selectedItemIndex!].Items[selectedRow!].description
calendarSwitch.setOn(items[selectedItemIndex!].Items[selectedRow!].isAddedCalendar, animated: true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func addItem(sender: UIButton) {
//Add button's click event
if titleString == "Add" {
//If it will add a new item
items[selectedItemIndex!].Items.insert(ViewController.ItemAttributes(description: descriptionLabel.text, dateAndTime: datePicker.date, alarmSwitch: alarmSwitch.on, isDone: false , isAddedCalendar: calendarSwitch.on), atIndex: 0)
}
else
{
//if it is editing the item
items[selectedItemIndex!].Items[selectedRow!].description = descriptionLabel.text
items[selectedItemIndex!].Items[selectedRow!].dateAndTime = datePicker.date
items[selectedItemIndex!].Items[selectedRow!].alarmSwitch = alarmSwitch.on
items[selectedItemIndex!].Items[selectedRow!].isAddedCalendar = calendarSwitch.on
}
if alarmSwitch.on {
//if notification switch is on, add the notification
var notification:UILocalNotification = UILocalNotification()
notification.category = "FIRST_CATEGORY"
notification.alertBody = "You missed \" " + descriptionLabel.text + "\""
notification.fireDate = datePicker.date
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
//If calender switch is on, we add a event to calendar,
//if it is not, then we control the calender and
//it is added before, deleting it
if calendarSwitch.on {
AddCalendar()
}
else {
if selectedRow != nil
{
var title:String = self.items[self.selectedItemIndex!].name
var note:String = items[selectedItemIndex!].Items[selectedRow!].description
var date:NSDate = items[selectedItemIndex!].Items[selectedRow!].dateAndTime
deleteFromCalender(date, title: title, note: note)
}
}
}
func deleteFromCalender(date:NSDate,title:String,note:String) {
var eventStore : EKEventStore = EKEventStore()
var startDate = date.dateByAddingTimeInterval(-60*60*24)
var endDate = date.dateByAddingTimeInterval(60*60*24*3)
var predicate2 = eventStore.predicateForEventsWithStartDate(startDate, endDate: endDate, calendars: nil)
var eV = eventStore.eventsMatchingPredicate(predicate2) as [EKEvent]!
if eV != nil {
for i in eV {
// Uncomment if you want to delete
if (i.notes == note && i.title == title)
{
eventStore.removeEvent(i, span: EKSpanThisEvent, error: nil)
}
}
}
}
//Adding new event to calendar
func AddCalendar(){
var eventStore : EKEventStore = EKEventStore()
eventStore.requestAccessToEntityType(EKEntityType.Event, completion: {
granted, error in
if (granted) && (error == nil) {
var event:EKEvent = EKEvent(eventStore: eventStore)
event.title = self.items[self.selectedItemIndex!].name
event.startDate = self.datePicker.date
event.endDate = self.datePicker.date
event.notes = self.descriptionLabel.text
event.calendar = eventStore.defaultCalendarForNewEvents
do {
try eventStore.saveEvent(event, span: EKSpanThisEvent)
} catch _ {
}
print("Saved Event")
}
})
}
//Segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "backToTitleListItemsSegue" {
let sg = segue.destinationViewController as! ListTableTableViewController
sg.items = items
sg.selectedItemIndex = selectedItemIndex
}
}
}
| mit | f89add5fa7a73417f3becdc4baa7eef7 | 39.555556 | 240 | 0.621918 | 5.140845 | false | false | false | false |
OAuthSwift/OAuthSwift | Demo/Common/AppDelegate.swift | 2 | 2328 | //
// AppDelegate.swift
// OAuthSwift
//
// Created by Dongri Jin on 6/21/14.
// Copyright (c) 2014 Dongri Jin. All rights reserved.
//
import OAuthSwift
#if os(iOS)
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder {
var window: UIWindow?
}
#elseif os(OSX)
import AppKit
@NSApplicationMain
class AppDelegate: NSObject {}
#endif
// MARK: handle callback url
extension AppDelegate {
func applicationHandle(url: URL) {
if (url.host == "oauth-callback") {
OAuthSwift.handle(url: url)
} else {
// Google provider is the only one with your.bundle.id url schema.
OAuthSwift.handle(url: url)
}
}
}
// MARK: ApplicationDelegate
#if os(iOS)
extension AppDelegate: UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
return true
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
applicationHandle(url: url)
return true
}
@available(iOS 9.0, *)
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
applicationHandle(url: url)
return true
}
class var sharedInstance: AppDelegate {
return UIApplication.shared.delegate as! AppDelegate
}
}
#elseif os(OSX)
extension AppDelegate: NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// listen to scheme url
NSAppleEventManager.shared().setEventHandler(self, andSelector:#selector(AppDelegate.handleGetURL(event:withReplyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
}
@objc func handleGetURL(event: NSAppleEventDescriptor!, withReplyEvent: NSAppleEventDescriptor!) {
if let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue, let url = URL(string: urlString) {
applicationHandle(url: url)
}
}
class var sharedInstance: AppDelegate {
return NSApplication.shared.delegate as! AppDelegate
}
}
#endif
| mit | 17116afeca89920c92054737aa60b0f2 | 28.1 | 214 | 0.676546 | 4.63745 | false | false | false | false |
allting/TwitterPIP | TwitterPIP/TweetWindowController.swift | 1 | 668 | //
// TweetWindowController.swift
// TwitterPIP
//
// Created by kkr on 20/07/2017.
// Copyright © 2017 allting. All rights reserved.
//
import Cocoa
class TweetWindowController: NSWindowController {
override func windowDidLoad() {
super.windowDidLoad()
self.window?.styleMask.insert(.fullSizeContentView)
self.window?.titleVisibility = .hidden
self.window?.titlebarAppearsTransparent = true
self.window?.isMovableByWindowBackground = true
self.window?.level = Int(CGWindowLevelForKey(.floatingWindow))
self.window!.standardWindowButton(NSWindowButton.zoomButton)?.isEnabled = false
}
}
| mit | bb64350b24367b7203dc0cd852930097 | 28 | 87 | 0.701649 | 4.6 | false | false | false | false |
shadanan/mado | Antlr4Runtime/Sources/Antlr4/atn/LexerPushModeAction.swift | 1 | 2090 | /// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
/// Implements the {@code pushMode} lexer action by calling
/// {@link org.antlr.v4.runtime.Lexer#pushMode} with the assigned mode.
///
/// - Sam Harwell
/// - 4.2
public final class LexerPushModeAction: LexerAction, CustomStringConvertible {
fileprivate final var mode: Int
/// Constructs a new {@code pushMode} action with the specified mode value.
/// - parameter mode: The mode value to pass to {@link org.antlr.v4.runtime.Lexer#pushMode}.
public init(_ mode: Int) {
self.mode = mode
}
/// Get the lexer mode this action should transition the lexer to.
///
/// - returns: The lexer mode for this {@code pushMode} command.
public func getMode() -> Int {
return mode
}
/// {@inheritDoc}
/// - returns: This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#pushMode}.
public override func getActionType() -> LexerActionType {
return LexerActionType.pushMode
}
/// {@inheritDoc}
/// - returns: This method returns {@code false}.
public override func isPositionDependent() -> Bool {
return false
}
/// {@inheritDoc}
///
/// <p>This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#pushMode} with the
/// value provided by {@link #getMode}.</p>
override
public func execute(_ lexer: Lexer) {
lexer.pushMode(mode)
}
override
public var hashValue: Int {
var hash: Int = MurmurHash.initialize()
hash = MurmurHash.update(hash, getActionType().rawValue)
hash = MurmurHash.update(hash, mode)
return MurmurHash.finish(hash, 2)
}
public var description: String {
return "pushMode(\(mode))"
}
}
public func ==(lhs: LexerPushModeAction, rhs: LexerPushModeAction) -> Bool {
if lhs === rhs {
return true
}
return lhs.mode == rhs.mode
}
| mit | 0ae2c9ef19460115b303c6b9dcf3e155 | 27.243243 | 101 | 0.641627 | 4.122288 | false | false | false | false |
ben-ng/swift | test/Parse/consecutive_statements.swift | 2 | 2069 | // RUN: %target-typecheck-verify-swift
func statement_starts() {
var f : (Int) -> ()
f = { (x : Int) -> () in }
f(0)
f (0)
f // expected-error{{expression resolves to an unused l-value}}
(0) // expected-warning {{result of call to 'init(_builtinIntegerLiteral:)' is unused}}
var a = [1,2,3]
a[0] = 1
a [0] = 1
a // expected-error{{expression resolves to an unused l-value}}
[0, 1, 2] // expected-warning {{expression of type '[Int]' is unused}}
}
// Within a function
func test(i: inout Int, j: inout Int) {
// Okay
let q : Int; i = j; j = i; _ = q
if i != j { i = j }
// Errors
i = j j = i // expected-error{{consecutive statements}} {{8-8=;}}
let r : Int i = j // expected-error{{consecutive statements}} {{14-14=;}}
let s : Int let t : Int // expected-error{{consecutive statements}} {{14-14=;}}
_ = r; _ = s; _ = t
}
struct X {
// In a sequence of declarations.
var a, b : Int func d() -> Int {} // expected-error{{consecutive declarations}} {{17-17=;}}
var prop : Int { return 4
} var other : Float // expected-error{{consecutive declarations}} {{4-4=;}}
// Within property accessors
subscript(i: Int) -> Float {
get {
var x = i x = i + x return Float(x) // expected-error{{consecutive statements}} {{16-16=;}} expected-error{{consecutive statements}} {{26-26=;}}
}
set {
var x = i x = i + 1 // expected-error{{consecutive statements}} {{16-16=;}}
_ = x
}
}
}
class C {
// In a sequence of declarations.
var a, b : Int func d() -> Int {} // expected-error{{consecutive declarations}} {{17-17=;}}
init() {
a = 0
b = 0
}
}
protocol P {
func a() func b() // expected-error{{consecutive declarations}} {{11-11=;}}
}
enum Color {
case Red case Blue // expected-error{{consecutive declarations}} {{11-11=;}}
func a() {} func b() {} // expected-error{{consecutive declarations}} {{14-14=;}}
}
// At the top level
var i, j : Int i = j j = i // expected-error{{consecutive statements}} {{15-15=;}} expected-error{{consecutive statements}} {{21-21=;}}
| apache-2.0 | 67f5555e2a0046311218b6cd8c0748a4 | 27.736111 | 150 | 0.58434 | 3.331723 | false | false | false | false |
Pursuit92/antlr4 | runtime/Swift/Antlr4/org/antlr/v4/runtime/CommonToken.swift | 3 | 8158 | /* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
public class CommonToken: WritableToken {
/**
* An empty {@link org.antlr.v4.runtime.misc.Pair} which is used as the default value of
* {@link #source} for tokens that do not have a source.
*/
internal static let EMPTY_SOURCE: (TokenSource?, CharStream?) = (nil, nil)
/**
* This is the backing field for {@link #getType} and {@link #setType}.
*/
internal var type: Int
/**
* This is the backing field for {@link #getLine} and {@link #setLine}.
*/
internal var line: Int = 0
/**
* This is the backing field for {@link #getCharPositionInLine} and
* {@link #setCharPositionInLine}.
*/
internal var charPositionInLine: Int = -1
// set to invalid position
/**
* This is the backing field for {@link #getChannel} and
* {@link #setChannel}.
*/
internal var channel: Int = DEFAULT_CHANNEL
/**
* This is the backing field for {@link #getTokenSource} and
* {@link #getInputStream}.
*
* <p>
* These properties share a field to reduce the memory footprint of
* {@link org.antlr.v4.runtime.CommonToken}. Tokens created by a {@link org.antlr.v4.runtime.CommonTokenFactory} from
* the same source and input stream share a reference to the same
* {@link org.antlr.v4.runtime.misc.Pair} containing these values.</p>
*/
internal var source: (TokenSource?, CharStream?)
/**
* This is the backing field for {@link #getText} when the token text is
* explicitly set in the constructor or via {@link #setText}.
*
* @see #getText()
*/
internal var text: String?
/**
* This is the backing field for {@link #getTokenIndex} and
* {@link #setTokenIndex}.
*/
internal var index: Int = -1
/**
* This is the backing field for {@link #getStartIndex} and
* {@link #setStartIndex}.
*/
internal var start: Int = 0
/**
* This is the backing field for {@link #getStopIndex} and
* {@link #setStopIndex}.
*/
internal var stop: Int = 0
/**
* Constructs a new {@link org.antlr.v4.runtime.CommonToken} with the specified token type.
*
* @param type The token type.
*/
private var _visited: Bool = false
public init(_ type: Int) {
self.type = type
self.source = CommonToken.EMPTY_SOURCE
}
public init(_ source: (TokenSource?, CharStream?), _ type: Int, _ channel: Int, _ start: Int, _ stop: Int) {
self.source = source
self.type = type
self.channel = channel
self.start = start
self.stop = stop
if let tsource = source.0 {
self.line = tsource.getLine()
self.charPositionInLine = tsource.getCharPositionInLine()
}
}
/**
* Constructs a new {@link org.antlr.v4.runtime.CommonToken} with the specified token type and
* text.
*
* @param type The token type.
* @param text The text of the token.
*/
public init(_ type: Int, _ text: String?) {
self.type = type
self.channel = CommonToken.DEFAULT_CHANNEL
self.text = text
self.source = CommonToken.EMPTY_SOURCE
}
/**
* Constructs a new {@link org.antlr.v4.runtime.CommonToken} as a copy of another {@link org.antlr.v4.runtime.Token}.
*
* <p>
* If {@code oldToken} is also a {@link org.antlr.v4.runtime.CommonToken} instance, the newly
* constructed token will share a reference to the {@link #text} field and
* the {@link org.antlr.v4.runtime.misc.Pair} stored in {@link #source}. Otherwise, {@link #text} will
* be assigned the result of calling {@link #getText}, and {@link #source}
* will be constructed from the result of {@link org.antlr.v4.runtime.Token#getTokenSource} and
* {@link org.antlr.v4.runtime.Token#getInputStream}.</p>
*
* @param oldToken The token to copy.
*/
public init(_ oldToken: Token) {
type = oldToken.getType()
line = oldToken.getLine()
index = oldToken.getTokenIndex()
charPositionInLine = oldToken.getCharPositionInLine()
channel = oldToken.getChannel()
start = oldToken.getStartIndex()
stop = oldToken.getStopIndex()
if oldToken is CommonToken {
text = (oldToken as! CommonToken).text
source = (oldToken as! CommonToken).source
} else {
text = oldToken.getText()
source = (oldToken.getTokenSource(), oldToken.getInputStream())
}
}
public func getType() -> Int {
return type
}
public func setLine(_ line: Int) {
self.line = line
}
public func getText() -> String? {
if text != nil {
return text!
}
if let input = getInputStream() {
let n: Int = input.size()
if start < n && stop < n {
return input.getText(Interval.of(start, stop))
} else {
return "<EOF>"
}
}
return nil
}
/**
* Explicitly set the text for this token. If {code text} is not
* {@code null}, then {@link #getText} will return this value rather than
* extracting the text from the input.
*
* @param text The explicit text of the token, or {@code null} if the text
* should be obtained from the input along with the start and stop indexes
* of the token.
*/
public func setText(_ text: String) {
self.text = text
}
public func getLine() -> Int {
return line
}
public func getCharPositionInLine() -> Int {
return charPositionInLine
}
public func setCharPositionInLine(_ charPositionInLine: Int) {
self.charPositionInLine = charPositionInLine
}
public func getChannel() -> Int {
return channel
}
public func setChannel(_ channel: Int) {
self.channel = channel
}
public func setType(_ type: Int) {
self.type = type
}
public func getStartIndex() -> Int {
return start
}
public func setStartIndex(_ start: Int) {
self.start = start
}
public func getStopIndex() -> Int {
return stop
}
public func setStopIndex(_ stop: Int) {
self.stop = stop
}
public func getTokenIndex() -> Int {
return index
}
public func setTokenIndex(_ index: Int) {
self.index = index
}
public func getTokenSource() -> TokenSource? {
return source.0
}
public func getInputStream() -> CharStream? {
return source.1
}
public var description: String {
return toString(nil)
}
public func toString(_ r: Recognizer<ATNSimulator>?) -> String {
var channelStr: String = ""
if channel > 0 {
channelStr = ",channel=\(channel)"
}
var txt: String
if let tokenText = getText() {
txt = tokenText.replaceAll("\n", replacement: "\\n")
txt = txt.replaceAll("\r", replacement: "\\r")
txt = txt.replaceAll("\t", replacement: "\\t")
} else {
txt = "<no text>"
}
var typeString = "\(type)"
if let r = r {
typeString = r.getVocabulary().getDisplayName(type);
}
return "[@"+getTokenIndex()+","+start+":"+stop+"='"+txt+"',<"+typeString+">"+channelStr+","+line+":"+getCharPositionInLine()+"]"
// let desc: StringBuilder = StringBuilder()
// desc.append("[@\(getTokenIndex()),")
// desc.append("\(start):\(stop)='\(txt)',")
// desc.append("<\(typeString)>\(channelStr),")
// desc.append("\(line):\(getCharPositionInLine())]")
//
// return desc.toString()
}
public var visited: Bool {
get {
return _visited
}
set {
_visited = newValue
}
}
}
| bsd-3-clause | 9550043715f848b0479ee7f236e25a4d | 26.560811 | 135 | 0.575754 | 4.181445 | false | false | false | false |
iprebeg/EnigmaKit | EnigmaKit/Rotor.swift | 1 | 3154 | //
// Rotor.swift
// EnigmaKit
//
// Created by Prebeg, Ivor on 02/12/2016.
// Copyright © 2016 Prebeg, Ivor. All rights reserved.
//
import Foundation
class Rotor : ReversibleSignalHandler {
private var alphaMapper:AlphaMapper
private var offset:Int
private var setting:Int
private var notches:Array<Character>
private(set) var carry:Bool = false
private var length:Int!
init(rotor:String, offset:Character = "A", setting:Character = "A", notches:Array<Character>) {
alphaMapper = AlphaMapper(alphaStatic: Constants.ALPHABET, alphaRot: rotor)
self.offset = offset.alphaIndex
self.setting = setting.alphaIndex
self.length = rotor.characters.count
self.notches = notches
}
func setOffset(offset:Character) {
self.offset = offset.alphaIndex % length
}
func setSetting(setting:Character) {
self.setting = setting.alphaIndex % length
}
func read() -> (Character) {
return alphaMapper.read(at: offset)
}
func rotate() {
offset += 1
offset %= length
if (notches.contains(alphaMapper.read(at: offset)) ) {
carry = true
} else {
carry = false
}
}
func signal(c: Character) -> (Character) {
return Character.fromAlphaIndex(idx: (alphaMapper.map(c: Character.fromAlphaIndex(idx:(c.alphaIndex + offset) % length), offset: setting).alphaIndex - offset + length) % length)
}
func signalReverse(c: Character) -> (Character) {
return Character.fromAlphaIndex(idx: (alphaMapper.maprev(c: Character.fromAlphaIndex(idx: (c.alphaIndex + offset) % length), offset: setting).alphaIndex - offset + length) % length)
}
static func ROTOR_I() -> (Rotor) {
return Rotor(rotor: Constants.ROTOR_I, notches: Array(arrayLiteral: "Q"))
}
static func ROTOR_II() -> (Rotor) {
return Rotor(rotor: Constants.ROTOR_II, notches: Array(arrayLiteral: "E"))
}
static func ROTOR_III() -> (Rotor) {
return Rotor(rotor: Constants.ROTOR_III, notches: Array(arrayLiteral: "V"))
}
static func ROTOR_IV() -> (Rotor) {
return Rotor(rotor: Constants.ROTOR_IV, notches: Array(arrayLiteral: "J"))
}
static func ROTOR_V() -> (Rotor) {
return Rotor(rotor: Constants.ROTOR_V, notches: Array(arrayLiteral: "Z"))
}
static func ROTOR_VI() -> (Rotor) {
return Rotor(rotor: Constants.ROTOR_VI, notches: Array(arrayLiteral: "Z", "M"))
}
static func ROTOR_VII() -> (Rotor) {
return Rotor(rotor: Constants.ROTOR_VII, notches: Array(arrayLiteral: "Z", "M"))
}
static func ROTOR_VIII() -> (Rotor) {
return Rotor(rotor: Constants.ROTOR_VIII, notches: Array(arrayLiteral: "Z", "M"))
}
static func ROTOR_BETA() -> (Rotor) {
return Rotor(rotor: Constants.ROTOR_BETA, notches: Array(arrayLiteral: "Z", "M"))
}
static func ROTOR_GAMMA() -> (Rotor) {
return Rotor(rotor: Constants.ROTOR_GAMMA, notches: Array(arrayLiteral: "Z", "M"))
}
}
| gpl-3.0 | 457b406e5f18947229d8a6cda868e15c | 31.173469 | 189 | 0.61275 | 3.558691 | false | false | false | false |
eselkin/DirectionFieldiOS | Pods/GRDB.swift/GRDB/Core/Database.swift | 1 | 36519 | import Foundation
/// A raw SQLite connection, suitable for the SQLite C API.
public typealias SQLiteConnection = COpaquePointer
/// A Database connection.
///
/// You don't create a database directly. Instead, you use a DatabaseQueue:
///
/// let dbQueue = DatabaseQueue(...)
///
/// // The Database is the `db` in the closure:
/// dbQueue.inDatabase { db in
/// db.execute(...)
/// }
public final class Database {
// =========================================================================
// MARK: - Select Statements
/// Returns a prepared statement that can be reused.
///
/// let statement = try db.selectStatement("SELECT * FROM persons WHERE age > ?")
/// let moreThanTwentyCount = Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = Int.fetchOne(statement, arguments: [30])!
///
/// - parameter sql: An SQL query.
/// - returns: A SelectStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func selectStatement(sql: String) throws -> SelectStatement {
return try SelectStatement(database: self, sql: sql)
}
// =========================================================================
// MARK: - Update Statements
/// Returns an prepared statement that can be reused.
///
/// let statement = try db.updateStatement("INSERT INTO persons (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
/// This method may throw a DatabaseError.
///
/// - parameter sql: An SQL query.
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func updateStatement(sql: String) throws -> UpdateStatement {
return try UpdateStatement(database: self, sql: sql)
}
/// Executes an update statement.
///
/// db.excute("INSERT INTO persons (name) VALUES (?)", arguments: ["Arthur"])
///
/// This method may throw a DatabaseError.
///
/// - parameter sql: An SQL query.
/// - parameter arguments: Statement arguments.
/// - returns: A DatabaseChanges.
/// - throws: A DatabaseError whenever a SQLite error occurs.
public func execute(sql: String, arguments: StatementArguments = StatementArguments.Default) throws -> DatabaseChanges {
let statement = try updateStatement(sql)
return try statement.execute(arguments: arguments)
}
/// Executes multiple SQL statements, separated by semi-colons.
///
/// try db.executeMultiStatement(
/// "INSERT INTO persons (name) VALUES ('Harry');" +
/// "INSERT INTO persons (name) VALUES ('Ron');" +
/// "INSERT INTO persons (name) VALUES ('Hermione');")
///
/// This method may throw a DatabaseError.
///
/// - parameter sql: SQL containing multiple statements separated by
/// semi-colons.
/// - returns: A DatabaseChanges. Note that insertedRowID will always be nil.
/// - throws: A DatabaseError whenever a SQLite error occurs.
public func executeMultiStatement(sql: String) throws -> DatabaseChanges {
preconditionValidQueue()
let changedRowsBefore = sqlite3_total_changes(sqliteConnection)
let code = sqlite3_exec(sqliteConnection, sql, nil, nil, nil)
guard code == SQLITE_OK else {
throw DatabaseError(code: code, message: lastErrorMessage, sql: sql, arguments: nil)
}
let changedRowsAfter = sqlite3_total_changes(sqliteConnection)
return DatabaseChanges(changedRowCount: changedRowsAfter - changedRowsBefore, insertedRowID: nil)
}
// =========================================================================
// MARK: - Transactions
/// Executes a block inside a database transaction.
///
/// try dbQueue.inDatabase do {
/// try db.inTransaction {
/// try db.execute("INSERT ...")
/// return .Commit
/// }
/// }
///
/// If the block throws an error, the transaction is rollbacked and the
/// error is rethrown.
///
/// This method is not reentrant: you can't nest transactions.
///
/// - parameter kind: The transaction type (default nil). If nil, the
/// transaction type is configuration.defaultTransactionKind, which itself
/// defaults to .Immediate. See https://www.sqlite.org/lang_transaction.html
/// for more information.
/// - parameter block: A block that executes SQL statements and return
/// either .Commit or .Rollback.
/// - throws: The error thrown by the block.
public func inTransaction(kind: TransactionKind? = nil, block: () throws -> TransactionCompletion) throws {
preconditionValidQueue()
var completion: TransactionCompletion = .Rollback
var blockError: ErrorType? = nil
try beginTransaction(kind)
do {
completion = try block()
} catch {
completion = .Rollback
blockError = error
}
switch completion {
case .Commit:
try commit()
case .Rollback:
// https://www.sqlite.org/lang_transaction.html#immediate
//
// > Response To Errors Within A Transaction
// >
// > If certain kinds of errors occur within a transaction, the
// > transaction may or may not be rolled back automatically. The
// > errors that can cause an automatic rollback include:
// >
// > - SQLITE_FULL: database or disk full
// > - SQLITE_IOERR: disk I/O error
// > - SQLITE_BUSY: database in use by another process
// > - SQLITE_NOMEM: out or memory
// >
// > [...] It is recommended that applications respond to the errors
// > listed above by explicitly issuing a ROLLBACK command. If the
// > transaction has already been rolled back automatically by the
// > error response, then the ROLLBACK command will fail with an
// > error, but no harm is caused by this.
if let blockError = blockError as? DatabaseError {
switch Int32(blockError.code) {
case SQLITE_FULL, SQLITE_IOERR, SQLITE_BUSY, SQLITE_NOMEM:
do { try rollback() } catch { }
default:
try rollback()
}
} else {
try rollback()
}
}
if let blockError = blockError {
throw blockError
}
}
private func beginTransaction(kind: TransactionKind? = nil) throws {
switch kind ?? configuration.defaultTransactionKind {
case .Deferred:
try execute("BEGIN DEFERRED TRANSACTION")
case .Immediate:
try execute("BEGIN IMMEDIATE TRANSACTION")
case .Exclusive:
try execute("BEGIN EXCLUSIVE TRANSACTION")
}
}
private func rollback() throws {
try execute("ROLLBACK TRANSACTION")
}
private func commit() throws {
try execute("COMMIT TRANSACTION")
}
// =========================================================================
// MARK: - Transaction Observation
private enum StatementCompletion {
// Statement has ended with a commit (implicit or explicit).
case TransactionCommit
// Statement has ended with a rollback.
case TransactionRollback
// Statement has been rollbacked by transactionObserver.
case TransactionErrorRollback(ErrorType)
// All other cases (CREATE TABLE, etc.)
case Regular
}
/// Updated in SQLite callbacks (see setupTransactionHooks())
/// Consumed in updateStatementDidFail() and updateStatementDidExecute().
private var statementCompletion: StatementCompletion = .Regular
func updateStatementDidFail() throws {
let statementCompletion = self.statementCompletion
self.statementCompletion = .Regular
switch statementCompletion {
case .TransactionErrorRollback(let error):
// The transaction has been rollbacked from
// TransactionObserverType.transactionWillCommit().
configuration.transactionObserver!.databaseDidRollback(self)
throw error
default:
break
}
}
func updateStatementDidExecute() {
let statementCompletion = self.statementCompletion
self.statementCompletion = .Regular
switch statementCompletion {
case .TransactionCommit:
configuration.transactionObserver!.databaseDidCommit(self)
case .TransactionRollback:
configuration.transactionObserver!.databaseDidRollback(self)
default:
break
}
}
private func setupTransactionHooks() {
// No need to setup any hook when there is no transactionObserver:
guard configuration.transactionObserver != nil else {
return
}
let dbPointer = unsafeBitCast(self, UnsafeMutablePointer<Void>.self)
sqlite3_update_hook(sqliteConnection, { (dbPointer, updateKind, databaseName, tableName, rowID) in
let db = unsafeBitCast(dbPointer, Database.self)
// Notify change event
let event = DatabaseEvent(
kind: DatabaseEvent.Kind(rawValue: updateKind)!,
databaseName: String.fromCString(databaseName)!,
tableName: String.fromCString(tableName)!,
rowID: rowID)
db.configuration.transactionObserver!.databaseDidChangeWithEvent(event)
}, dbPointer)
sqlite3_commit_hook(sqliteConnection, { dbPointer in
let db = unsafeBitCast(dbPointer, Database.self)
do {
try db.configuration.transactionObserver!.databaseWillCommit()
// Next step: updateStatementDidExecute()
db.statementCompletion = .TransactionCommit
return 0
} catch {
// Next step: sqlite3_rollback_hook callback
db.statementCompletion = .TransactionErrorRollback(error)
return 1
}
}, dbPointer)
sqlite3_rollback_hook(sqliteConnection, { dbPointer in
let db = unsafeBitCast(dbPointer, Database.self)
switch db.statementCompletion {
case .TransactionErrorRollback:
// The transactionObserver has rollbacked the transaction.
// Don't lose this information.
// Next step: updateStatementDidFail()
break
default:
// Next step: updateStatementDidExecute()
db.statementCompletion = .TransactionRollback
}
}, dbPointer)
}
// =========================================================================
// MARK: - Concurrency
/// The busy handler callback, if any. See Configuration.busyMode.
private var busyCallback: BusyCallback?
func setupBusyMode() {
switch configuration.busyMode {
case .ImmediateError:
break
case .Timeout(let duration):
let milliseconds = Int32(duration * 1000)
sqlite3_busy_timeout(sqliteConnection, milliseconds)
case .Callback(let callback):
let dbPointer = unsafeBitCast(self, UnsafeMutablePointer<Void>.self)
busyCallback = callback
sqlite3_busy_handler(
sqliteConnection,
{ (dbPointer: UnsafeMutablePointer<Void>, numberOfTries: Int32) in
let database = unsafeBitCast(dbPointer, Database.self)
let callback = database.busyCallback!
return callback(numberOfTries: Int(numberOfTries)) ? 1 : 0
},
dbPointer)
}
}
// =========================================================================
// MARK: - Functions
private var functions = Set<DatabaseFunction>()
/// Add or redefine an SQL function.
///
/// let fn = DatabaseFunction("succ", argumentCount: 1) { databaseValues in
/// let dbv = databaseValues.first!
/// guard let int = dbv.value() as Int? else {
/// return nil
/// }
/// return int + 1
/// }
/// db.addFunction(fn)
/// Int.fetchOne(db, "SELECT succ(1)")! // 2
///
/// - parameter function: A function.
public func addFunction(function: DatabaseFunction) {
functions.remove(function)
functions.insert(function)
let functionPointer = unsafeBitCast(function, UnsafeMutablePointer<Void>.self)
let code = sqlite3_create_function_v2(
sqliteConnection,
function.name,
function.argumentCount,
SQLITE_UTF8 | function.eTextRep,
functionPointer,
{ (context, argc, argv) in
let function = unsafeBitCast(sqlite3_user_data(context), DatabaseFunction.self)
do {
let result = try function.function(context, argc, argv)
switch result.storage {
case .Null:
sqlite3_result_null(context)
case .Int64(let int64):
sqlite3_result_int64(context, int64)
case .Double(let double):
sqlite3_result_double(context, double)
case .String(let string):
sqlite3_result_text(context, string, -1, SQLITE_TRANSIENT)
case .Blob(let data):
sqlite3_result_blob(context, data.bytes, Int32(data.length), SQLITE_TRANSIENT)
}
} catch let error as DatabaseError {
if let message = error.message {
sqlite3_result_error(context, message, -1)
}
sqlite3_result_error_code(context, Int32(error.code))
} catch {
sqlite3_result_error(context, "\(error)", -1)
}
}, nil, nil, nil)
guard code == SQLITE_OK else {
fatalError(DatabaseError(code: code, message: lastErrorMessage, sql: nil, arguments: nil).description)
}
}
/// Remove an SQL function.
///
/// - parameter function: A function.
public func removeFunction(function: DatabaseFunction) {
functions.remove(function)
let code = sqlite3_create_function_v2(
sqliteConnection,
function.name,
function.argumentCount,
SQLITE_UTF8 | function.eTextRep,
nil, nil, nil, nil, nil)
guard code == SQLITE_OK else {
fatalError(DatabaseError(code: code, message: lastErrorMessage, sql: nil, arguments: nil).description)
}
}
// =========================================================================
// MARK: - Collations
private var collations = Set<DatabaseCollation>()
/// Add or redefine a collation.
///
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
/// return (string1 as NSString).localizedStandardCompare(string2)
/// }
/// db.addCollation(collation)
/// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD")
///
/// - parameter collation: A collation.
public func addCollation(collation: DatabaseCollation) {
collations.remove(collation)
collations.insert(collation)
let collationPointer = unsafeBitCast(collation, UnsafeMutablePointer<Void>.self)
let code = sqlite3_create_collation_v2(
sqliteConnection,
collation.name,
SQLITE_UTF8,
collationPointer,
{ (collationPointer, length1, buffer1, length2, buffer2) -> Int32 in
let collation = unsafeBitCast(collationPointer, DatabaseCollation.self)
// Buffers are not C strings: they do not end with \0.
let string1 = String(bytesNoCopy: UnsafeMutablePointer<Void>(buffer1), length: Int(length1), encoding: NSUTF8StringEncoding, freeWhenDone: false)!
let string2 = String(bytesNoCopy: UnsafeMutablePointer<Void>(buffer2), length: Int(length2), encoding: NSUTF8StringEncoding, freeWhenDone: false)!
return Int32(collation.function(string1, string2).rawValue)
}, nil)
guard code == SQLITE_OK else {
fatalError(DatabaseError(code: code, message: lastErrorMessage, sql: nil, arguments: nil).description)
}
}
/// Remove a collation.
///
/// - parameter collation: A collation.
public func removeCollation(collation: DatabaseCollation) {
collations.remove(collation)
sqlite3_create_collation_v2(
sqliteConnection,
collation.name,
SQLITE_UTF8,
nil, nil, nil)
}
// =========================================================================
// MARK: - Database Informations
/// Clears the database schema cache.
///
/// You may need to clear the cache if you modify the database schema
/// outside of a migration (see DatabaseMigrator).
public func clearSchemaCache() {
preconditionValidQueue()
columnInfosCache = [:]
}
/// The last error message
var lastErrorMessage: String? { return String.fromCString(sqlite3_errmsg(sqliteConnection)) }
/// Returns whether a table exists.
///
/// - parameter tableName: A table name.
/// - returns: True if the table exists.
public func tableExists(tableName: String) -> Bool {
// SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html)
return Row.fetchOne(self,
"SELECT sql FROM sqlite_master WHERE type = 'table' AND LOWER(name) = ?",
arguments: [tableName.lowercaseString]) != nil
}
/// Return the primary key for table named `tableName`, or nil if table does
/// not exist.
///
/// This method is not thread-safe.
func primaryKey(tableName: String) -> PrimaryKey? {
// https://www.sqlite.org/pragma.html
//
// > PRAGMA database.table_info(table-name);
// >
// > This pragma returns one row for each column in the named table.
// > Columns in the result set include the column name, data type,
// > whether or not the column can be NULL, and the default value for
// > the column. The "pk" column in the result set is zero for columns
// > that are not part of the primary key, and is the index of the
// > column in the primary key for columns that are part of the primary
// > key.
//
// CREATE TABLE persons (
// id INTEGER PRIMARY KEY,
// firstName TEXT,
// lastName TEXT)
//
// PRAGMA table_info("persons")
//
// cid | name | type | notnull | dflt_value | pk |
// 0 | id | INTEGER | 0 | NULL | 1 |
// 1 | firstName | TEXT | 0 | NULL | 0 |
// 2 | lastName | TEXT | 0 | NULL | 0 |
let columnInfos = self.columnInfos(tableName)
guard columnInfos.count > 0 else {
// Table does not exist
return nil
}
let pkColumnInfos = columnInfos
.filter { $0.primaryKeyIndex > 0 }
.sort { $0.primaryKeyIndex < $1.primaryKeyIndex }
switch pkColumnInfos.count {
case 0:
// No primary key column
return PrimaryKey.None
case 1:
// Single column
let pkColumnInfo = pkColumnInfos.first!
// https://www.sqlite.org/lang_createtable.html:
//
// > With one exception noted below, if a rowid table has a primary
// > key that consists of a single column and the declared type of
// > that column is "INTEGER" in any mixture of upper and lower
// > case, then the column becomes an alias for the rowid. Such a
// > column is usually referred to as an "integer primary key".
// > A PRIMARY KEY column only becomes an integer primary key if the
// > declared type name is exactly "INTEGER". Other integer type
// > names like "INT" or "BIGINT" or "SHORT INTEGER" or "UNSIGNED
// > INTEGER" causes the primary key column to behave as an ordinary
// > table column with integer affinity and a unique index, not as
// > an alias for the rowid.
// >
// > The exception mentioned above is that if the declaration of a
// > column with declared type "INTEGER" includes an "PRIMARY KEY
// > DESC" clause, it does not become an alias for the rowid [...]
//
// We ignore the exception, and consider all INTEGER primary keys as
// aliases for the rowid:
if pkColumnInfo.type.uppercaseString == "INTEGER" {
return .Managed(pkColumnInfo.name)
} else {
return .Unmanaged([pkColumnInfo.name])
}
default:
// Multi-columns primary key
return .Unmanaged(pkColumnInfos.map { $0.name })
}
}
// CREATE TABLE persons (
// id INTEGER PRIMARY KEY,
// firstName TEXT,
// lastName TEXT)
//
// PRAGMA table_info("persons")
//
// cid | name | type | notnull | dflt_value | pk |
// 0 | id | INTEGER | 0 | NULL | 1 |
// 1 | firstName | TEXT | 0 | NULL | 0 |
// 2 | lastName | TEXT | 0 | NULL | 0 |
private struct ColumnInfo : RowConvertible {
let name: String
let type: String
let notNull: Bool
let defaultDatabaseValue: DatabaseValue
let primaryKeyIndex: Int
static func fromRow(row: Row) -> ColumnInfo {
return ColumnInfo(
name:row.value(named: "name"),
type:row.value(named: "type"),
notNull:row.value(named: "notnull"),
defaultDatabaseValue:row["dflt_value"]!,
primaryKeyIndex:row.value(named: "pk"))
}
}
// Cache for columnInfos()
private var columnInfosCache: [String: [ColumnInfo]] = [:]
private func columnInfos(tableName: String) -> [ColumnInfo] {
if let columnInfos = columnInfosCache[tableName] {
return columnInfos
} else {
// This pragma is case-insensitive: PRAGMA table_info("PERSONS") and
// PRAGMA table_info("persons") yield the same results.
let columnInfos = ColumnInfo.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
columnInfosCache[tableName] = columnInfos
return columnInfos
}
}
// =========================================================================
// MARK: - Raw SQLite connetion
/// The raw SQLite connection, suitable for the SQLite C API.
public let sqliteConnection: SQLiteConnection
// =========================================================================
// MARK: - Configuration
/// The database configuration
public let configuration: Configuration
// =========================================================================
// MARK: - Initialization
/// The queue from which the database can be used. See preconditionValidQueue().
/// Design note: this is not very clean. A delegation pattern may be a
/// better fit.
var databaseQueueID: DatabaseQueueID = nil
init(path: String, configuration: Configuration) throws {
self.configuration = configuration
// See https://www.sqlite.org/c3ref/open.html
var sqliteConnection = SQLiteConnection()
let code = sqlite3_open_v2(path, &sqliteConnection, configuration.sqliteOpenFlags, nil)
self.sqliteConnection = sqliteConnection
if code != SQLITE_OK {
throw DatabaseError(code: code, message: String.fromCString(sqlite3_errmsg(sqliteConnection)))
}
setupTrace() // First, so that all queries, including initialization queries, are traced.
try setupForeignKeys()
setupBusyMode()
setupTransactionHooks()
}
// Initializes an in-memory database
convenience init(configuration: Configuration) {
try! self.init(path: ":memory:", configuration: configuration)
}
deinit {
sqlite3_close(sqliteConnection)
}
// =========================================================================
// MARK: - Misc
func preconditionValidQueue() {
precondition(databaseQueueID == nil || databaseQueueID == dispatch_get_specific(DatabaseQueue.databaseQueueIDKey), "Database was not used on the correct thread: execute your statements inside DatabaseQueue.inDatabase() or DatabaseQueue.inTransaction(). If you get this error while iterating the result of a fetch() method, use fetchAll() instead: it returns an Array that can be iterated on any thread.")
}
func setupForeignKeys() throws {
if configuration.foreignKeysEnabled {
try execute("PRAGMA foreign_keys = ON")
}
}
func setupTrace() {
guard configuration.trace != nil else {
return
}
let dbPointer = unsafeBitCast(self, UnsafeMutablePointer<Void>.self)
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
let database = unsafeBitCast(dbPointer, Database.self)
database.configuration.trace!(String.fromCString(sql)!)
}, dbPointer)
}
}
// =============================================================================
// MARK: - PrimaryKey
/// A primary key
enum PrimaryKey {
/// No primary key
case None
/// A primary key managed by SQLite. Associated string is a column name.
case Managed(String)
/// A primary key not managed by SQLite. It can span accross several
/// columns. Associated strings are column names.
case Unmanaged([String])
/// The columns in the primary key. May be empty.
var columns: [String] {
switch self {
case .None:
return []
case .Managed(let column):
return [column]
case .Unmanaged(let columns):
return columns
}
}
}
// =============================================================================
// MARK: - TransactionKind
/// A SQLite transaction kind. See https://www.sqlite.org/lang_transaction.html
public enum TransactionKind {
case Deferred
case Immediate
case Exclusive
}
// =============================================================================
// MARK: - TransactionCompletion
/// The end of a transaction: Commit, or Rollback
public enum TransactionCompletion {
case Commit
case Rollback
}
// =============================================================================
// MARK: - TransactionObserverType
/// A transaction observer is notified of all changes and transactions committed
/// or rollbacked on a database.
///
/// Adopting types must be a class.
public protocol TransactionObserverType : class {
/// Notifies a database change (insert, update, or delete).
///
/// The change is pending until the end of the current transaction, notified
/// to databaseWillCommit, databaseDidCommit and databaseDidRollback.
///
/// This method is called on the database queue.
///
/// **WARNING**: this method must not change the database.
///
/// - parameter event: A database event.
func databaseDidChangeWithEvent(event: DatabaseEvent)
/// When a transaction is about to be committed, the transaction observer
/// has an opportunity to rollback pending changes by throwing an error.
///
/// This method is called on the database queue.
///
/// **WARNING**: this method must not change the database.
///
/// - throws: An eventual error that rollbacks pending changes.
func databaseWillCommit() throws
/// Database changes have been committed.
///
/// This method is called on the database queue. It can change the database.
///
/// - parameter db: A Database.
func databaseDidCommit(db: Database)
/// Database changes have been rollbacked.
///
/// This method is called on the database queue. It can change the database.
///
/// - parameter db: A Database.
func databaseDidRollback(db: Database)
}
// =============================================================================
// MARK: - DatabaseEvent
/// A database event, notified to TransactionObserverType.
///
/// See https://www.sqlite.org/c3ref/update_hook.html for more information.
public struct DatabaseEvent {
/// An event kind
public enum Kind: Int32 {
case Insert = 18 // SQLITE_INSERT
case Delete = 9 // SQLITE_DELETE
case Update = 23 // SQLITE_UPDATE
}
/// The event kind
public let kind: Kind
/// The database name
public let databaseName: String
/// The table name
public let tableName: String
/// The rowID of the changed row.
public let rowID: Int64
}
// =============================================================================
// MARK: - ThreadingMode
/// A SQLite threading mode. See https://www.sqlite.org/threadsafe.html.
enum ThreadingMode {
case Default
case MultiThread
case Serialized
var sqliteOpenFlags: Int32 {
switch self {
case .Default:
return 0
case .MultiThread:
return SQLITE_OPEN_NOMUTEX
case .Serialized:
return SQLITE_OPEN_FULLMUTEX
}
}
}
// =============================================================================
// MARK: - BusyMode
/// See BusyMode and https://www.sqlite.org/c3ref/busy_handler.html
public typealias BusyCallback = (numberOfTries: Int) -> Bool
/// When there are several connections to a database, a connection may try to
/// access the database while it is locked by another connection.
///
/// The BusyMode enum describes the behavior of GRDB when such a situation
/// occurs:
///
/// - .ImmediateError: The SQLITE_BUSY error is immediately returned to the
/// connection that tries to access the locked database.
///
/// - .Timeout: The SQLITE_BUSY error will be returned only if the database
/// remains locked for more than the specified duration.
///
/// - .Callback: Perform your custom lock handling.
///
/// To set the busy mode of a database, use Configuration:
///
/// let configuration = Configuration(busyMode: .Timeout(1))
/// let dbQueue = DatabaseQueue(path: "...", configuration: configuration)
///
/// Relevant SQLite documentation:
///
/// - https://www.sqlite.org/c3ref/busy_timeout.html
/// - https://www.sqlite.org/c3ref/busy_handler.html
/// - https://www.sqlite.org/lang_transaction.html
/// - https://www.sqlite.org/wal.html
public enum BusyMode {
/// The SQLITE_BUSY error is immediately returned to the connection that
/// tries to access the locked database.
case ImmediateError
/// The SQLITE_BUSY error will be returned only if the database remains
/// locked for more than the specified duration.
case Timeout(NSTimeInterval)
/// A custom callback that is called when a database is locked.
/// See https://www.sqlite.org/c3ref/busy_handler.html
case Callback(BusyCallback)
}
// =========================================================================
// MARK: - Functions
/// An SQL function.
public class DatabaseFunction : Hashable {
let name: String
let argumentCount: Int32
let pure: Bool
let function: (COpaquePointer, Int32, UnsafeMutablePointer<COpaquePointer>) throws -> DatabaseValue
var eTextRep: Int32 { return pure ? SQLITE_DETERMINISTIC : 0 }
/// The hash value.
public var hashValue: Int {
return name.hashValue ^ argumentCount.hashValue
}
/// Returns an SQL function.
///
/// let fn = DatabaseFunction("succ", argumentCount: 1) { databaseValues in
/// let dbv = databaseValues.first!
/// guard let int = dbv.value() as Int? else {
/// return nil
/// }
/// return int + 1
/// }
/// db.addFunction(fn)
/// Int.fetchOne(db, "SELECT succ(1)")! // 2
///
/// - parameter name: The function name.
/// - parameter argumentCount: The number of arguments of the function. If
/// omitted, or nil, the function accepts any number of arguments.
/// - parameter pure: Whether the function is "pure", which means that its
/// results only depends on its inputs. When a function is pure, SQLite
/// has the opportunity to perform additional optimizations. Default value
/// is false.
/// - parameter function: A function that takes an array of DatabaseValue
/// arguments, and returns an optional DatabaseValueConvertible such as
/// Int, String, NSDate, etc. The array is guaranteed to have exactly
/// *argumentCount* elements, provided *argumentCount* is not nil.
public init(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, function: [DatabaseValue] throws -> DatabaseValueConvertible?) {
self.name = name
self.argumentCount = argumentCount ?? -1
self.pure = pure
self.function = { (context, argc, argv) in
let arguments = (0..<Int(argc)).map { index in DatabaseValue(sqliteValue: argv[index]) }
return try function(arguments)?.databaseValue ?? .Null
}
}
}
/// Two functions are equal if they share the same name and argumentCount.
public func ==(lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool {
return lhs.name == rhs.name && lhs.argumentCount == rhs.argumentCount
}
// =========================================================================
// MARK: - Collations
/// A Collation.
public class DatabaseCollation : Hashable {
let name: String
let function: (String, String) -> NSComparisonResult
/// The hash value.
public var hashValue: Int {
// We can't compute a hash since the equality is based on the opaque
// sqlite3_strnicmp SQLite function.
return 0
}
/// Returns a collation.
///
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
/// return (string1 as NSString).localizedStandardCompare(string2)
/// }
/// db.addCollation(collation)
/// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD")
///
/// - parameter name: The function name.
/// - parameter function: A function that compares two strings.
public init(_ name: String, function: (String, String) -> NSComparisonResult) {
self.name = name
self.function = function
}
}
/// Two collations are equal if they share the same name (case insensitive)
public func ==(lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool {
// See https://www.sqlite.org/c3ref/create_collation.html
return sqlite3_stricmp(lhs.name, lhs.name) == 0
}
| gpl-3.0 | ba20bdd147166da76492b4635b0d4b49 | 37.001041 | 412 | 0.572524 | 5.019794 | false | false | false | false |
netyouli/WHC_Debuger | WHC_DebugerSwift/WHC_DebugerSwift/ViewController.swift | 1 | 2298 | //
// ViewController.swift
// WHC_DebugerSwift
//
// Created by WHC on 17/1/14.
// Copyright © 2017年 WHC. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
private let button = UIButton()
private let buttonUI = UIButton()
private let label = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor.white
self.title = "iOS Debuger";
layoutUI()
/// 添加约束
button.whc_Center(0, y: -60)
.whc_Size(100, height: 100)
buttonUI.whc_CenterX(0)
.whc_Top(20, toView: button)
.whc_SizeEqual(button)
label.whc_Top(20, toView: buttonUI)
.whc_Left(10)
.whc_Right(10)
.whc_HeightAuto()
}
private func layoutUI() {
button.setTitle("PUSH", for: .normal)
button.backgroundColor = UIColor.green
button.addTarget(self, action: #selector(clickPush(_:)), for: .touchUpInside)
self.view.addSubview(button)
buttonUI.setTitle("ThreadUI", for: .normal)
buttonUI.backgroundColor = UIColor.orange
buttonUI.addTarget(self, action: #selector(clickButtonUI(_:)), for: .touchUpInside)
self.view.addSubview(buttonUI)
label.backgroundColor = UIColor.gray
label.textColor = UIColor.white
label.text = "改变文字演示"
self.view.addSubview(label)
}
@objc private func clickPush(_ sender: UIButton) {
let vc = ViewControllerDemo1()
self.navigationController?.pushViewController(vc, animated: true)
}
@objc private func clickButtonUI(_ sender: UIButton) {
DispatchQueue.global().async {
if self.label.text == "改变文字演示" {
self.label.whc_HeightAuto()
self.label.text = "改变frame演示"
}else {
self.label.whc_Height(40)
self.label.text = "改变文字演示"
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 73759e76bb70153b57b98339f3175240 | 27.0375 | 91 | 0.59251 | 4.093066 | false | false | false | false |
TEDxBerkeley/iOSapp | iOSApp/Data.swift | 1 | 17587 | //
// SpeakersData.swift
// TEDxBerkeley
//
// Created by alvinwan on 1/4/16.
// Copyright (c) 2016 TExBerkeley. All rights reserved.
//
import Foundation
var names = [
"Christopher Ategeka",
"Kathy Calvin",
"Jacob Corn",
"Stephanie Freid",
"Rob Hotchkiss",
"Naveen Jain",
"Jeromy Johnson",
"Reverend Deborah Johnson",
"Aran Khanna",
"John Koenig",
"Ellen Petry Leanse",
"Dr. Susan Lim",
"Oakland School for the Arts Chamber Choir",
"Amandine Roche",
"Dr. Sriram Shamasunder",
"Dr. Andrew Siemion",
"Joshua Toch",
"UC Berkeley Azaad",
"Sonia Rao",
"Isha Ray",
"Celli@Berkeley"
]
var bylines = [
"Engineer and Social Entrepreneur",
"CEO of United Nations Foundation",
"Scientific Director, Innovative Genomics Initiative",
"Journalist",
"Musician",
"Entrepreneur and Philanthropist",
"Expert in EMF Exposure",
"Minister, Author, and Diversity Expert",
"Computer Scientist, Security Researcher",
"Creator, The Dictionary of Obscure Sorrows",
"Digital Pioneer",
"Surgeon and Entrepreneur",
"Oakland School for the Arts",
"Human Rights Expert",
"Co-Founder HEAL Initiative",
"Astrophysicist",
"Founder, Mind Before Mouth",
"UC Berkeley Bollywood Dance Group",
"Singer and Songwriter",
"Professor, Co-Director Berkeley Water Center",
"UC Berkeley Celli Performance Group"
]
var bios = [
"Christopher Ategeka is award-winning social entrepreneur, engineer, and inventor. Among his many inventions is the patent of nanotechnology that can detect and monitor chronic diseases. Ategeka previously served as the founder and CEO of Ride for Lives, a company that builds innovative vehicles to deliver healthcare services in developing countries. He has been recognized in publications such as NPR and BBC for his work as a social entrepreneur. Additionally, Ategeka was included in the 2014 “Forbes 30 Under 30” list. Ategeka is a University of California, Berkeley alumnus, holding a Bachelor of Science and Master of Science in Mechanical Engineering.",
"Kathy Calvin is the President and CEO of the United Nations Foundation. Calvin diverse career, spanning the public, private, and nonprofit sectors, has fueled her passion for multi-sector problem solving. At the United Nations Foundation, Calvin connects people, resources, and ideas in order to advocate for the United Nation’s causes and activities. The United Nation Foundation’s work focuses on decreasing child mortality, empowering women and girls, creating a clean energy future, using mobile technology for development, and improving U.S.-UN relations. Calvin’s philanthropy and leadership have been featured in the New York Times. She was also named one of Newsweek’s “150 Women Who Rock the World.”",
"Jacob Corn is the Scientific Director of the Innovative Genomics Initiative and a University of California, Berkeley faculty member in the department of Molecular and Cell Biology. Corn previously worked at Genentech in the department of Early Discovery Biochemistry, interrogating the feasibility for challenging therapeutic pathways in neurobiology, infectious disease, and oncology. Corn’s current research investigates how biophysical properties interact within the cellular environment to shape signaling behavior, and how disease arises when these properties go awry. At the Innovative Genomics Initiative, Corn seeks to push the boundaries of genome editing in order to improve insight into fundamental biology, and to lay the groundwork for clinical and commercial applications.",
"Stephanie Freid is a television correspondent for China Central Television (CCTV) and Turkish Television International networks. She formerly was a freelance producer for programs including BBC and NBC News. Freid reports from the world’s conflict zones. Her assignments have covered the current refugee crisis, the Israeli-Palestinian Conflict, and Ebola outbreak in West Africa. Furthermore, she has reported on the wars in Syria, Ukraine, Libya, Iraq, and Mali. Freid views her work as a privilege, as her close proximity to conflict provides glimpses of humankind’s ugliest and most incredible traits.",
"Rob Hotchkiss won a Grammy Award (Best Rock Song) for five-time nominated “Drops of Jupiter”, and was the musical force behind hits such as Meet Virginia, Free, I Am , and Get To Me. Rob founded the band, Train, and his songwriting was integral to their multi-platinum success. For creative reasons Rob left Train after their third album to record and produce the solo album, Midnight Ghost, which received tremendous critical acclaim. Rob’s classic sound, with meaningful lyrics, beautiful melodies, and lush harmonies, has been likened to The Beatles, Neil Young, and more current artists like Ed Sheeran. After several years of retirement from music, Rob moved back to the Bay Area to work with Tom Luce (of LUCE) and Charlie Colin (former member of Train) on a project called Painbirds, releasing an eponymous EP in June of 2015. Rob is currently performing as a solo artist, writing songs and performing in the Bay Area and Los Angeles, with plans to tour the West Coast.",
"Naveen Jain is an entrepreneur and philanthropist driven to solve the world’s challenges using innovation. Jain is a founder of many businesses, including InfoSpace, Intelius, and iNome. His latest project is Moon Express, a company dedicated to developing a robotic lunar lander mine the moon for natural resources. Moreover, Jain is a trustee of the board for the X Prize Foundation, a public competition in search for solutions to global challenges in health, education, poverty, agriculture, and clean water. Jain’s leadership and entrepreneurial spirit have earned him many awards, including “Ernst & Young Entrepreneur of the Year” and Silicon India’s “Most Admired Serial Entrepreneur.”",
"Jeromy Johnson is an expert in mitigating the negative impacts of Electromagnetic Field (EMF) exposure. Jeromy has an advanced degree in Civil Engineering and has worked in Silicon Valley for 15 years. After becoming what medical doctors call “Electro-hypersensitive” (EHS) in 2011 due to extensive exposure to EMF radiation, Jeromy immersed himself in the available data on the impacts of EMF exposure. His experience and knowledge inspire us to create new technologies and to utilize existing technologies in ways that are safer for humans, animals and the environment.",
"Deborah Johnson is a voice for compassion, justice, and reconciliation. She is the founder and president of The Motivational Institute, an organizational development consulting firm specializing in diversity, and Inner Light Ministries, which teaches practical applications of Universal Spiritual Principles. She holds a vision of Oneness, beyond creed and doctrine, and builds bridges between those adhering to conservative and progressive ideologies. The ground breaking work of Deborah Johnson has received many awards and been featured in numerous books, magazines, and television programs including appearances on The Donahue Show, ABC Nightline, Showtime, Glamour & Ms. Magazines, Shambhala Sun, and NPR.",
"Aran Khanna is a student-developer, blogger, and student at Harvard who is working to understand the consequences of the increasing role of technology in our lives, particularly in the realm of personal privacy. Aran builds tools that empower users to discover for themselves the consequences of the digital footprint they are leaving. Notably Aran’s work on disclosing the dangers of default location sharing in Facebook Messenger spurred Facebook to remove the feature from Messenger. It also prompted Facebook to rescind Aran’s internship offer, raising questions about how social media companies respond to privacy issues.",
"John Koenig has spent the last decade building a home in every creative field he can find, working as a graphic designer, video editor, voice actor, illustrator, photographer, director, and writer. He has spent the last six years writing an original dictionary of made-up words, The Dictionary of Obscure Sorrows, which fills gaps in the language with hundreds of new terms for emotions, some of which (‘sonder’) have entered the language outright. Business Standard has said “Koenig is a writer to be reckoned with” and stated “The Dictionary is the kind of thing you want to print and bind, and refer to often.”",
"Ellen Petry Leanse is a digital pioneer and road-tested entrepreneur who Ellen has guided entrepreneurs and policy makers in East Africa, India, Italy, Latin America, Asia, and in the U.S. on innovation and strategy. As a digital pioneer and road-tested entrepreneur, Ellen has guided more than 40 technology companies spanning early stage to global leaders including Microsoft, Facebook, Samsung, Intuit, Oracle, and Women 2.0. Additionally, Ellen writes and speaks on innovation, gender, and ethics and is a member of Stanford’s Continuing Education faculty, teaching “Enlightened Innovation” as part of the extended studies curriculum.",
"Dr Susan Lim’s historic performance of the first successful cadaveric liver transplant for Singapore and Asia in 1990 propelled her into the media spotlight at the age of 35. She became the first in Asia, and the second woman in the world to have performed a successful liver transplant at that time. She holds many academic recognitions and honors, and even has an award for continuing medical education named after her for her work in the advancement of Laparoscopic & Minimally Invasive Surgery. Her desire to discover that next big thing keeps her actively focused on robotics and stem cell research. She strongly believes that as society increasingly embraces technology, communication and interactions will extend beyond humans to robots and other inanimates.",
"The Oakland School of the Arts (OSA) Chamber Choir is the largest audition-only high school Vocal ensemble at OSA. They have performed at notable events including President Obama's 2012 campaign tour and the Giants Game at AT&T park, and with celebrities including Sean Penn, Robert Downey Jr., and the band CAKE. In addition,the students have traveled to New Orleans, Italy and Puerto Rico for concert tours. The OSA Chamber Choir is directed by Ms. Cava Menzies.",
"Amandine Roche is a Human Rights expert who has worked with the United Nations, UNICEF, UNDP, UNESCO, and UN WOMEN for over 15 years. Her focus is on civic education, democratization, and gender and youth empowerment. After the kidnapping and assassination of her colleagues, Amandine was evacuated from Kabul, Afganistan. She found her inner peace in India and realized that non-violence was also the only way to achieve harmony for Afghanistan and the whole world. She returned to Kabul to create the Amanuddin Foundation in order to promote a culture of peace and non-violence.",
"Sriram Shamasunder completed his residency in Internal Medicine at Harbor UCLA Medical Center and is currently an Academic Hospitalist at UCSF. Sri has spent the last 10 years working several months a year in Burundi, Haiti, Rwanda and India. He is co-founder of the HEAL initiative, which aims to support workforce capacity in limited resource settings, both in the United States and internationally. In 2010, he received the Young Physician of the Year award from the Northern California Chapter of the American College of Physicians. He is interested in health equity and narrative equity, working towards a world where lives are of equal value both the health care we deliver and the stories we highlight.",
"Dr. Andrew Siemion is an astrophysicist at the University of California (UC), Berkeley and serves as Director of the UC Berkeley Center for Search for Extraterrestrial Intelligence (SETI) Research. His research interests include studies of time-variable celestial phenomena, astronomical instrumentation and SETI. Dr. Siemion is one of the leaders of the “Breakthrough Listen Initiative” – a 10 year, 100 million dollar effort, sponsored by Yuri Milner’s Breakthrough Prize Foundation, that is conducting the most sensitive search for advanced extraterrestrial life in history, and has received many awards for his work on searches for exotic radio phenomena. Dr. Siemion frequently appears on international television and radio discussing the search for life beyond on Earth and the prospects for detection.",
"UC Berkeley sophomore Joshua Toch plans to pursue a degree in Business Administration with a minor in Industrial engineering. At the age of 15, he took a stance against bullying by speaking about his personal experiences with Cerebral Palsy. He founded Mind Before Mouth, a not-for-profit organization that visits schools and clubs to encourage teamwork to get through hardship. Toch is the recipient of the 2014 Morgan Hill Chamber of Commerce Student of the Year and the 2014 Diller Teen Tikkun Olam Award. He has spoken at TEDxUCDavisSF and will be a part of Patricia Wooster’s upcoming book, “So You Want to Be A Leader?” in 2016.",
"UCB Azaad, referring to “independence or freedom”, is excited to bring a fresh, new taste of Bollywood to Berkeley! The team is based on dedication, passion and energy, with the primary goal of creating productions that entertain and motivate audiences to connect with the Bollywood culture.",
"On the surface, Sonia Rao is a pop singer/songwriter with over 35 film and television placements and a BMI Spotlight Artist. Her songs have been featured on MTV’s Jersey Shore, ABC’s The Vineyard, Keeping Up With the Kardashians, and many others. But dig into Sonia’s music and you’ll discover she’s an vessel of inspiration. At a recent TEDxWomen event, she was asked to perform and speak about gender equality, just one of the issues she holds dear. Sonia captivated the room with her energy, and it’s with that same spirit that she welcomes us into her world on her forthcoming album, Meet Them At The Door, her most transparent work yet.",
"Isha Ray is Associate Professor at the Energy and Resources Group and Co-Director (with Professor David Sedlak) of the Berkeley Water Center. She has a BA in Philosophy, Politics and Economics from Oxford University, and a PhD in Applied Economics from the Food Research Institute at Stanford University. Her research projects focus on access to water and sanitation for the rural and urban poor, and on the role of technology in advancing sustainable development goals and improving livelihoods. She has worked on developing access to water in India, China, Turkey, Mexico, Tanzania and California’s Central Valley. Dr. Ray has extensive experience in the international non-profit sector on development and freshwater issues, and is a regular adviser to United Nations Women.",
"Celli@Berkeley was created one night in 2012 after the cellists of the UC Berkeley Symphony Orchestra realized that the only thing better than one cello was many, many cellos. Composed of sixteen students studying a variety of academic disciplines, they are united by a desire to express the possibilities of the cello. They love performing and sharing music ranging from classical to pop, not only in concert halls but also outdoors - by the Campanile, in art galleries, at marathons or flea markets, and on the streets of Berkeley!"
]
var imagesSpeakers = [
"ChristopherAtegeka.jpg",
"KathyCalvin.jpeg",
"JacobCorn.jpeg",
"StephanieFreid.jpg",
"RobHotchkiss.jpg",
"NaveenJain.jpg",
"JeromyJohnson.jpg",
"ReverendDebraJohnson.jpg",
"AranKhanna.png",
"JohnKoenig.jpg",
"EllenLeanse.png",
"DrSusanLim.jpg",
"OSAChamberChoir.jpg",
"AmandineRoche.jpg",
"DrSriramShamasunder.jpg",
"DrAndrewSiemion.jpg",
"JoshuaToche.jpg",
"UCBerkeleyAzaad.jpg",
"SoniaRao.jpg",
"IshaRay.jpg",
"Celli.jpeg"
]
var titles = [
"Registration",
"Celli@Berkeley",
"Naveen Jain",
"Jeromy Johnson",
"Dr. Susan Lim",
"Andrew Siemion",
"Jacob Corn",
"Kathy Calvin",
"Sonia Rao",
"Lunch",
"UC Berkeley Azaad",
"Christopher Ategeka",
"Isha Ray",
"Ellen Petry Leanse",
"Amandine Roche",
"Joshua Toch",
"Reverend Deborah Johnson",
"Oakland School for the Arts Chamber Choir",
"Intermission",
"Oakland School for the Arts - Visual Arts",
"Dr. Sriram Shamasunder",
"Aran Khanna",
"Stephanie Freid",
"John Koenig",
"Rob Hotchkiss",
"Wine Reception"
];
var times = [
"8:30 - 10:00 a.m.",
"10:00 a.m.",
"10:14 a.m.",
"10:30 a.m.",
"10:46 a.m.",
"11:03 a.m.",
"11:19 a.m.",
"11:35 a.m.",
"12:10 p.m.",
"12:20 p.m. - 1:30 p.m.",
"1:30 p.m.",
"1:41 p.m.",
"1:56 p.m.",
"14:09 p.m.",
"2:20 p.m.",
"2:36 p.m.",
"2:47 p.m.",
"3:06 p.m.",
"3:15 p.m. - 3:45 p.m.",
"3:45 p.m.",
"3:51 p.m.",
"4:31 p.m.",
"4:41 p.m.",
"4:58 p.m.",
"5:17 p.m.",
"5:30 p.m."
]
var imagesTimeline = [
"music",
"music",
"speaker",
"speaker",
"speaker",
"speaker",
"speaker",
"speaker",
"speaker",
"music",
"music",
"speaker",
"speaker",
"speaker",
"speaker",
"speaker",
"speaker",
"speaker",
"music",
"music",
"music",
"speaker",
"speaker",
"speaker",
"speaker",
"music"
]
| apache-2.0 | e30c66323e1c0c09880d79dfcc119bda | 90.067708 | 986 | 0.760137 | 3.79861 | false | false | false | false |
KrishMunot/swift | test/IDE/complete_assignment.swift | 6 | 13917 | // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSIGN_1 | FileCheck %s -check-prefix=ASSIGN_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSIGN_2 | FileCheck %s -check-prefix=ASSIGN_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSIGN_3 | FileCheck %s -check-prefix=ASSIGN_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSIGN_4 | FileCheck %s -check-prefix=ASSIGN_4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSIGN_5 | FileCheck %s -check-prefix=ASSIGN_5
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSIGN_6 | FileCheck %s -check-prefix=ASSIGN_6
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSIGN_7 | FileCheck %s -check-prefix=ASSIGN_7
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSIGN_8 | FileCheck %s -check-prefix=ASSIGN_8
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSIGN_9 | FileCheck %s -check-prefix=ASSIGN_9
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSIGN_10 | FileCheck %s -check-prefix=ASSIGN_10
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSIGN_11 | FileCheck %s -check-prefix=ASSIGN_11
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSIGN_12 | FileCheck %s -check-prefix=ASSIGN_12
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSIGN_13 | FileCheck %s -check-prefix=ASSIGN_13
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSIGN_14 | FileCheck %s -check-prefix=ASSIGN_14
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSIGN_15 | FileCheck %s -check-prefix=ASSIGN_15
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSIGN_16 | FileCheck %s -check-prefix=ASSIGN_16
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSIGN_17 | FileCheck %s -check-prefix=ASSIGN_17
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSIGN_18 | FileCheck %s -check-prefix=ASSIGN_18
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ASSIGN_19 | FileCheck %s -check-prefix=ASSIGN_19
class C1 {
var I1 = 1
var I2 = 3
var IO1 : Int?
var S1 = ""
var S2 = ""
var SO1 : String?
enum D1 {
case case1
case case2
}
enum D2 {
case case3
case case4
}
func IntGenerator() -> Int {
return 0
}
func IntOpGenerator() -> Int? {
return 0
}
func StringGenerator() -> String {
return ""
}
func StringOpGenerator() -> String? {
return ""
}
func VoidGen() {}
class C2 {
func IntGen() -> Int { return 1 }
func IntOpGen() -> Int? { return 1 }
func D1Gen() -> D1 { return D1.case1 }
func D2Gen() -> D2 { return D2.case3 }
func VoidGen() {}
var InternalC2 = C2()
}
func C2Gen() -> C2 { return C2() }
func f1() {
var I3 : Int
I3 = #^ASSIGN_1^#
}
// ASSIGN_1: Begin completions
// ASSIGN_1-DAG: Decl[LocalVar]/Local/TypeRelation[Identical]: I3[#Int#]; name=I3
// ASSIGN_1-DAG: Decl[InstanceVar]/CurrNominal/TypeRelation[Identical]: I1[#Int#]; name=I1
// ASSIGN_1-DAG: Decl[InstanceVar]/CurrNominal/TypeRelation[Identical]: I2[#Int#]; name=I2
// ASSIGN_1-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: IntGenerator()[#Int#]; name=IntGenerator()
// ASSIGN_1-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: VoidGen()[#Void#]; name=VoidGen()
// ASSIGN_1-DAG: Decl[InstanceVar]/CurrNominal: S1[#String#]; name=S1
func f2() {
var I3 : Int?
I3 = #^ASSIGN_2^#
}
// ASSIGN_2-DAG: Begin completions
// ASSIGN_2-DAG: Decl[LocalVar]/Local/TypeRelation[Identical]: I3[#Int?#]; name=I3
// ASSIGN_2-DAG: Decl[InstanceVar]/CurrNominal/TypeRelation[Convertible]: I1[#Int#]; name=I1
// ASSIGN_2-DAG: Decl[InstanceVar]/CurrNominal/TypeRelation[Convertible]: I2[#Int#]; name=I2
// ASSIGN_2-DAG: Decl[InstanceVar]/CurrNominal/TypeRelation[Identical]: IO1[#Int?#]; name=IO1
// ASSIGN_2-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Convertible]: IntGenerator()[#Int#]; name=IntGenerator()
// ASSIGN_2-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: IntOpGenerator()[#Int?#]; name=IntOpGenerator()
// ASSIGN_2-DAG: Decl[InstanceVar]/CurrNominal: S1[#String#]; name=S1
func f3() {
var S3 = ""
S3 = #^ASSIGN_3^#
}
// ASSIGN_3-DAG: Begin completions
// ASSIGN_3-DAG: Decl[LocalVar]/Local/TypeRelation[Identical]: S3[#String#]; name=S3
// ASSIGN_3-DAG: Decl[InstanceVar]/CurrNominal/TypeRelation[Identical]: S1[#String#]; name=S1
// ASSIGN_3-DAG: Decl[InstanceVar]/CurrNominal/TypeRelation[Identical]: S2[#String#]; name=S2
// ASSIGN_3-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: StringGenerator()[#String#]; name=StringGenerator()
// ASSIGN_3-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: VoidGen()[#Void#]; name=VoidGen()
// ASSIGN_3-DAG: Decl[InstanceVar]/CurrNominal: I1[#Int#]; name=I1
func f4() {
var S4 : String?
S4 = #^ASSIGN_4^#
}
// ASSIGN_4-DAG: Begin completions
// ASSIGN_4-DAG: Decl[LocalVar]/Local/TypeRelation[Identical]: S4[#String?#]; name=S4
// ASSIGN_4-DAG: Decl[InstanceVar]/CurrNominal/TypeRelation[Convertible]: S1[#String#]; name=S1
// ASSIGN_4-DAG: Decl[InstanceVar]/CurrNominal/TypeRelation[Convertible]: S2[#String#]; name=S2
// ASSIGN_4-DAG: Decl[InstanceVar]/CurrNominal/TypeRelation[Identical]: SO1[#String?#]; name=SO1
// ASSIGN_4-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Convertible]: StringGenerator()[#String#]; name=StringGenerator()
// ASSIGN_4-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: StringOpGenerator()[#String?#]; name=StringOpGenerator()
// ASSIGN_4-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: VoidGen()[#Void#]; name=VoidGen()
// ASSIGN_4-DAG: Decl[InstanceVar]/CurrNominal: I1[#Int#]; name=I1
func f5() {
var d : D1
d = .#^ASSIGN_5^#
}
// ASSIGN_5: Begin completions, 2 items
// ASSIGN_5-DAG: Decl[EnumElement]/ExprSpecific: case2[#C1.D1#]; name=case2
// ASSIGN_5-DAG: Decl[EnumElement]/ExprSpecific: case1[#C1.D1#]; name=case1
func f6() {
var d : D2
d = .#^ASSIGN_6^#
}
// ASSIGN_6: Begin completions, 2 items
// ASSIGN_6-DAG: Decl[EnumElement]/ExprSpecific: case3[#C1.D2#]; name=case3
// ASSIGN_6-DAG:Decl[EnumElement]/ExprSpecific: case4[#C1.D2#]; name=case4
func f7 (C : C2) {
var i : Int
i = C.#^ASSIGN_7^#
}
// ASSIGN_7: Begin completions
// ASSIGN_7-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: IntGen()[#Int#]
// ASSIGN_7-DAG: Decl[InstanceMethod]/CurrNominal: IntOpGen()[#Int?#]
// ASSIGN_7-DAG: Decl[InstanceMethod]/CurrNominal: D1Gen()[#C1.D1#]
// ASSIGN_7-DAG: Decl[InstanceMethod]/CurrNominal: D2Gen()[#C1.D2#]
// ASSIGN_7-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: VoidGen()[#Void#]
// ASSIGN_7-DAG: Decl[InstanceVar]/CurrNominal: InternalC2[#C1.C2#]
func f8 (C : C2) {
var i : Int?
i = C.#^ASSIGN_8^#
}
// ASSIGN_8: Begin completions
// ASSIGN_8-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Convertible]: IntGen()[#Int#]
// ASSIGN_8-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: IntOpGen()[#Int?#]
// ASSIGN_8-DAG: Decl[InstanceMethod]/CurrNominal: D1Gen()[#C1.D1#]
// ASSIGN_8-DAG: Decl[InstanceMethod]/CurrNominal: D2Gen()[#C1.D2#]
// ASSIGN_8-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: VoidGen()[#Void#]
// ASSIGN_8-DAG: Decl[InstanceVar]/CurrNominal: InternalC2[#C1.C2#]
func f9 (C : C2) {
var d : D1
d = C.#^ASSIGN_9^#
}
// ASSIGN_9: Begin completions
// ASSIGN_9-DAG: Decl[InstanceMethod]/CurrNominal: IntGen()[#Int#]
// ASSIGN_9-DAG: Decl[InstanceMethod]/CurrNominal: IntOpGen()[#Int?#]
// ASSIGN_9-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: D1Gen()[#C1.D1#]
// ASSIGN_9-DAG: Decl[InstanceMethod]/CurrNominal: D2Gen()[#C1.D2#]
// ASSIGN_9-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: VoidGen()[#Void#]
// ASSIGN_9-DAG: Decl[InstanceVar]/CurrNominal: InternalC2[#C1.C2#]
func f10 (C : C2) {
var d : D1
d = C.InternalC2.#^ASSIGN_10^#
}
// ASSIGN_10: Begin completions
// ASSIGN_10-DAG: Decl[InstanceMethod]/CurrNominal: IntGen()[#Int#]
// ASSIGN_10-DAG: Decl[InstanceMethod]/CurrNominal: IntOpGen()[#Int?#]
// ASSIGN_10-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: D1Gen()[#C1.D1#]
// ASSIGN_10-DAG: Decl[InstanceMethod]/CurrNominal: D2Gen()[#C1.D2#]
// ASSIGN_10-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: VoidGen()[#Void#]
// ASSIGN_10-DAG: Decl[InstanceVar]/CurrNominal: InternalC2[#C1.C2#]
func f11(C: C2) {
d = C.#^ASSIGN_11^#
}
// ASSIGN_11: Begin completions
// ASSIGN_11-DAG: Decl[InstanceMethod]/CurrNominal: IntGen()[#Int#]
// ASSIGN_11-DAG: Decl[InstanceMethod]/CurrNominal: IntOpGen()[#Int?#]
// ASSIGN_11-DAG: Decl[InstanceMethod]/CurrNominal: D1Gen()[#C1.D1#]
// ASSIGN_11-DAG: Decl[InstanceMethod]/CurrNominal: D2Gen()[#C1.D2#]
// ASSIGN_11-DAG: Decl[InstanceMethod]/CurrNominal: VoidGen()[#Void#]
// ASSIGN_11-DAG: Decl[InstanceVar]/CurrNominal: InternalC2[#C1.C2#]
func f12() {
var i : Int
i = C2Gen().#^ASSIGN_12^#
}
// ASSIGN_12: Begin completions
// ASSIGN_12-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: IntGen()[#Int#]
// ASSIGN_12-DAG: Decl[InstanceMethod]/CurrNominal: IntOpGen()[#Int?#]
// ASSIGN_12-DAG: Decl[InstanceMethod]/CurrNominal: D1Gen()[#C1.D1#]
// ASSIGN_12-DAG: Decl[InstanceMethod]/CurrNominal: D2Gen()[#C1.D2#]
// ASSIGN_12-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: VoidGen()[#Void#]
// ASSIGN_12-DAG: Decl[InstanceVar]/CurrNominal: InternalC2[#C1.C2#]
func f13() {
var i : Int = #^ASSIGN_13^#
}
// ASSIGN_13: Begin completions
// ASSIGN_13-DAG: Decl[InstanceVar]/CurrNominal/TypeRelation[Identical]: I1[#Int#]; name=I1
// ASSIGN_13-DAG: Decl[InstanceVar]/CurrNominal/TypeRelation[Identical]: I2[#Int#]; name=I2
// ASSIGN_13-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: IntGenerator()[#Int#]; name=IntGenerator()
// ASSIGN_13-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: VoidGen()[#Void#]; name=VoidGen()
// ASSIGN_13-DAG: Decl[InstanceVar]/CurrNominal: S1[#String#]; name=S1
func f14() {
let i : Int? = #^ASSIGN_14^#
}
// ASSIGN_14-DAG: Begin completions
// ASSIGN_14-DAG: Decl[InstanceVar]/CurrNominal/TypeRelation[Convertible]: I1[#Int#]; name=I1
// ASSIGN_14-DAG: Decl[InstanceVar]/CurrNominal/TypeRelation[Convertible]: I2[#Int#]; name=I2
// ASSIGN_14-DAG: Decl[InstanceVar]/CurrNominal/TypeRelation[Identical]: IO1[#Int?#]; name=IO1
// ASSIGN_14-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Convertible]: IntGenerator()[#Int#]; name=IntGenerator()
// ASSIGN_14-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: IntOpGenerator()[#Int?#]; name=IntOpGenerator()
// ASSIGN_14-DAG: Decl[InstanceVar]/CurrNominal: S1[#String#]; name=S1
func f15() {
let i = #^ASSIGN_15^#
}
// ASSIGN_15-NOT: TypeRelation
func f16 (C : C2) {
var d : D1 = C.InternalC2.#^ASSIGN_16^#
}
// ASSIGN_16: Begin completions
// ASSIGN_16-DAG: Decl[InstanceMethod]/CurrNominal: IntGen()[#Int#]
// ASSIGN_16-DAG: Decl[InstanceMethod]/CurrNominal: IntOpGen()[#Int?#]
// ASSIGN_16-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: D1Gen()[#C1.D1#]
// ASSIGN_16-DAG: Decl[InstanceMethod]/CurrNominal: D2Gen()[#C1.D2#]
// ASSIGN_16-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: VoidGen()[#Void#]
// ASSIGN_16-DAG: Decl[InstanceVar]/CurrNominal: InternalC2[#C1.C2#]
func f17() {
var i : Int = C2Gen().#^ASSIGN_17^#
}
// ASSIGN_17: Begin completions
// ASSIGN_17-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: IntGen()[#Int#]
// ASSIGN_17-DAG: Decl[InstanceMethod]/CurrNominal: IntOpGen()[#Int?#]
// ASSIGN_17-DAG: Decl[InstanceMethod]/CurrNominal: D1Gen()[#C1.D1#]
// ASSIGN_17-DAG: Decl[InstanceMethod]/CurrNominal: D2Gen()[#C1.D2#]
// ASSIGN_17-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: VoidGen()[#Void#]
// ASSIGN_17-DAG: Decl[InstanceVar]/CurrNominal: InternalC2[#C1.C2#]
func f18 (C : C2) {
var d : D1 = C.#^ASSIGN_18^#
}
// ASSIGN_18: Begin completions
// ASSIGN_18-DAG: Decl[InstanceMethod]/CurrNominal: IntGen()[#Int#]
// ASSIGN_18-DAG: Decl[InstanceMethod]/CurrNominal: IntOpGen()[#Int?#]
// ASSIGN_18-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: D1Gen()[#C1.D1#]
// ASSIGN_18-DAG: Decl[InstanceMethod]/CurrNominal: D2Gen()[#C1.D2#]
// ASSIGN_18-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: VoidGen()[#Void#]
// ASSIGN_18-DAG: Decl[InstanceVar]/CurrNominal: InternalC2[#C1.C2#]
}
class Test19 {
func test() {
let t = true
prop = #^ASSIGN_19^#
}
var prop: Bool
}
// rdar://23111219
// ASSIGN_19: Decl[LocalVar]/Local/TypeRelation[Identical]: t[#Bool#]
| apache-2.0 | 567a4bfca60ec27b57e4aa72b4f729f1 | 46.660959 | 139 | 0.687002 | 3.333413 | false | true | false | false |
KrishMunot/swift | stdlib/public/core/ShadowProtocols.swift | 1 | 5966 | //===--- ShadowProtocols.swift - Protocols for decoupled ObjC bridging ----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// To implement bridging, the core standard library needs to interact
// a little bit with Cocoa. Because we want to keep the core
// decoupled from the Foundation module, we can't use foundation
// classes such as NSArray directly. We _can_, however, use an @objc
// protocols whose API is "layout-compatible" with that of NSArray,
// and use unsafe casts to treat NSArray instances as instances of
// that protocol.
//
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
import SwiftShims
@objc
public protocol _ShadowProtocol {}
/// A shadow for the `NSFastEnumeration` protocol.
@objc
public protocol _NSFastEnumeration : _ShadowProtocol {
@objc(countByEnumeratingWithState:objects:count:)
func countByEnumeratingWith(
_ state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>, count: Int
) -> Int
}
/// A shadow for the `NSEnumerator` class.
@objc
public protocol _NSEnumerator : _ShadowProtocol {
init()
func nextObject() -> AnyObject?
}
/// A token that can be used for `NSZone*`.
public typealias _SwiftNSZone = OpaquePointer
/// A shadow for the `NSCopying` protocol.
@objc
public protocol _NSCopying : _ShadowProtocol {
@objc(copyWithZone:)
func copy(with zone: _SwiftNSZone) -> AnyObject
}
/// A shadow for the "core operations" of NSArray.
///
/// Covers a set of operations everyone needs to implement in order to
/// be a useful `NSArray` subclass.
@unsafe_no_objc_tagged_pointer @objc
public protocol _NSArrayCore :
_NSCopying, _NSFastEnumeration {
@objc(objectAtIndex:)
func objectAt(_ index: Int) -> AnyObject
func getObjects(_: UnsafeMutablePointer<AnyObject>, range: _SwiftNSRange)
@objc(countByEnumeratingWithState:objects:count:)
func countByEnumeratingWith(
_ state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>, count: Int
) -> Int
var count: Int { get }
}
/// A shadow for the "core operations" of NSDictionary.
///
/// Covers a set of operations everyone needs to implement in order to
/// be a useful `NSDictionary` subclass.
@objc
public protocol _NSDictionaryCore :
_NSCopying, _NSFastEnumeration {
// The following methods should be overridden when implementing an
// NSDictionary subclass.
// The designated initializer of `NSDictionary`.
init(
objects: UnsafePointer<AnyObject?>,
forKeys: UnsafePointer<Void>, count: Int)
var count: Int { get }
@objc(objectForKey:)
func objectFor(_ aKey: AnyObject) -> AnyObject?
func keyEnumerator() -> _NSEnumerator
// We also override the following methods for efficiency.
@objc(copyWithZone:)
func copy(with zone: _SwiftNSZone) -> AnyObject
func getObjects(_ objects: UnsafeMutablePointer<AnyObject>,
andKeys keys: UnsafeMutablePointer<AnyObject>)
@objc(countByEnumeratingWithState:objects:count:)
func countByEnumeratingWith(
_ state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>, count: Int
) -> Int
}
/// A shadow for the API of `NSDictionary` we will use in the core
/// stdlib.
///
/// `NSDictionary` operations, in addition to those on
/// `_NSDictionaryCore`, that we need to use from the core stdlib.
/// Distinct from `_NSDictionaryCore` because we don't want to be
/// forced to implement operations that `NSDictionary` already
/// supplies.
@unsafe_no_objc_tagged_pointer @objc
public protocol _NSDictionary : _NSDictionaryCore {
// Note! This API's type is different from what is imported by the clang
// importer.
func getObjects(_ objects: UnsafeMutablePointer<AnyObject>,
andKeys keys: UnsafeMutablePointer<AnyObject>)
}
/// A shadow for the "core operations" of NSSet.
///
/// Covers a set of operations everyone needs to implement in order to
/// be a useful `NSSet` subclass.
@objc
public protocol _NSSetCore :
_NSCopying, _NSFastEnumeration {
// The following methods should be overridden when implementing an
// NSSet subclass.
// The designated initializer of `NSSet`.
init(objects: UnsafePointer<AnyObject?>, count: Int)
var count: Int { get }
func member(_ object: AnyObject) -> AnyObject?
func objectEnumerator() -> _NSEnumerator
// We also override the following methods for efficiency.
@objc(copyWithZone:)
func copy(with zone: _SwiftNSZone) -> AnyObject
@objc(countByEnumeratingWithState:objects:count:)
func countByEnumeratingWith(
_ state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>, count: Int
) -> Int
}
/// A shadow for the API of NSSet we will use in the core
/// stdlib.
///
/// `NSSet` operations, in addition to those on
/// `_NSSetCore`, that we need to use from the core stdlib.
/// Distinct from `_NSSetCore` because we don't want to be
/// forced to implement operations that `NSSet` already
/// supplies.
@unsafe_no_objc_tagged_pointer @objc
public protocol _NSSet : _NSSetCore {
}
/// A shadow for the API of NSNumber we will use in the core
/// stdlib.
@objc
public protocol _NSNumber {
var doubleValue: Double { get }
var floatValue: Float { get }
var unsignedLongLongValue: UInt64 { get }
var longLongValue: Int64 { get }
var objCType: UnsafePointer<Int8> { get }
}
#else
public protocol _NSArrayCore {}
public protocol _NSDictionaryCore {}
public protocol _NSSetCore {}
#endif
| apache-2.0 | afd230e9fa6a632cd276ffefb262c386 | 30.235602 | 80 | 0.70885 | 4.495855 | false | false | false | false |
xibe/WordPress-iOS | WordPress/Classes/ViewRelated/Reader/ReaderSiteStreamHeader.swift | 1 | 2264 | import Foundation
@objc public class ReaderSiteStreamHeader: UIView, ReaderStreamHeader
{
@IBOutlet private weak var avatarImageView: UIImageView!
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var detailLabel: UILabel!
@IBOutlet private weak var followButton: PostMetaButton!
@IBOutlet private weak var followCountLabel: UILabel!
@IBOutlet private weak var descriptionLabel: UILabel!
@IBOutlet private weak var descriptionBottomConstraint: NSLayoutConstraint!
@IBOutlet private weak var followCountBottomConstraint: NSLayoutConstraint!
public var delegate: ReaderStreamHeaderDelegate?
private var defaultBlavatar = "blavatar-default"
// MARK: - Lifecycle Methods
public override func awakeFromNib() {
super.awakeFromNib()
applyStyles()
}
func applyStyles() {
backgroundColor = WPStyleGuide.greyLighten30()
WPStyleGuide.applyReaderStreamHeaderTitleStyle(titleLabel)
WPStyleGuide.applyReaderStreamHeaderDetailStyle(detailLabel)
WPStyleGuide.applyReaderSiteStreamDescriptionStyle(descriptionLabel)
WPStyleGuide.applyReaderSiteStreamCountStyle(followCountLabel)
}
// MARK: - Configuration
public func configureHeader(topic: ReaderAbstractTopic) {
// TODO: Wire up actual display when supported in core data
avatarImageView.setImageWithURL(nil, placeholderImage: UIImage(named: defaultBlavatar))
titleLabel.text = topic.title
detailLabel.text = "site.com"
if topic.following {
WPStyleGuide.applyReaderStreamHeaderFollowingStyle(followButton)
} else {
WPStyleGuide.applyReaderStreamHeaderNotFollowingStyle(followButton)
}
followCountLabel.text = "100 followers"
descriptionLabel.text = "Just another WordPress site"
// var attributes = WPStyleGuide.readerStreamHeaderDescriptionAttributes()
// var attributedText = NSAttributedString(string: topic.description, attributes: attributes)
// descriptionLabel.attributedText = attributedText
}
// MARK: - Actions
@IBAction func didTapFollowButton(sender: UIButton) {
delegate?.handleFollowActionForHeader(self)
}
}
| gpl-2.0 | ef01688fc19059bc60267f1a0665a1b8 | 36.733333 | 100 | 0.734099 | 5.562654 | false | false | false | false |
combes/audio-weather | AudioWeather/AudioWeather/MainViewController.swift | 1 | 4527 | //
// MainViewController.swift
// AudioWeather
//
// Created by Christopher Combes on 6/16/17.
// Copyright © 2017 Christopher Combes. All rights reserved.
//
import AVFoundation
import UIKit
import SwiftyJSON
import RevealingSplashView
class MainViewController: UIViewController {
@IBOutlet weak var background: UIImageView!
@IBOutlet weak var city: UILabel!
@IBOutlet weak var condition: UILabel!
@IBOutlet weak var temperature: UILabel!
@IBOutlet weak var windDirection: UILabel!
@IBOutlet weak var windChill: UILabel!
@IBOutlet weak var windSpeed: UILabel!
@IBOutlet weak var sunrise: UILabel!
@IBOutlet weak var sunset: UILabel!
@IBOutlet weak var windX: UIImageView!
@IBOutlet weak var locationBackground: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Start refresh immediately
WeatherLoader().refresh()
// Set navigation bar to transparent
navigationController?.makeTransparent()
let searchItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.search, target: self, action: #selector(showSearch))
navigationItem.rightBarButtonItem = searchItem
NotificationCenter.default.addObserver(self, selector: #selector(updateFieldsFromNotification), name: .weatherNotification, object: nil)
// Show splash view for snazzyness
let revealingSplashView = RevealingSplashView(iconImage: UIImage(named: "storm")!, iconInitialSize: CGSize(width: 70, height: 70), backgroundColor: UIColor.white)
self.view.addSubview(revealingSplashView)
revealingSplashView.duration = 0.9
revealingSplashView.useCustomIconColor = false
revealingSplashView.animationType = SplashAnimationType.popAndZoomOut
revealingSplashView.startAnimation(){
self.setNeedsStatusBarAppearanceUpdate()
print("Completed")
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateFieldsMainThread()
}
func updateFieldsWith(model: WeatherModel) {
let viewModel = WeatherViewModel(model: model)
city.text = viewModel.city
condition.text = viewModel.conditionText
temperature.text = viewModel.temperature
windDirection.text = viewModel.windDirection
windChill.text = viewModel.windChill
windSpeed.text = viewModel.windSpeed
sunrise.text = viewModel.sunrise
sunset.text = viewModel.sunset
locationBackground.image = viewModel.backgroundImage()
// Rotate wind vane based on wind speed.
// Using a fudge factor of 120 / speed which provides ample visible animation.
if let speedValue = Double(model.windSpeed) {
self.windX.rotate360Degrees(duration: 120 / speedValue)
}
}
func updateFieldsMainThread() {
if !isInternetAvailable() {
showNetworkOutage(view: self.view)
}
let data = WeatherLoader().data
let model = WeatherModel(json: data)
updateFieldsWith(model: model)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()) {
WeatherVoice.shared.speakWeather(model)
}
}
// MARK: Animations
func animateLabelColors() {
UIView.transition(with: self.view, duration: 1.0, options: UIViewAnimationOptions.transitionCrossDissolve, animations: {
self.city.textColor = UIColor.red
self.condition.textColor = UIColor.red
self.temperature.textColor = UIColor.red
}) { (completed) in
self.city.textColor = UIColor.white
self.condition.textColor = UIColor.white
self.temperature.textColor = UIColor.white
}
}
// MARK: Action methods
func showSearch() {
performSegue(withIdentifier: "search", sender: self)
}
// MARK: Helper methods
func updateFieldsFromNotification() {
DispatchQueue.main.async {
self.updateFieldsMainThread()
// Animate labels only when data is refreshed from server
self.animateLabelColors()
}
}
}
| mit | dc9814cccec4d8cf21b76bcc548fc145 | 32.776119 | 170 | 0.662837 | 5.172571 | false | false | false | false |
broccolii/Demos | DEMO01-Layers/Layers/AnimatedContentsDisplayLayer.swift | 1 | 641 |
//
// AnimatedContentsDisplayLayer.swift
// Layers
//
// Created by Broccoli on 16/6/24.
// Copyright © 2016年 Razeware LLC. All rights reserved.
//
import UIKit
class AnimatedContentsDisplayLayer: _ASDisplayLayer {
override func actionForKey(event: String) -> CAAction? {
if let action = super.actionForKey(event) {
return action
}
if event == "contents" && contents == nil {
let transition = CATransition()
transition.duration = 0.6
transition.type = kCATransitionFade
return transition
}
return nil
}
}
| mit | c19d89787e66b19b6dfad61b984ab5ca | 22.62963 | 60 | 0.592476 | 4.524823 | false | false | false | false |
lovemo/SEKNavigationView | SEKNavigationView/SEKNavigationView.swift | 1 | 7414 | //
// SEKNavigationView.swift
// NavigationViewDemo
//
// Created by Mac on 16/8/24.
// Copyright © 2016年 Mac. All rights reserved.
//
import UIKit
/// 导航栏代理
@objc protocol SEKNavigationViewDelegate{
/// 导航栏按钮点击
func navButtonClick(_ button: UIButton)
/// 导航栏按钮点击
@objc optional func navLeftButtonClick(_ button: UIButton)
/// 导航栏按钮点击
@objc optional func navRightButtonClick(_ button: UIButton)
}
class SEKNavigationView: UIView {
/// 内部按钮点击代理
weak var delegate: SEKNavigationViewDelegate?
/// 当前选中的按钮
lazy var selectedButton = UIButton()
/// 是否铺满
var isFillout = false
/// 是否默认选中中间按钮
var isSelectedMiddleButton = false
/// 标题视图的宽度
var titlesViewW: CGFloat = 0.0 {
didSet{
setNeedsLayout()
}
}
/// 标题视图中按钮的间隔距离
var titlesViewMargin: CGFloat = 6.0 {
didSet{
setNeedsLayout()
}
}
/// 指示器与按钮的间隔距离
var indicatorViewMargin: CGFloat = 5.0 {
didSet{
setNeedsLayout()
}
}
/// 标题按钮的正常颜色,即非选中颜色,建议在设置标题数组前设置此属性
var titleButtonNormalColor:UIColor = UIColor.gray
/// 标题按钮的禁用颜色,即选中颜色,防止用户多次点击,建议在设置标题数组前设置此属性
var titleButtonDisabledColor:UIColor = UIColor.red
/// 标题按钮的文字大小,建议在设置标题数组前设置此属性
var titleButtonTitleFont: UIFont = UIFont.systemFont(ofSize: 14)
/// 顶部的所有标签
lazy var titlesView: UIScrollView = {
// 标签栏整体
let titlesView = UIScrollView()
titlesView.showsVerticalScrollIndicator = false
titlesView.showsHorizontalScrollIndicator = false
titlesView.backgroundColor = UIColor.white.withAlphaComponent(0.7)
self.addSubview(titlesView)
return titlesView
}()
/// 标签栏底部的红色指示器
lazy var indicatorView: UIView = {
let indicatorView = UIView()
// 底部的红色指示器
indicatorView.backgroundColor = UIColor.red
indicatorView.tag = -1
return indicatorView
}()
/// 左边按钮,默认隐藏
lazy var leftButton: UIButton? = {
let leftButton = UIButton()
leftButton.isHidden = true
leftButton.addTarget(self, action: #selector(SEKNavigationView.leftButtonClick(_:)), for: .touchUpInside)
self.addSubview(leftButton)
return leftButton
}()
/// 右边按钮,默认隐藏
lazy var rightButton: UIButton? = {
let rightButton = UIButton()
rightButton.isHidden = true
rightButton.addTarget(self, action: #selector(SEKNavigationView.rightButtonClick(_:)), for: .touchUpInside)
self.addSubview(rightButton)
return rightButton
}()
/// 标题数组
var titles: [String]? {
didSet {
guard let titles = titles else { return}
for i in 0..<titles.count {
let button = UIButton()
button.tag = i
button.setTitle(titles[i], for: UIControlState())
button.setTitleColor(titleButtonNormalColor, for: UIControlState())
button.setTitleColor(titleButtonDisabledColor, for: .disabled)
button.titleLabel?.font = titleButtonTitleFont
button.addTarget(self, action: #selector(SEKNavigationView.titleClick(_:)), for: .touchUpInside)
titlesView.addSubview(button)
// 默认点击了哪个个按钮
if i == (self.isSelectedMiddleButton ? ((titles.count - 1) / 2) : 0) {
button.isEnabled = false
selectedButton = button
}
}
titlesView.addSubview(indicatorView)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func titleClick(_ button: UIButton)
{
// 修改按钮状态
selectedButton.isEnabled = true
button.isEnabled = false
selectedButton = button
// 动画
UIView.animate(withDuration: 0.25, animations: {
self.indicatorView.width = self.isFillout ? self.titlesViewW / CGFloat(self.titles!.count) : button.titleLabel!.width
self.indicatorView.centerX = button.centerX;
})
delegate?.navButtonClick(button)
}
func leftButtonClick( _ button: UIButton) {
delegate?.navLeftButtonClick!(button)
}
func rightButtonClick( _ button: UIButton) {
delegate?.navRightButtonClick!(button)
}
override func layoutSubviews() {
super.layoutSubviews()
let buttonItemX: CGFloat = 14.0
let buttonItemW: CGFloat = 28
// 布局左边按钮
leftButton?.x = buttonItemX
leftButton?.y = (self.height - buttonItemW) * 0.5
leftButton?.width = buttonItemW
leftButton?.height = buttonItemW
// 布局右边按钮
rightButton?.x = self.width - buttonItemX - buttonItemW
rightButton?.y = (self.height - buttonItemW) * 0.5
rightButton?.width = buttonItemW
rightButton?.height = buttonItemW
// 布局titlesView
guard let titles = titles else { return}
if titles.count <= 0 || titlesView.subviews.count <= 0 {return}
self.titlesView.frame = self.bounds
self.titlesView.width = titlesViewW
self.titlesView.centerX = self.centerX
indicatorView.height = 3
indicatorView.y = titlesView.height - indicatorView.height
let height = titlesView.height
var lastBtn = UIButton()
lastBtn.frame = CGRect.zero
for i in 0..<titles.count {
if !titlesView.subviews[i].isKind(of: UIButton.classForCoder()) {
continue
}
let button = titlesView.subviews[i] as! UIButton
button.tag = i
button.height = height
button.sizeToFit()
button.x = lastBtn.frame.maxX + titlesViewMargin
lastBtn = button
// 布局指示器的位置
self.indicatorView.y = button.frame.maxY + indicatorViewMargin
if i == (self.isSelectedMiddleButton ? ((titles.count - 1) / 2) : 0) {
// 让按钮内部的label根据文字内容来计算尺寸
button.titleLabel!.sizeToFit()
self.indicatorView.width = self.isFillout ? self.titlesViewW / CGFloat(self.titles!.count) : button.titleLabel!.width
self.indicatorView.centerX = button.centerX
}
if i == titles.count - 1 {
// 设置titlesView的contentSize
titlesView.contentSize = CGSize(width: button.frame.maxX, height: titlesView.height)
}
}
}
}
| mit | 17267e9aefbebe1ce9bc59b2f631df1a | 30.288991 | 133 | 0.584958 | 4.687973 | false | false | false | false |
cuappdev/podcast-ios | old/Podcast/SearchDiscoverViewController.swift | 1 | 23848 | //
// SearchDiscoverViewController.swift
// Podcast
//
// Created by Natasha Armbrust on 10/14/17.
// Copyright © 2017 Cornell App Development. All rights reserved.
//
import UIKit
import SnapKit
enum SearchType: Int {
case episodes = 0
case series = 1
case people = 2
static let allValues: [SearchType] = [.series, .episodes, .people]
func toString() -> String {
switch self {
case .episodes:
return "Episodes"
case .series:
return "Series"
case .people:
return "People"
}
}
var endpointType: SearchEndpointRequest.Type {
switch self {
case .series:
return SearchSeriesEndpointRequest.self
case .episodes:
return SearchEpisodesEndpointRequest.self
case .people:
return SearchUsersEndpointRequest.self
}
}
var identifiers: String {
switch self {
case .series:
return "SearchSeries"
case .episodes:
return "SearchEpisode"
case .people:
return "SearchPeople"
}
}
var cells: UITableViewCell.Type {
switch self {
case .series:
return SearchSeriesTableViewCell.self
case .episodes:
return SearchEpisodeTableViewCell.self
case .people:
return SearchPeopleTableViewCell.self
}
}
var cellHeight: CGFloat {
switch self {
case .series:
return SearchSeriesTableViewCell.height
case .episodes:
return SearchEpisodeTableViewCell.height
case .people:
return SearchPeopleTableViewCell.cellHeight
}
}
var path: String {
switch self {
case .series:
return "series"
case .episodes:
return "episodes"
case .people:
return "users"
}
}
}
protocol SearchTableViewDelegate: class {
func didSelectCell(cell: UITableViewCell, object: Any)
func didPressFollowButton(cell: SearchPeopleTableViewCell)
func didPressSubscribeButton(cell: SearchSeriesTableViewCell)
func didPressPlayButton(cell: SearchEpisodeTableViewCell)
func didPressViewAllButton(type: SearchType, results: [SearchType: [Any]])
func refreshController()
func hideSearchFooter()
func showSearchFooter()
}
class SearchDiscoverViewController: ViewController {
override var usesLargeTitles: Bool { get { return false } }
var previousSearches: [String] = []
var searchController: UISearchController!
var pastSearchesTableView: EmptyStateTableView!
var searchResultsTableView: EmptyStateTableView!
var searchFooterView: SearchFooterView!
let searchITunesHeaderHeight: CGFloat = 67.5
var tableViewData: MainSearchDataSourceDelegate!
var hasLoaded: Bool = false
var lastSearchText: String = ""
var searchDelayTimer: Timer?
var currentlyPlayingIndexPath: IndexPath?
var pastSearchKey = "PastSearches"
var discoverVC: DiscoverViewController!
var discoverContainerView: UIView!
var sections = SearchType.allValues
let topOffset:CGFloat = 36
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .offWhite
tableViewData = MainSearchDataSourceDelegate()
tableViewData.delegate = self
searchResultsTableView = EmptyStateTableView(frame: .zero, type: .search, style: .grouped)
searchResultsTableView.emptyStateView.delegate = self
searchResultsTableView.sectionFooterHeight = 0
searchResultsTableView.dataSource = tableViewData
searchResultsTableView.delegate = tableViewData
searchResultsTableView.emptyStateView.backgroundColor = .paleGrey
searchResultsTableView.startLoadingAnimation()
SearchType.allValues.forEach { searchType in
searchResultsTableView.register(searchType.cells, forCellReuseIdentifier: searchType.identifiers)
}
view.addSubview(searchResultsTableView)
searchFooterView = SearchFooterView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: SearchFooterView.height))
searchFooterView.delegate = self
searchFooterView.isHidden = true
searchResultsTableView.tableFooterView = searchFooterView
searchResultsTableView.layoutSubviews()
searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.searchBar.delegate = self
let cancelButtonAttributes: [NSAttributedStringKey : Any] = [.foregroundColor: UIColor.sea]
UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes, for: .normal)
searchController.searchBar.showsCancelButton = false
searchController.searchBar.searchBarStyle = .minimal
searchController.searchBar.placeholder = "Search"
searchController.delegate = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.isActive = true
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
navigationItem.titleView = searchController?.searchBar
//IMPORTANT: Does not implement EmptyStateTableViewDelegate because pastSearch does not have an action button
pastSearchesTableView = EmptyStateTableView(frame: .zero, type: .pastSearch)
pastSearchesTableView.register(PreviousSearchResultTableViewCell.self, forCellReuseIdentifier: "PastSearchCell")
pastSearchesTableView.delegate = self
pastSearchesTableView.dataSource = self
pastSearchesTableView.stopLoadingAnimation()
let clearSearchView = ClearSearchFooterView()
clearSearchView.frame.size.height = PreviousSearchResultTableViewCell.height
clearSearchView.delegate = self
pastSearchesTableView.tableFooterView = clearSearchView
view.addSubview(pastSearchesTableView)
mainScrollView = pastSearchesTableView
pastSearchesTableView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
searchResultsTableView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
discoverContainerView = UIView()
view.addSubview(discoverContainerView)
discoverVC = DiscoverViewController()
addChildViewController(discoverVC)
discoverContainerView.addSubview(discoverVC.view)
discoverContainerView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
discoverVC.view.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
hasLoaded = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
navigationController?.navigationBar.prefersLargeTitles = false
pastSearchesTableViewReloadData()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.navigationBar.prefersLargeTitles = true
searchController?.searchBar.isHidden = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
searchController?.searchBar.isHidden = false
}
func pastSearchesTableViewReloadData() {
previousSearches = UserDefaults.standard.value(forKey: pastSearchKey) as? [String] ?? []
pastSearchesTableView.tableFooterView?.isHidden = previousSearches.isEmpty
pastSearchesTableView.reloadData()
}
func addPastSearches() {
guard let searchText = searchController.searchBar.text else { return }
if searchText.isEmpty { return }
if var userDefaultSearches = UserDefaults.standard.value(forKey: pastSearchKey) as? [String] {
if !userDefaultSearches.contains(searchText) {
userDefaultSearches.insert(searchText, at: 0)
UserDefaults.standard.set(userDefaultSearches, forKey: pastSearchKey)
}
} else {
UserDefaults.standard.set([searchText], forKey: pastSearchKey)
}
}
func removePastSearch(index: Int) {
if var userDefaultSearches = UserDefaults.standard.value(forKey: pastSearchKey) as? [String] {
userDefaultSearches.remove(at: index)
UserDefaults.standard.set(userDefaultSearches, forKey: pastSearchKey)
}
}
}
// MARK: TableView Data Source
extension SearchDiscoverViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "PastSearchCell") as? PreviousSearchResultTableViewCell else { return UITableViewCell() }
cell.label.text = previousSearches[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .normal, title: "Delete") { _, _ in
self.removePastSearch(index: indexPath.row)
self.pastSearchesTableViewReloadData()
}
delete.backgroundColor = .sea
return [delete]
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return previousSearches.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return PreviousSearchResultTableViewCell.height
}
}
// MARK: TableView Delegate
extension SearchDiscoverViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let priorSearches = UserDefaults.standard.value(forKey: pastSearchKey) as? [String] else { return }
searchController.isActive = true
searchController.searchBar.text = priorSearches[indexPath.row]
searchController.searchResultsUpdater?.updateSearchResults(for: searchController)
}
}
// MARK: UISearchController Delegate
extension SearchDiscoverViewController: UISearchControllerDelegate, UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
guard let searchText = searchController.searchBar.text, searchText != "" else {
if hasLoaded {
searchResultsTableView.isHidden = true
pastSearchesTableView.isHidden = false
pastSearchesTableViewReloadData()
mainScrollView = pastSearchesTableView
}
return
}
if lastSearchText == searchText && pastSearchesTableView.isHidden {
return
}
hideSearchFooter()
tableViewData.resetResults()
lastSearchText = searchText
searchResultsTableView.isHidden = false
pastSearchesTableView.isHidden = true
mainScrollView = searchResultsTableView
searchResultsTableView.startLoadingAnimation()
searchResultsTableView.loadingAnimation.bringSubview(toFront: searchResultsTableView)
updateTableViewInsetsForAccessoryView()
tableViewData.completingNewSearch = true
searchResultsTableView.reloadData()
if let timer = searchDelayTimer {
timer.invalidate()
searchDelayTimer = nil
}
searchDelayTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(searchAfterDelay), userInfo: nil, repeats: false)
}
@objc func searchAfterDelay() {
tableViewData.fetchData(query: lastSearchText)
}
}
// MARK: SearchBar Delegate
extension SearchDiscoverViewController: UISearchBarDelegate {
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
discoverContainerView.isHidden = false
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
discoverContainerView.isHidden = true
}
}
// MARK: SearchFooterView Delegate
extension SearchDiscoverViewController: SearchFooterDelegate {
func searchFooterDidPress(searchFooter: SearchFooterView) {
let searchItunesViewController = SearchITunesViewController(query: searchController.searchBar.text ?? "")
navigationController?.pushViewController(searchItunesViewController, animated: true)
}
}
// MARK: EmptyStateView Delegate
extension SearchDiscoverViewController: EmptyStateViewDelegate {
func didPressActionItemButton() {
let searchItunesViewController = SearchITunesViewController(query: searchController.searchBar.text ?? "")
navigationController?.pushViewController(searchItunesViewController, animated: true)
}
func emptyStateTableViewHandleRefresh() {
refreshController()
}
}
// MARK: ClearSearchFooterView Delegate
extension SearchDiscoverViewController: ClearSearchFooterViewDelegate {
func didPressClearSearchHistoryButton() {
UserDefaults.standard.set([], forKey: pastSearchKey)
pastSearchesTableViewReloadData()
}
}
// MARK: SearchTableView Delegate
extension SearchDiscoverViewController: SearchTableViewDelegate {
func refreshController() {
searchResultsTableView.stopLoadingAnimation()
searchResultsTableView.finishInfiniteScroll()
searchResultsTableView.reloadData()
searchResultsTableView.layoutIfNeeded()
updateTableViewInsetsForAccessoryView()
}
func hideSearchFooter() {
searchFooterView.isHidden = true
}
func showSearchFooter() {
searchFooterView.isHidden = false
}
func didSelectCell(cell: UITableViewCell, object: Any) {
if let series = object as? Series {
didTapOnCell(for: series)
} else if let episode = object as? Episode {
didTapOnCell(for: episode)
} else if let user = object as? User {
didTapOnCell(for: user)
}
}
private func didTapOnCell(for series: Series) {
addPastSearches()
let seriesDetailViewController = SeriesDetailViewController(series: series)
navigationController?.pushViewController(seriesDetailViewController,animated: true)
}
private func didTapOnCell(for episode: Episode) {
addPastSearches()
let episodeViewController = EpisodeDetailViewController()
episodeViewController.episode = episode
navigationController?.pushViewController(episodeViewController, animated: true)
}
private func didTapOnCell(for user: User) {
addPastSearches()
let externalProfileViewController = UserDetailViewController(user: user)
navigationController?.pushViewController(externalProfileViewController, animated: true)
}
func didPressFollowButton(cell: SearchPeopleTableViewCell) {
guard let data = searchResultsTableView.dataSource as? MainSearchDataSourceDelegate, let indexPath = searchResultsTableView.indexPath(for: cell), let user = data.searchResults[.people]![indexPath.row] as? User else { return }
user.followChange(completion: cell.setFollowButtonState)
}
func didPressSubscribeButton(cell: SearchSeriesTableViewCell) {
guard let data = searchResultsTableView.dataSource as? MainSearchDataSourceDelegate, let indexPath = searchResultsTableView.indexPath(for: cell), let series = data.searchResults[.series]![indexPath.row] as? Series else { return }
series.subscriptionChange(completion: cell.setSubscribeButtonToState)
}
func didPressPlayButton(cell: SearchEpisodeTableViewCell) {
guard let data = searchResultsTableView.dataSource as? MainSearchDataSourceDelegate, let indexPath = searchResultsTableView.indexPath(for: cell), let appDelegate = UIApplication.shared.delegate as? AppDelegate, let episode = data.searchResults[.episodes]![indexPath.row] as? Episode else { return }
appDelegate.showAndExpandPlayer()
Player.sharedInstance.playEpisode(episode: episode)
cell.setPlayButtonToState(isPlaying: true)
// reset previously playings view
if let playingIndexPath = currentlyPlayingIndexPath, currentlyPlayingIndexPath != indexPath, let currentlyPlayingCell = searchResultsTableView.cellForRow(at: playingIndexPath) as? SearchEpisodeTableViewCell, let playingEpisode = data.searchResults[.episodes]![playingIndexPath.row] as? Episode {
currentlyPlayingCell.setPlayButtonToState(isPlaying: playingEpisode.isPlaying)
}
refreshController()
currentlyPlayingIndexPath = indexPath
updateTableViewInsetsForAccessoryView()
}
func didPressViewAllButton(type: SearchType, results: [SearchType: [Any]]) {
addPastSearches()
let fullResultsController = TopSearchResultsViewController(type: type, query: lastSearchText, results: results[type]!)
self.navigationController?.pushViewController(fullResultsController, animated: true)
}
}
class MainSearchDataSourceDelegate: NSObject {
var searchTypes = SearchType.allValues
var searchResults: [SearchType: [Any]] = [.people:[], .episodes:[], .series:[]]
var previewSize: Int = 4
var pageSize: Int = 20
var completingNewSearch: Bool = false
var endpointType = SearchAllEndpointRequest.self
var path = "all"
var sectionHeaderHeight: CGFloat = 55
let firstSectionHeaderPadding: CGFloat = 16
var areResults = true
weak var delegate: SearchTableViewDelegate?
func fetchData(query: String) {
System.endpointRequestQueue.cancelAllEndpointRequestsOfType(type: endpointType)
let request = endpointType.init(modelPath: path, query: query, offset: 0, max: pageSize)
request.success = { endpoint in
guard let results = endpoint.processedResponseValue as? [SearchType: [Any]] else { return }
self.searchResults = results
self.completingNewSearch = false
if (self.searchResults[.series]?.isEmpty)! && (self.searchResults[.episodes]?.isEmpty)! && (self.searchResults[.people]?.isEmpty)! {
self.delegate?.hideSearchFooter()
}
else { self.delegate?.showSearchFooter() }
self.delegate?.refreshController()
}
request.failure = { _ in
self.completingNewSearch = false
}
System.endpointRequestQueue.addOperation(request)
}
func resetResults() {
self.searchResults = [.people:[], .episodes:[], .series:[]]
}
}
// MARK: SearchEpisodeTableViewCell Delegate
extension MainSearchDataSourceDelegate: SearchEpisodeTableViewCellDelegate {
func searchEpisodeTableViewCellDidPressPlayButton(cell: SearchEpisodeTableViewCell) {
delegate?.didPressPlayButton(cell: cell)
}
}
// MARK: SearchSeriesTableView Delegate
extension MainSearchDataSourceDelegate: SearchSeriesTableViewDelegate {
func searchSeriesTableViewCellDidPressSubscribeButton(cell: SearchSeriesTableViewCell) {
delegate?.didPressSubscribeButton(cell: cell)
}
}
// MARK: SearchPeopleTableViewCell Delegate
extension MainSearchDataSourceDelegate: SearchPeopleTableViewCellDelegate {
func searchPeopleTableViewCellDidPressFollowButton(cell: SearchPeopleTableViewCell) {
delegate?.didPressFollowButton(cell: cell)
}
}
// MARK: SearchTableViewHeader Delegate
extension MainSearchDataSourceDelegate: SearchTableViewHeaderDelegate {
func searchTableViewHeaderDidPressViewAllButton(view: SearchSectionHeaderView) {
delegate?.didPressViewAllButton(type: view.type, results: searchResults)
}
}
// MARK: TableView Data Source
extension MainSearchDataSourceDelegate: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return min(searchResults[searchTypes[section]]!.count, previewSize)
}
func numberOfSections(in tableView: UITableView) -> Int {
return completingNewSearch ? 0 : searchTypes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellType = searchTypes[indexPath.section]
if searchResults[cellType]!.isEmpty {
let cell = NoResultsTableViewCell(style: .default, reuseIdentifier: "noresults", type: cellType)
return cell
}
if let cell = tableView.dequeueReusableCell(withIdentifier: SearchType.people.identifiers) as? SearchPeopleTableViewCell, let user = searchResults[cellType]![indexPath.row] as? User {
cell.configure(for: user, index: indexPath.row)
cell.delegate = self
cell.isHidden = completingNewSearch
return cell
} else if let cell = tableView.dequeueReusableCell(withIdentifier: SearchType.series.identifiers) as? SearchSeriesTableViewCell, let series = searchResults[cellType]![indexPath.row] as? Series {
cell.configure(for: series, index: indexPath.row)
cell.delegate = self
cell.isHidden = completingNewSearch
return cell
} else if let cell = tableView.dequeueReusableCell(withIdentifier: SearchType.episodes.identifiers) as? SearchEpisodeTableViewCell, let episode = searchResults[cellType]![indexPath.row] as? Episode {
if let url = episode.smallArtworkImageURL {
cell.displayView.set(smallImageUrl: url)
}
cell.displayView.set(title: episode.title)
cell.displayView.set(description: episode.dateTimeLabelString)
cell.displayView.set(isPlaying: episode.isPlaying)
cell.displayView.set(isPlayable: episode.audioURL != nil)
cell.delegate = self
cell.isHidden = completingNewSearch
return cell
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return searchResults[searchTypes[indexPath.section]]!.isEmpty ? NoResultsTableViewCell.height : searchTypes[indexPath.section].cellHeight
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard !(searchResults[searchTypes[section]]?.isEmpty)! else {
return 0
}
return sectionHeaderHeight
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard !completingNewSearch && !(searchResults[searchTypes[section]]?.isEmpty)! else {
return nil
}
let headerView = SearchSectionHeaderView(frame: .zero, type: searchTypes[section])
headerView.delegate = self
headerView.configure(type: searchTypes[section])
if searchResults[searchTypes[section]]!.count <= 3 {
headerView.hideViewAllButton()
}
return headerView
}
}
// MARK: TableView Delegate
extension MainSearchDataSourceDelegate: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) else { return }
delegate?.didSelectCell(cell: cell, object: searchResults[SearchType.allValues[indexPath.section]]![indexPath.row])
}
}
| mit | 20006f081c71109a4becf23d375a63ae | 36.97293 | 306 | 0.69535 | 5.558741 | false | false | false | false |
J-Mendes/Flickr-Viewer | Flickr Viewer/Flickr Viewer/Views/ProgressHUD.swift | 1 | 3089 | //
// ProgressHUD.swift
// Flickr Viewer
//
// Created by Jorge Mendes on 25/10/16.
// Copyright © 2016 Jorge Mendes. All rights reserved.
//
import UIKit
import JGProgressHUD
class ProgressHUD: NSObject {
private class func createProgressHUD() -> JGProgressHUD {
let hud: JGProgressHUD = JGProgressHUD(style: .dark)
hud.interactionType = .blockAllTouches
hud.animation = JGProgressHUDFadeZoomAnimation()
hud.backgroundColor = UIColor.init(white: 0.0, alpha: 0.4)
hud.textLabel.font = UIFont.systemFont(ofSize: 14.0)
hud.hudView.layer.shadowColor = UIColor.black.cgColor
hud.hudView.layer.shadowOffset = CGSize.zero
hud.hudView.layer.shadowOpacity = 0.4
hud.hudView.layer.shadowRadius = 8.0
return hud
}
class func showProgressHUD(view: UIView, text: String = "", isSquared: Bool = true) {
let allHuds: [JGProgressHUD] = JGProgressHUD.allProgressHUDs(in: view) as! [JGProgressHUD]
if allHuds.count > 0 {
let hud: JGProgressHUD = allHuds.first!
hud.indicatorView = JGProgressHUDIndeterminateIndicatorView(hudStyle: hud.style)
hud.textLabel.text = text
hud.square = isSquared
} else {
let newHud: JGProgressHUD = self.createProgressHUD()
newHud.indicatorView = JGProgressHUDIndeterminateIndicatorView(hudStyle: newHud.style)
newHud.textLabel.text = text
newHud.square = isSquared
newHud.show(in: view)
}
}
class func showSuccessHUD(view: UIView, text: String = "Success") {
let allHuds: [JGProgressHUD] = JGProgressHUD.allProgressHUDs(in: view) as! [JGProgressHUD]
if allHuds.count > 0 {
let hud: JGProgressHUD = allHuds.first!
hud.indicatorView = JGProgressHUDSuccessIndicatorView()
hud.textLabel.text = text
hud.dismiss(afterDelay: 3.0)
} else {
let newHud: JGProgressHUD = self.createProgressHUD()
newHud.indicatorView = JGProgressHUDSuccessIndicatorView()
newHud.textLabel.text = text
newHud.show(in: view)
newHud.dismiss(afterDelay: 3.0)
}
}
class func showErrorHUD(view: UIView, text: String = "Error") {
let allHuds: [JGProgressHUD] = JGProgressHUD.allProgressHUDs(in: view) as! [JGProgressHUD]
if allHuds.count > 0 {
let hud: JGProgressHUD = allHuds.first!
hud.indicatorView = JGProgressHUDErrorIndicatorView()
hud.textLabel.text = text
hud.dismiss(afterDelay: 3.0)
} else {
let newHud: JGProgressHUD = self.createProgressHUD()
newHud.indicatorView = JGProgressHUDErrorIndicatorView()
newHud.textLabel.text = text
newHud.show(in: view)
newHud.dismiss(afterDelay: 3.0)
}
}
class func dismissAllHuds(view: UIView) {
JGProgressHUD.allProgressHUDs(in: view).forEach{ ($0 as! JGProgressHUD).dismiss() }
}
}
| lgpl-3.0 | 2f178e37a2127dc13e5419a814450b39 | 38.088608 | 98 | 0.632124 | 4.247593 | false | false | false | false |
Bouke/HAP | Sources/HAP/Base/Predefined/Characteristics/Characteristic.MacRetransmissionMaximum.swift | 1 | 2089 | import Foundation
public extension AnyCharacteristic {
static func macRetransmissionMaximum(
_ value: UInt8 = 0,
permissions: [CharacteristicPermission] = [.read],
description: String? = "MAC Retransmission Maximum",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.macRetransmissionMaximum(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func macRetransmissionMaximum(
_ value: UInt8 = 0,
permissions: [CharacteristicPermission] = [.read],
description: String? = "MAC Retransmission Maximum",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<UInt8> {
GenericCharacteristic<UInt8>(
type: .macRetransmissionMaximum,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
| mit | fa16df1982b59f377267ea9102d4c946 | 33.245902 | 66 | 0.588798 | 5.411917 | false | false | false | false |
wendyabrantes/WAInvisionProjectSpaceExample | WAInvisionProjectSpaceExample/InvisionProjectSpaceCellView.swift | 1 | 1914 | //
// InvisionProjectSpaceCellView.swift
// WAInvisionProjectSpaceExample
//
// Created by Wendy Abrantes on 22/02/2017.
// Copyright © 2017 Wendy Abrantes. All rights reserved.
//
import UIKit
class InvisionProjectSpaceViewCell : UICollectionViewCell, CardViewProtocol, NSCopying {
static let reuseIdentifier = "InvisionProjectSpaceViewCell"
var isFullScreen: Bool = false {
didSet {
cardView.isFullScreen = isFullScreen
}
}
var cardView = CardView(frame: .zero)
var parallaxValue: CGFloat = 0 {
didSet {
cardView.parallax = parallaxValue
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
}
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(cardView)
}
override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
super.apply(layoutAttributes)
guard let layoutAttributes = layoutAttributes as? InvisionCollectionViewLayoutAttributes else { return }
parallaxValue = layoutAttributes.parallaxValue
}
public func updateWithImage(mainImage: UIImage, logoImage:UIImage, title: String, nbProject: Int){
cardView.updateWithImage(mainImage: mainImage, logoImage:logoImage, title: title, nbProject: nbProject)
}
override func layoutSubviews() {
super.layoutSubviews()
cardView.frame = CGRect(origin: .zero, size: frame.size)
cardView.layoutSubviews()
}
func copy(with zone: NSZone? = nil) -> Any {
//copy the exising cardView and replace it on the screen
let cardView = self.cardView.copy() as! CardView
let instance = InvisionProjectSpaceViewCell(frame: self.frame)
instance.cardView.removeFromSuperview()
instance.cardView = cardView
instance.contentView.addSubview(cardView)
return instance
}
}
| mit | be851b6808adcc64677806fdb24408b9 | 27.132353 | 108 | 0.726085 | 4.49061 | false | false | false | false |
GhostSK/SpriteKitPractice | RestaurantManager/RestaurantManager/Main/Views/EmployeeView.swift | 1 | 7382 | //
// EmployeeView.swift
// RestaurantManager
//
// Created by 胡杨林 on 2017/9/26.
// Copyright © 2017年 胡杨林. All rights reserved.
//
import Foundation
import UIKit
class employeeViewInMarket: UIView {
class func BuildEmployeeView(model:EmployeeModel, PositionPoint:CGPoint)->employeeViewInMarket{
let view = employeeViewInMarket.init(frame: CGRect(x: PositionPoint.x, y: PositionPoint.y, width: 260, height: 300))
view.backgroundColor = UIColor.init(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.55)
let headImageView = UIImageView.init(frame: CGRect(x: 15, y: 15, width: 60, height:80))
headImageView.image = UIImage(named: "443png")
view.addSubview(headImageView)
let nameTitle = UILabel.init(frame: CGRect(x: 90, y: 25, width: 50, height: 25))
nameTitle.text = "姓名:"
nameTitle.adjustsFontSizeToFitWidth = true
view.addSubview(nameTitle)
let nameLabel = UILabel.init(frame: CGRect(x: 140, y: 25, width: 110, height: 25))
nameLabel.text = model.Name == "" ? "尼古拉斯·二狗子" : model.Name
nameLabel.adjustsFontSizeToFitWidth = true
nameLabel.font = UIFont.systemFont(ofSize: 16)
view.addSubview(nameLabel)
let PayPrice = UILabel.init(frame: CGRect(x: 90, y: 60, width: 50, height: 25))
PayPrice.text = "薪酬:"
PayPrice.adjustsFontSizeToFitWidth = true
view.addSubview(PayPrice)
let Price = UILabel.init(frame: CGRect(x: 140, y: 60, width: 110, height: 25))
Price.text = "\(model.Payment)"
view.addSubview(Price)
//数值条
let Label1 = UILabel.init(frame: CGRect(x: 15, y: 110, width: 55, height: 20))
Label1.text = "灵巧"
Label1.textAlignment = .center
Label1.adjustsFontSizeToFitWidth = true
view.addSubview(Label1)
let bar1 = abilityBar.buildBar(Frame: CGRect(x: 75, y: 115, width: 140, height: 10), value: model.agility, ColorType: 0)
view.addSubview(bar1)
let right1 = UILabel.init(frame: CGRect(x: 220, y: 110, width: 30, height: 20))
right1.text = "\(model.agility)"
right1.adjustsFontSizeToFitWidth = true
view.addSubview(right1)
let Label2 = UILabel.init(frame: CGRect(x: 15, y: 135, width: 55, height: 20))
Label2.text = "计算"
Label2.textAlignment = .center
Label2.adjustsFontSizeToFitWidth = true
view.addSubview(Label2)
let bar2 = abilityBar.buildBar(Frame: CGRect(x: 75, y: 140, width: 140, height: 10), value: model.calculateAbility, ColorType: 1)
view.addSubview(bar2)
let right2 = UILabel.init(frame: CGRect(x: 220, y: 135, width: 30, height: 20))
right2.text = "\(model.calculateAbility)"
right2.adjustsFontSizeToFitWidth = true
view.addSubview(right2)
let Label3 = UILabel.init(frame: CGRect(x: 15, y: 160, width: 55, height: 20))
Label3.text = "厨艺"
Label3.textAlignment = .center
Label3.adjustsFontSizeToFitWidth = true
view.addSubview(Label3)
let bar3 = abilityBar.buildBar(Frame: CGRect(x: 75, y: 165, width: 140, height: 10), value: model.CookAbility, ColorType: 2)
view.addSubview(bar3)
let right3 = UILabel.init(frame: CGRect(x: 220, y: 160, width: 30, height: 20))
right3.text = "\(model.CookAbility)"
right3.adjustsFontSizeToFitWidth = true
view.addSubview(right3)
let Label4 = UILabel.init(frame: CGRect(x: 15, y: 185, width: 55, height: 20))
Label4.text = "武力"
Label4.textAlignment = .center
Label4.adjustsFontSizeToFitWidth = true
view.addSubview(Label4)
let bar4 = abilityBar.buildBar(Frame: CGRect(x: 75, y: 190, width: 140, height: 10), value: model.military, ColorType: 3)
view.addSubview(bar4)
let right4 = UILabel.init(frame: CGRect(x: 220, y: 185, width: 30, height: 20))
right4.text = "\(model.military)"
right4.adjustsFontSizeToFitWidth = true
view.addSubview(right4)
let Label5 = UILabel.init(frame: CGRect(x: 15, y: 210, width: 55, height: 20))
Label5.text = "魅力"
Label5.textAlignment = .center
Label5.adjustsFontSizeToFitWidth = true
view.addSubview(Label5)
let bar5 = abilityBar.buildBar(Frame: CGRect(x: 75, y: 215, width: 140, height: 10), value: model.charmAbility, ColorType: 4)
view.addSubview(bar5)
let right5 = UILabel.init(frame: CGRect(x: 220, y: 210, width: 30, height: 20))
right5.text = "\(model.charmAbility)"
right5.adjustsFontSizeToFitWidth = true
view.addSubview(right5)
let Label6 = UILabel.init(frame: CGRect(x: 15, y: 235, width: 55, height: 20))
Label6.text = "气运"
Label6.textAlignment = .center
Label6.adjustsFontSizeToFitWidth = true
view.addSubview(Label6)
let bar6 = abilityBar.buildBar(Frame: CGRect(x: 75, y: 240, width: 140, height: 10), value: model.Lucky, ColorType: 5)
view.addSubview(bar6)
let right6 = UILabel.init(frame: CGRect(x: 220, y: 235, width: 30, height: 20))
right6.text = "\(model.Lucky)"
right6.adjustsFontSizeToFitWidth = true
view.addSubview(right6)
let judgeTitle = UILabel.init(frame: CGRect(x: 15, y: 260, width: 55, height: 20))
judgeTitle.text = "评价"
judgeTitle.textAlignment = .center
view.addSubview(judgeTitle)
let judge = UILabel.init(frame: CGRect(x: 75, y: 260, width: 170, height: 35))
judge.numberOfLines = 2
judge.textAlignment = .left
// judge.text = "吃的挺多,偷懒在行,凑合着用吧。"
judge.text = model.judge
judge.adjustsFontSizeToFitWidth = true
view.addSubview(judge)
return view
}
func didEmployed(){
let view = UIView.init(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height))
view.backgroundColor = UIColor.init(red: 147.0/255, green: 147.0/255, blue: 147.0/255, alpha: 0.8)
let mark = UIImageView.init(frame: CGRect(x: (view.frame.size.width - 200) / 2, y: (view.frame.size.height - 100) / 2, width: 200, height: 100))
mark.image = UIImage.init(named: "招募印章")
view.addSubview(mark)
self.addSubview(view)
}
}
class abilityBar: UIView {
//http://www.iconfont.cn/search/index?searchType=icon&q=%E8%BF%9B%E5%BA%A6%E6%9D%A1
class func buildBar(Frame:CGRect, value:NSInteger, ColorType:NSInteger)->abilityBar{
let view = abilityBar.init(frame: Frame)
let backImage = UIImageView.init(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height))
backImage.image = UIImage(named: "progress_back")
view.addSubview(backImage)
let value2 = CGFloat(value)
let upImage = UIImageView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width / 100.0 * value2, height: view.frame.size.height))
var color = ColorType
if color > 5{
color = 5
}
let upname = "progress_up\(color)"
upImage.image = UIImage(named: upname)
view.addSubview(upImage)
return view;
}
}
| apache-2.0 | 6ba1fb30977c0828d97d8f8991811a98 | 46.181818 | 152 | 0.630195 | 3.554795 | false | false | false | false |
mattwelborn/HSTracker | HSTracker/UIs/Trackers/CardHudContainer.swift | 1 | 6078 | //
// CardHudContainer.swift
// HSTracker
//
// Created by Benjamin Michotte on 16/06/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
import CleanroomLogger
class CardHudContainer: NSWindowController {
var positions: [Int: [NSPoint]] = [:]
var huds: [CardHud] = []
@IBOutlet weak var container: NSView!
override func windowDidLoad() {
super.windowDidLoad()
self.window!.styleMask = NSBorderlessWindowMask
//self.window!.ignoresMouseEvents = true
self.window!.level = Int(CGWindowLevelForKey(CGWindowLevelKey.ScreenSaverWindowLevelKey))
self.window!.opaque = false
self.window!.hasShadow = false
self.window!.backgroundColor = NSColor.clearColor()
for _ in 0 ..< 10 {
let hud = CardHud()
hud.alphaValue = 0.0
container.addSubview(hud)
huds.append(hud)
}
initPoints()
NSNotificationCenter.defaultCenter()
.addObserver(self,
selector: #selector(BoardDamage.hearthstoneActive(_:)),
name: "hearthstone_active",
object: nil)
}
func initPoints() {
positions[1] = [
NSPoint(x: 144, y: -3)
]
positions[2] = [
NSPoint(x: 97, y: -1),
NSPoint(x: 198, y: -1)
]
positions[3] = [
NSPoint(x: 42, y: 19),
NSPoint(x: 146, y: -1),
NSPoint(x: 245, y: 8)
]
positions[4] = [
NSPoint(x: 31, y: 28),
NSPoint(x: 109, y: 6),
NSPoint(x: 185, y: -1),
NSPoint(x: 262, y: 5)
]
positions[5] = [
NSPoint(x: 21, y: 26),
NSPoint(x: 87, y: 6),
NSPoint(x: 148, y: -4),
NSPoint(x: 211, y: -2),
NSPoint(x: 274, y: 9)
]
positions[6] = [
NSPoint(x: 19, y: 36),
NSPoint(x: 68, y: 15),
NSPoint(x: 123, y: 2),
NSPoint(x: 175, y: -3),
NSPoint(x: 229, y: 0),
NSPoint(x: 278, y: 9)
]
positions[7] = [
NSPoint(x: 12.0, y: 36.0),
NSPoint(x: 57.0, y: 16.0),
NSPoint(x: 104.0, y: 4.0),
NSPoint(x: 153.0, y: -1.0),
NSPoint(x: 194.0, y: -3.0),
NSPoint(x: 240.0, y: 6.0),
NSPoint(x: 283.0, y: 19.0)
]
positions[8] = [
NSPoint(x: 14.0, y: 38.0),
NSPoint(x: 52.0, y: 22.0),
NSPoint(x: 92.0, y: 6.0),
NSPoint(x: 134.0, y: -2.0),
NSPoint(x: 172.0, y: -5.0),
NSPoint(x: 210.0, y: -4.0),
NSPoint(x: 251.0, y: 1.0),
NSPoint(x: 289.0, y: 10.0)
]
positions[9] = [
NSPoint(x: 16.0, y: 38.0),
NSPoint(x: 57.0, y: 25.0),
NSPoint(x: 94.0, y: 12.0),
NSPoint(x: 127.0, y: 3.0),
NSPoint(x: 162.0, y: -1.0),
NSPoint(x: 201.0, y: -6.0),
NSPoint(x: 238.0, y: 2.0),
NSPoint(x: 276.0, y: 13.0),
NSPoint(x: 315.0, y: 28.0)
]
positions[10] = [
NSPoint(x: 21.0, y: 40.0),
NSPoint(x: 53.0, y: 30.0),
NSPoint(x: 86.0, y: 20.0),
NSPoint(x: 118.0, y: 8.0),
NSPoint(x: 149.0, y: -1.0),
NSPoint(x: 181.0, y: -2.0),
NSPoint(x: 211.0, y: -0.0),
NSPoint(x: 245.0, y: 1.0),
NSPoint(x: 281.0, y: 12.0),
NSPoint(x: 319.0, y: 23.0)
]
}
func hearthstoneActive(notification: NSNotification) {
let hs = Hearthstone.instance
let level: Int
if hs.hearthstoneActive {
level = Int(CGWindowLevelForKey(CGWindowLevelKey.ScreenSaverWindowLevelKey))
} else {
level = Int(CGWindowLevelForKey(CGWindowLevelKey.NormalWindowLevelKey))
}
self.window!.level = level
}
func reset() {
for hud in huds {
hud.alphaValue = 0.0
hud.frame = NSRect.zero
}
}
func update(entities: [Entity], cardCount: Int) {
for (i, hud) in huds.enumerate() {
var hide = true
if let entity = entities.firstWhere({ $0.getTag(.ZONE_POSITION) == i + 1 }) {
hud.entity = entity
var pos: NSPoint? = nil
if let points = positions[cardCount] where points.count > i {
pos = points[i]
if let pos = pos {
hide = false
let rect = NSRect(x: pos.x * SizeHelper.hearthstoneWindow.scaleX,
y: pos.y * SizeHelper.hearthstoneWindow.scaleY,
width: 36,
height: 45)
hud.needsDisplay = true
// this will avoid a weird move
if hud.frame == NSRect.zero {
hud.frame = rect
}
NSAnimationContext.runAnimationGroup({ (context) in
context.duration = 0.5
hud.animator().frame = rect
hud.animator().alphaValue = 1.0
}, completionHandler: nil)
}
}
}
if hide {
NSAnimationContext.runAnimationGroup({ (context) in
context.duration = 0.5
hud.animator().alphaValue = 0.0
}, completionHandler: nil)
}
}
}
} | mit | 521e4d6f5a1b6b3cd194006c235b2ba5 | 30.65625 | 97 | 0.425539 | 4.095013 | false | false | false | false |
Daltron/Spartan | Spartan/Classes/TuneableTrackAttribute.swift | 1 | 1619 | /*
The MIT License (MIT)
Copyright (c) 2017 Dalton Hinterscher
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
public enum TuneableTrackAttribute: String {
case acousticness = "acousticness"
case danceability = "danceability"
case durationMs = "duration_ms"
case energy = "energy"
case instrumentalness = "instrumentalness"
case key = "key"
case liveness = "liveness"
case loudness = "loudness"
case mode = "mode"
case popularity = "popularity"
case speechiness = "speechiness"
case tempo = "tempo"
case timeSignature = "time_signature"
case valence = "valence"
}
| mit | 761e4f803f60dc3e36022f90fb583ff3 | 45.257143 | 147 | 0.751699 | 4.497222 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/Features/ProjectActivities/Views/Cells/ProjectActivityCommentCell.swift | 1 | 5653 | import KsApi
import Library
import Prelude
import Prelude_UIKit
import UIKit
internal protocol ProjectActivityCommentCellDelegate: AnyObject {
func projectActivityCommentCellGoToBacking(project: Project, user: User)
func projectActivityCommentCellGoToSendReply(project: Project, update: Update?, comment: ActivityComment)
}
internal final class ProjectActivityCommentCell: UITableViewCell, ValueCell {
fileprivate let viewModel: ProjectActivityCommentCellViewModelType = ProjectActivityCommentCellViewModel()
internal weak var delegate: ProjectActivityCommentCellDelegate?
@IBOutlet fileprivate var authorImageView: UIImageView!
@IBOutlet fileprivate var backingButton: UIButton!
@IBOutlet fileprivate var bodyLabel: UILabel!
@IBOutlet fileprivate var bodyView: UIView!
@IBOutlet fileprivate var bulletSeparatorView: UIView!
@IBOutlet fileprivate var cardView: UIView!
@IBOutlet fileprivate var containerStackView: UIStackView!
@IBOutlet fileprivate var footerDividerView: UIView!
@IBOutlet fileprivate var footerStackView: UIStackView!
@IBOutlet fileprivate var headerDividerView: UIView!
@IBOutlet fileprivate var headerStackView: UIStackView!
@IBOutlet fileprivate var replyButton: UIButton!
@IBOutlet fileprivate var titleLabel: UILabel!
internal override func awakeFromNib() {
super.awakeFromNib()
_ = self.backingButton
|> UIButton.lens.targets .~ [(self, #selector(self.backingButtonPressed), .touchUpInside)]
_ = self.replyButton
|> UIButton.lens.targets .~ [(self, #selector(self.replyButtonPressed), .touchUpInside)]
}
internal func configureWith(value activityAndProject: (Activity, Project)) {
self.viewModel.inputs.configureWith(
activity: activityAndProject.0,
project: activityAndProject.1
)
}
internal override func bindViewModel() {
super.bindViewModel()
self.footerStackView.rac.hidden = self.viewModel.outputs.pledgeFooterIsHidden
self.viewModel.outputs.authorImageURL
.observeForUI()
.on(event: { [weak self] _ in
self?.authorImageView.af.cancelImageRequest()
self?.authorImageView.image = nil
})
.skipNil()
.observeValues { [weak self] url in
self?.authorImageView.ksr_setImageWithURL(url)
}
self.rac.accessibilityLabel = self.viewModel.outputs.cellAccessibilityLabel
self.rac.accessibilityValue = self.viewModel.outputs.cellAccessibilityValue
self.viewModel.outputs.notifyDelegateGoToBacking
.observeForUI()
.observeValues { [weak self] project, user in
self?.delegate?.projectActivityCommentCellGoToBacking(project: project, user: user)
}
self.viewModel.outputs.notifyDelegateGoToSendReply
.observeForUI()
.observeValues { [weak self] project, update, comment in
self?.delegate?.projectActivityCommentCellGoToSendReply(
project: project, update: update, comment: comment
)
}
self.bodyLabel.rac.text = self.viewModel.outputs.body
self.viewModel.outputs.title
.observeForUI()
.observeValues { [weak titleLabel] title in
guard let titleLabel = titleLabel else { return }
titleLabel.attributedText = title.simpleHtmlAttributedString(
base: [
NSAttributedString.Key.font: UIFont.ksr_title3(size: 14),
NSAttributedString.Key.foregroundColor: UIColor.ksr_support_400
],
bold: [
NSAttributedString.Key.font: UIFont.ksr_title3(size: 14),
NSAttributedString.Key.foregroundColor: UIColor.ksr_support_700
],
italic: nil
)
?? .init()
}
}
internal override func bindStyles() {
super.bindStyles()
_ = self
|> baseTableViewCellStyle()
|> ProjectActivityCommentCell.lens.contentView.layoutMargins %~~ { layoutMargins, cell in
cell.traitCollection.isRegularRegular
? projectActivityRegularRegularLayoutMargins
: layoutMargins
}
|> UITableViewCell.lens.accessibilityHint %~ { _ in Strings.Opens_comments() }
_ = self.authorImageView
|> ignoresInvertColorsImageViewStyle
_ = self.backingButton
|> projectActivityFooterButton
|> UIButton.lens.title(for: .normal) %~ { _ in Strings.dashboard_activity_pledge_info() }
_ = self.bodyLabel
|> UILabel.lens.textColor .~ .ksr_support_400
|> UILabel.lens.font %~~ { _, label in
label.traitCollection.isRegularRegular
? UIFont.ksr_body()
: UIFont.ksr_body(size: 14)
}
_ = self.bodyView
|> UIView.lens.layoutMargins .~ .init(topBottom: Styles.grid(3), leftRight: Styles.grid(2))
_ = self.bulletSeparatorView
|> projectActivityBulletSeparatorViewStyle
_ = self.cardView
|> dropShadowStyleMedium()
_ = self.footerDividerView
|> projectActivityDividerViewStyle
_ = self.footerStackView
|> projectActivityFooterStackViewStyle
|> UIStackView.lens.layoutMargins .~ .init(all: Styles.grid(2))
_ = self.headerDividerView
|> projectActivityDividerViewStyle
_ = self.headerStackView
|> projectActivityHeaderStackViewStyle
_ = self.replyButton
|> projectActivityFooterButton
|> UIButton.lens.title(for: .normal) %~ { _ in Strings.dashboard_activity_reply() }
_ = self.titleLabel
|> UILabel.lens.numberOfLines .~ 2
}
@objc fileprivate func backingButtonPressed(_: UIButton) {
self.viewModel.inputs.backingButtonPressed()
}
@objc fileprivate func replyButtonPressed(_: UIButton) {
self.viewModel.inputs.replyButtonPressed()
}
}
| apache-2.0 | 9ad0ed9e2c6ad9bce77c79487dffdb6a | 33.054217 | 108 | 0.706881 | 4.924216 | false | false | false | false |
whiteshadow-gr/HatForIOS | HAT/Objects/HAT Operator/HATOperatorTypes.swift | 1 | 3280 | //
/**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
import Foundation
// MARK: OperatorIn class
/// The `in` operator used in `dataDebits`
public class OperatorIn: HATOperator {
// MARK: - Coding Keys
/**
The JSON fields used by the hat
The Fields are the following:
* `value` in JSON is `value`
*/
private enum CodingKeys: String, CodingKey {
case value
}
// MARK: - Variables
/// value
var value: Dictionary<String, String> = [:]
}
// MARK: - OperatorContains class
/// The `contains` operator used in `dataDebits` asking for a search in a `String` for a specific `substring`
public class OperatorContains: HATOperator {
// MARK: - Coding Keys
/**
The JSON fields used by the hat
The Fields are the following:
* `hasValue` in JSON is `value`
*/
private enum CodingKeys: String, CodingKey {
case hasValue = "value"
}
// MARK: - Variables
/// A flag indicating if the specific `dataDebit` contains the required `substring` or not
var hasValue: Bool = false
}
// MARK: - OperatorBetween class
/// The `between` operator used in `dataDebits` asking for a search in a number between 2 values
public class OperatorBetween: HATOperator {
// MARK: - Coding Keys
/**
The JSON fields used by the hat
The Fields are the following:
* `upperLimit` in JSON is `upper`
* `lowerLimit` in JSON is `lower`
*/
private enum CodingKeys: String, CodingKey {
case upperLimit = "upper"
case lowerLimit = "lower"
}
// MARK: - Variables
/// The upper limit of the search to search for
var upperLimit: Int = 0
/// The lower limit of the search to search for
var lowerLimit: Int = 0
}
// MARK: - OperatorFind class
/// The `find` operator used in `dataDebits` asking for a search in a `String`
public class OperatorFind: HATOperator {
// MARK: - Coding Keys
/**
The JSON fields used by the hat
The Fields are the following:
* `operatorType` in JSON is `operator`
* `searchString` in JSON is `search`
*/
private enum CodingKeys: String, CodingKey {
case operatorType = "operator"
case searchString = "search"
}
// MARK: - Variables
/// The `String` to search for
var searchString: String = ""
// MARK: - Initialiser
/**
Decodes from a JSON file receiced over the internet to a class
- parameter decoder: The `Decoder` to decode the class from a JSON file to a class
*/
public required init(from decoder: Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
self.searchString = try container.decode(String.self, forKey: .searchString)
try super.init(from: decoder)
}
}
| mpl-2.0 | 8bc2b850f5bd4709ecf43c992c603751 | 24.230769 | 109 | 0.621037 | 4.281984 | false | false | false | false |
hacktoolkit/htk-ios-RottenTomatoes | RottenTomatoes/MoviesTabItemViewController.swift | 1 | 949 | //
// MoviesTabItemViewController.swift
// rottentomatoes
//
// Created by Jonathan Tsai on 9/16/14.
// Copyright (c) 2014 Hacktoolkit. All rights reserved.
//
import UIKit
class MoviesTabItemViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
var moviesTabBarController = self.parentViewController?.tabBarController
var tabBarItemTitle = self.tabBarItem.title!
var moviesViewController = segue.destinationViewController as MoviesViewController
var movieType = tabBarItemTitle == "Movies" ? RottenTomatoesApiMovieType.Movies : RottenTomatoesApiMovieType.DVDs
moviesViewController.setMovieType(movieType)
}
}
| mit | 239fa9d847a98b3e1c1cc9fa468fa229 | 31.724138 | 121 | 0.730242 | 4.942708 | false | false | false | false |
fe9lix/Protium | iOS/ProtiumTests/GifDetailInteractorTests.swift | 1 | 1203 | import XCTest
import RxSwift
import RxCocoa
@testable import Protium
// Example of integration tests for Interactors.
class GifDetailInteractorTests: XCTestCase {
private var actions: GifDetailsUI.Actions!
private var interactor: GifDetailsInteractor!
private let disposeBag = DisposeBag()
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testOpenURL() {
let testExpectation = expectation(description: "Open URL.")
actions = GifDetailsUI.Actions(
copyEmbedLink: Driver.empty(),
openGiphy: Driver.just(())
)
let gif = GifPM(Gif(
URL(string: "https://giphy.com/gifs/thisisgiphy-reaction-audience-3o7qDPfGhunRMZikI8")!
))
interactor = GifDetailsInteractor(gateway: GifStubGateway(), gif: Observable.just(gif), actions: actions)
interactor.urlToOpen.drive(onNext: { url in
XCTAssertEqual(url, gif.url!)
testExpectation.fulfill()
})
.addDisposableTo(disposeBag)
waitForExpectations(timeout: 1.0, handler: nil)
}
}
| mit | 4817dd1704b1dc9be47eaa5e8d6d867b | 27.642857 | 113 | 0.620948 | 4.850806 | false | true | false | false |
JadenGeller/Parsley | Sources/OperatorExpression.swift | 1 | 5558 | //
// OperatorExpression.swift
// Parsley
//
// Created by Jaden Geller on 2/22/16.
// Copyright © 2016 Jaden Geller. All rights reserved.
//
public enum OperatorExpression<Symbol, Element> {
case value(Element)
indirect case infix(infixOperator: Symbol, between: (OperatorExpression, OperatorExpression))
// indirect case prefix(prefixOperator: Symbol, before: OperatorExpression)
// indirect case postfix(postfixOperator: Symbol, after: OperatorExpression)
}
//extension Infix: Equatable where Symbol: Equatable, Element: Equatable { }
public func ==<Symbol: Equatable, Element: Equatable>(lhs: OperatorExpression<Symbol, Element>, rhs: OperatorExpression<Symbol, Element>) -> Bool {
switch (lhs, rhs) {
case (.value(let l), .value(let r)):
return l == r
case (.infix(let lInfixOperator, let lBetween), .infix(let rInfixOperator, let rBetween)):
return lInfixOperator == rInfixOperator && lBetween.0 == rBetween.0 && lBetween.1 == rBetween.1
default:
return false
}
}
extension OperatorExpression: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
switch self {
case .value(let element):
return "\(element)"
case .infix(let infixOperator, let (left, right)):
return "(\(left) \(infixOperator) \(right))"
// case .prefix(let prefixOperator , let value):
// return "(\(prefixOperator) \(value))"
// case .postfix(let postfixOperator , let value):
// return "(\(value) \(postfixOperator))"
}
}
public var debugDescription: String {
switch self {
case .value(let element):
return "OperatorExpression.value(\(element))"
case .infix(let infixOperator, let (left, right)):
return "OperatorExpression.infix(infixOperator: \(infixOperator), between: (\(left), \(right)))"
// case .prefix(let prefixOperator , let value):
// return "OperatorExpression.prefix(prefixOperator: \(prefixOperator), before: \(value))"
// case .postfix(let postfixOperator , let value):
// return "OperatorExpression.postfix(postfixOperator: \(postfixOperator), after: \(value))"
}
}
}
public func operatorExpression<Symbol: Hashable, Token, Result, Discard>(
parsing parser: Parser<Token, Result>,
groupedBy grouping: (left: Parser<Token, Discard>, right: Parser<Token, Discard>),
usingSpecification specification: OperatorSpecification<Symbol>,
matching: Symbol -> Parser<Token, Result>
) -> Parser<Token, OperatorExpression<Symbol, Result>> {
typealias OperatorParser = Parser<Token, OperatorExpression<Symbol, Result>>
// This is the bottom layer of the parser. We will place layer upon layer on top of this so we'll
// first check for low precedence paths (like addition) before we check high precedence paths
// (like multiplication). If this seems opposite to your intuitions, think of it this way: If we
// first find the addition, then it will be more loosely bound than the later found multiplication.
// For example, given (3 * 2 + 5), finding addition first gives us ((3 * 2) + (5)).
var level = between(grouping.left, grouping.right, parse: hold(operatorExpression(
parsing: parser,
groupedBy: grouping,
usingSpecification: specification,
matching: matching
))) ?? parser.map(OperatorExpression.value)
// Iterate over the precedence levels in decreasing order since we're building this parser from the bottom up.
for precedenceLevel in specification.descendingPrecedenceTieredInfixDeclarations {
let previousLevel = level // Want to capture the value before it changes.
// Define how this level is parsed, updating the `previousLevel` variable for the subsequent iteration.
// Parse operators of just one of the possible associativities.
level = coalesce(precedenceLevel.map { (associativity: Associativity, compatibleOperators: [Symbol]) in
recursive { (currentLevel: OperatorParser) in
// Parse any of the possible operators with this associativity and precedence.
return coalesce(compatibleOperators.map { infixOperator in
// Parse the operator symbol expression. Each expression will be either the same or
// previous level depending on the associativity of the operator. Eventually, we'll
// run out of operators to parse and parse the previous level regardless.
return infix(matching(infixOperator), between:
associativity == .right ? (currentLevel ?? previousLevel) : previousLevel,
associativity == .left ? (currentLevel ?? previousLevel) : previousLevel
).map { lhs, rhs in
OperatorExpression.infix(infixOperator: infixOperator, between: (lhs, rhs))
}
})
}
}) ?? previousLevel // There are no operators to parse at this level, so parse the previous level.
}
// // Handle prefix and postfix operators
// let x = specification.prefixOperators.map { prefixOperator in
// pair(matching(prefixOperator), level).map(right)
// OperatorExpression.prefix(prefixOperator:
// }
// }
// Return the parser that will parse a tree of operators.
return level
}
| mit | 0f2ccd0919ce2309fce9bb30b5c5ddf8 | 48.616071 | 147 | 0.655929 | 4.815425 | false | false | false | false |
iadmir/Signal-iOS | Signal/src/util/DeviceSleepManager.swift | 2 | 2879 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
// This entity has responsibility for blocking the device from sleeping if
// certain behaviors (e.g. recording or playing voice messages) are in progress.
//
// Sleep blocking is keyed using "block objects" whose lifetime corresponds to
// the duration of the block. For example, sleep blocking during audio playback
// can be keyed to the audio player. This provides a measure of robustness.
// On the one hand, we can use weak references to track block objects and stop
// blocking if the block object is deallocated even if removeBlock() is not
// called. On the other hand, we will also get correct behavior to addBlock()
// being called twice with the same block object.
@objc class DeviceSleepManager: NSObject {
let TAG = "[DeviceSleepManager]"
static let sharedInstance = DeviceSleepManager()
private class SleepBlock {
weak var blockObject: NSObject?
init(blockObject: NSObject) {
self.blockObject = blockObject
}
}
private var blocks: [SleepBlock] = []
override init() {
super.init()
NotificationCenter.default.addObserver(self,
selector:#selector(didEnterBackground),
name:NSNotification.Name.UIApplicationDidEnterBackground,
object:nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func didEnterBackground() {
AssertIsOnMainThread()
ensureSleepBlocking()
}
public func addBlock(blockObject: NSObject) {
AssertIsOnMainThread()
blocks.append(SleepBlock(blockObject: blockObject))
ensureSleepBlocking()
}
public func removeBlock(blockObject: NSObject) {
AssertIsOnMainThread()
blocks = blocks.filter {
$0.blockObject != nil && $0.blockObject != blockObject
}
ensureSleepBlocking()
}
private func ensureSleepBlocking() {
AssertIsOnMainThread()
// Cull expired blocks.
blocks = blocks.filter {
$0.blockObject != nil
}
let shouldBlock = blocks.count > 0
if UIApplication.shared.isIdleTimerDisabled != shouldBlock {
if shouldBlock {
var logString = "\(self.TAG) \(#function): Blocking sleep because of: \(String(describing: blocks.first?.blockObject))"
if blocks.count > 1 {
logString += " and \(blocks.count - 1) others."
}
Logger.info(logString)
} else {
Logger.info("\(self.TAG) \(#function): Unblocking sleep")
}
}
UIApplication.shared.isIdleTimerDisabled = shouldBlock
}
}
| gpl-3.0 | d702af3b6241b1ee10dc20d68d3709c3 | 30.637363 | 135 | 0.61306 | 5.113677 | false | false | false | false |
zSOLz/viper-base | ViperBase-Sample/ViperBase-Sample/Modules/ArticleDetails/Presenter/ArticleDetailsPresenter.swift | 1 | 1710 | //
// ArticleDetailsPresenter.swift
// ViperBase-Sample
//
// Created by SOL on 03.05.17.
// Copyright © 2017 SOL. All rights reserved.
//
import ViperBase
final class ArticleDetailsPresenter: Presenter {
fileprivate var articleDetailsInteractor: ArticleDetailsInteractorInterface
init(router: RouterInterface, articleDetailsInteractor: ArticleDetailsInteractorInterface) {
self.articleDetailsInteractor = articleDetailsInteractor
super.init(router: router)
}
override func viewDidLoad() {
super.viewDidLoad()
setupArticle()
}
fileprivate func setupArticle() {
var articleImage: UIImage? = nil
if let imageName = articleDetailsInteractor.imageName {
articleImage = UIImage(named: imageName)
}
let viewModel = ArticleDetailsViewModel(title: articleDetailsInteractor.title,
image: articleImage,
author: articleDetailsInteractor.authorName,
text: articleDetailsInteractor.text)
view?.setup(viewModel: viewModel)
}
}
// MARK: - Fileprivate
fileprivate extension ArticleDetailsPresenter {
final var view: ArticleDetailsViewInterface? {
return viewInterface as? ArticleDetailsViewInterface
}
final var router: NewsFeedRouterInterface? {
return routerInterface as? NewsFeedRouterInterface
}
}
// MARK: - ArticleDetailsPresenterInterface
extension ArticleDetailsPresenter: ArticleDetailsPresenterInterface {
func closeButtonTapped() {
router?.closeCurrentView()
}
}
| mit | 89b67900e1579d98bfb3f818f4b01e43 | 29.517857 | 96 | 0.654184 | 5.677741 | false | false | false | false |
roecrew/AudioKit | AudioKit/Common/Playgrounds/Filters.playground/Pages/Modal Resonance Filter.xcplaygroundpage/Contents.swift | 2 | 1460 | //: ## Modal Resonance Filter
//:
import XCPlayground
import AudioKit
let file = try AKAudioFile(readFileName: filtersPlaygroundFiles[0],
baseDir: .Resources)
let player = try AKAudioPlayer(file: file)
player.looping = true
var filter = AKModalResonanceFilter(player)
filter.frequency = 300 // Hz
filter.qualityFactor = 20
let balancedOutput = AKBalancer(filter, comparator: player)
AudioKit.output = balancedOutput
AudioKit.start()
player.play()
//: User Interface Set up
class PlaygroundView: AKPlaygroundView {
override func setup() {
addTitle("Modal Resonance Filter")
addSubview(AKResourcesAudioFileLoaderView(
player: player,
filenames: filtersPlaygroundFiles))
addSubview(AKPropertySlider(
property: "Frequency",
format: "%0.1f Hz",
value: filter.frequency, maximum: 5000,
color: AKColor.greenColor()
) { sliderValue in
filter.frequency = sliderValue
})
addSubview(AKPropertySlider(
property: "Quality Factor",
format: "%0.1f",
value: filter.qualityFactor, minimum: 0.1, maximum: 20,
color: AKColor.redColor()
) { sliderValue in
filter.qualityFactor = sliderValue
})
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = PlaygroundView()
| mit | 7b4b4cd62ed88979b0f77418f8171697 | 25.545455 | 67 | 0.646575 | 5 | false | false | false | false |
dgollub/pokealmanac | PokeAlmanac/DB.swift | 1 | 25493 | //
// DB.swift
// PokeAlmanac
//
// Created by 倉重ゴルプ ダニエル on 2016/04/19.
// Copyright © 2016年 Daniel Kurashige-Gollub. All rights reserved.
//
import Foundation
import SQLite // using SQLite.swift https://github.com/stephencelis/SQLite.swift
import UIKit
import JSONJoy
import MapKit
import CoreLocation
//# Caching
//
// The app tries to cache the PokeAPI RESTful responses in a local SQLite database, however even so it states in the
// official documentation for version 2 of the API the modified/created timestamps are only avaiable in version 1.
//
//> If you are going to be regularly using the API, I recommend caching data on your service.
//> Luckily, we provide modified/created datetime stamps on every single resource so you can check for updates
//> (and thus make your caching efficient).
//
//
// See this issue on github for details: https://github.com/phalt/pokeapi/issues/140
//
private let DB_FILENAME: String = (applicationDocumentsFolder() as NSString).stringByAppendingPathComponent("pokedb.sqlite3")
private let API_VERSION: Int = 2
private let APP_VERSION: Int = 1
public let API_LIST_REQUEST_ID = -1 // whenever we want to cache the result of a "list" request, we use this ID
public enum APIType: String {
// NOTE(dkg): list access to API endpoint (name same as endpoint but without "list-" prefix)
case ListPokemon = "list-pokemon"
// NOTE(dkg): official API endpoints names - use this for individual ID/name access
// TODO(dkg): add more
case Pokemon = "pokemon"
case PokemonForm = "pokemon-form"
case PokemonSpecies = "pokemon-species"
case Move = "move"
}
public final class DB {
let db: Connection
init() {
db = try! Connection(DB_FILENAME)
log("DB_FILENAME \(DB_FILENAME)")
}
public func createTables() {
log("Create tables....")
createCacheTable()
createPokemonTables()
}
// TODO(dkg): improve error handling/reporting
public func insertOrUpdateCachedResponse(type: APIType, json: String, id: Int = API_LIST_REQUEST_ID, offset: Int = 0, limit: Int = 0, lastUpdated: NSDate = NSDate()) -> Void {
let apiCacheTable = Table("api_cache")
let idColumn = Expression<Int>("id")
let apiTypeColumn = Expression<String>("apiType")
let jsonColumn = Expression<String>("jsonResponse")
let lastUpdatedColumn = Expression<NSDate>("lastUpdated")
let limitColumn = Expression<Int>("listLimit")
let offsetColumn = Expression<Int>("listOffset")
let apiVersionColumn = Expression<Int>("apiVersion")
let appVersionColumn = Expression<Int>("appVersion")
let query = apiCacheTable
.filter(idColumn == id)
.filter(apiTypeColumn == type.rawValue)
.filter(limitColumn == limit)
.filter(offsetColumn == offset)
.filter(apiVersionColumn == API_VERSION)
.limit(1)
if db.pluck(query) != nil {
// update
let update = query.update(jsonColumn <- json, lastUpdatedColumn <- lastUpdated)
do {
let updatedCount = try db.run(update)
log("updated data: \(updatedCount)")
} catch {
log("could not update data: \(error)")
}
} else {
// insert
let insert = apiCacheTable.insert(idColumn <- id, apiTypeColumn <- type.rawValue,
limitColumn <- limit, offsetColumn <- offset,
lastUpdatedColumn <- lastUpdated,
appVersionColumn <- APP_VERSION, apiVersionColumn <- API_VERSION,
jsonColumn <- json)
do {
let rowid = try db.run(insert)
log("inserted data: \(rowid)")
} catch {
// TODO(dkg): catch the "database is locked" error and try again after a few milliseconds
logWarn("could not insert data: \(error)")
}
}
}
public func getCachedResponse(type: APIType, id: Int = API_LIST_REQUEST_ID, offset: Int = 0, limit: Int = 0) -> String? {
let apiCacheTable = Table("api_cache")
let idColumn = Expression<Int>("id")
let apiTypeColumn = Expression<String>("apiType")
let limitColumn = Expression<Int>("listLimit")
let offsetColumn = Expression<Int>("listOffset")
let jsonColumn = Expression<String>("jsonResponse")
let apiVersionColumn = Expression<Int>("apiVersion")
let query = apiCacheTable
.filter(idColumn == id)
.filter(apiTypeColumn == type.rawValue)
.filter(limitColumn == limit)
.filter(offsetColumn == offset)
.filter(apiVersionColumn == API_VERSION)
.limit(1)
let row = db.pluck(query)
let result = row?.get(jsonColumn)
return result
}
public func getLastUsedOffsetLimit(type: APIType) -> (offset: Int?, limit: Int?) {
let apiCacheTable = Table("api_cache")
let idColumn = Expression<Int>("id")
let apiTypeColumn = Expression<String>("apiType")
let limitColumn = Expression<Int>("listLimit")
let offsetColumn = Expression<Int>("listOffset")
let apiVersionColumn = Expression<Int>("apiVersion")
// NOTE(dkg): Does this return the right offset and limit at all times? Better double check this logic again!
let query = apiCacheTable
.filter(idColumn == API_LIST_REQUEST_ID)
.filter(apiTypeColumn == type.rawValue)
.filter(apiVersionColumn == API_VERSION)
.limit(1)
if let max = db.scalar(query.select(offsetColumn.max)) {
let innerQuery = query.filter(offsetColumn == max)
if let row = db.pluck(innerQuery) {
let limit = row.get(limitColumn)
return (max, limit == 0 ? nil : limit)
} else {
return (max, nil)
}
}
return (nil, nil)
}
public func getLastUsedID(type: APIType) -> Int? {
let apiCacheTable = Table("api_cache")
let idColumn = Expression<Int>("id")
let apiTypeColumn = Expression<String>("apiType")
let apiVersionColumn = Expression<Int>("apiVersion")
let query = apiCacheTable
.filter(apiTypeColumn == type.rawValue)
.filter(apiVersionColumn == API_VERSION)
.limit(1)
let max = db.scalar(query.select(idColumn.max))
return max
}
public func getPokemonCount() -> Int {
let count = db.scalar("SELECT COUNT(*) FROM pokemon") as! Int64
return Int(count)
}
func getMaximumCountPokemonsAvailableFromAPI() -> Int? {
var maxCount: Int? = nil
let apiCacheTable = Table("api_cache")
let idColumn = Expression<Int>("id")
let apiTypeColumn = Expression<String>("apiType")
let jsonColumn = Expression<String>("jsonResponse")
let apiVersionColumn = Expression<Int>("apiVersion")
let lastUpdatedColumn = Expression<NSDate>("lastUpdated")
// TODO(dkg): we should probably look at the LAST API result that we got for the
// pokemon list, instead of just a "random" (or rather the first) one like this
let query = apiCacheTable
.filter(idColumn == API_LIST_REQUEST_ID)
.filter(apiTypeColumn == APIType.ListPokemon.rawValue)
.filter(apiVersionColumn == API_VERSION)
.order(lastUpdatedColumn.desc)
.limit(1)
let row = db.pluck(query)
if let json = row?.get(jsonColumn) {
let resourceList = Transformer().jsonToNamedAPIResourceList(json)
if let list = resourceList {
maxCount = list.count
}
}
return maxCount
}
// TODO(dkg): refactor common table creation/statement execution code
private func createCacheTable() {
do {
// a table to cache ALL RESTful API calls; not the best solution, but the quickest to implement
// one could use a cache table for each individual API endpoint instead, but that's obviously more work
let sql = "CREATE TABLE IF NOT EXISTS api_cache (" +
"id INTEGER NOT NULL, " + // the actual resource ID used in the request, so this is not unique on its own
"apiType TEXT NOT NULL, " + // the RESTful API resource that was requested
"listLimit INTEGER NOT NULL DEFAULT 0, " + // limit is a reserved keyword
"listOffset INTEGER NOT NULL DEFAULT 0, " + // offset might be reserved keyword
"apiVersion INTEGER NOT NULL DEFAULT 2, " + // can't use the API_VERSION constant here, because the compiler complains about complexity of the expression ... what?! Why?! Must be a compiler bug.... == // Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions.
"appVersion INTEGER NOT NULL DEFAULT 1, " + // same here
"lastUpdated DATETIME NOT NULL DEFAULT NOW, " +
"jsonResponse TEXT, " +
"PRIMARY KEY (apiType, id, listLimit, listOffset)" + // TODO(dkg): Should apiVersion be part of the PK?
")"
// log("sql: \(sql)")
let stmt = try db.prepare(sql)
try stmt.run()
} catch {
logWarn("ERROR: Could not run SQL statement: \(error)")
}
}
private func createPokemonTables() {
do {
// TODO(dkg): Put all information that we want to display in the UITableView cells right here
// in additional columns, so we do not have to parse any JSON whatsoever when we
// just want to display the list of pokemons - this will solve our performance issue
// in the ListViewController where we currently parse JSON in order to populate our
// PokemonTableCells!!!!
let sql = "CREATE TABLE IF NOT EXISTS pokemon (" +
"id INTEGER PRIMARY KEY NOT NULL, " + // the actual resource ID for the pokemon
"name TEXT NOT NULL, " +
"favorite TINYINT NOT NULL DEFAULT 0, " +
"stars TINYINT NOT NULL DEFAULT 0, " +
"comment TEXT " +
")"
// log("sql: \(sql)")
let stmt = try db.prepare(sql)
try stmt.run()
} catch {
log("ERROR: Could not run SQL statement: \(error)")
}
do {
let sql = "CREATE TABLE IF NOT EXISTS backpack (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"pokemon_id INTEGER NOT NULL, " +
"foundlat FLOAT DEFAULT 0, " +
"foundlong FLOAT DEFAULT 0, " +
"founddate DATETIME DEFAULT NOW, " +
"name TEXT, " + // user can rename the pokemon
"FOREIGN KEY(pokemon_id) REFERENCES pokemon(id)" +
")"
// log("sql: \(sql)")
let stmt = try db.prepare(sql)
try stmt.run()
} catch {
logWarn("ERROR: Could not run SQL statement: \(error)")
}
}
public func savePokemon(pokemon: Pokemon, name: String? = nil, favorite: Bool = false, stars: Int = 0, comment: String? = nil) {
let pokemonTable = Table("pokemon")
let idColumn = Expression<Int>("id")
let nameColumn = Expression<String>("name")
let favoriteColumn = Expression<Bool>("favorite")
let starsColumn = Expression<Int>("stars")
let commentColumn = Expression<String>("comment")
let query = pokemonTable
.filter(idColumn == pokemon.id)
.limit(1)
let newName = name == nil ? pokemon.name : name!
let newComment = comment == nil ? "" : comment!
if db.pluck(query) != nil {
// update
let update = query.update(nameColumn <- newName,
favoriteColumn <- favorite,
starsColumn <- stars,
commentColumn <- newComment)
do {
let updatedCount = try db.run(update)
log("updated pokemon \(pokemon.id) data: \(updatedCount)")
} catch {
logWarn("could not update pokemon \(pokemon.id) data: \(error)")
}
} else {
// insert
let insert = pokemonTable.insert(idColumn <- pokemon.id,
nameColumn <- newName,
favoriteColumn <- favorite,
starsColumn <- stars,
commentColumn <- newComment)
do {
let rowid = try db.run(insert)
log("inserted pokemon \(pokemon.id) data: \(rowid)")
} catch {
logWarn("could not insert pokemon \(pokemon.id) data: \(error)")
}
}
}
public func getPokemonJSON(pokemonId: Int) -> String? {
return getCachedResponse(.Pokemon, id: pokemonId)
}
public func updatePokemonFavoriteStatus(pokemonId: Int, isFavorite: Bool) {
let pokemonTable = Table("pokemon")
let idColumn = Expression<Int>("id")
let favoriteColumn = Expression<Bool>("favorite")
let query = pokemonTable
.filter(idColumn == pokemonId)
.limit(1)
if db.pluck(query) != nil {
// update
let update = query.update(favoriteColumn <- isFavorite)
do {
let updatedCount = try db.run(update)
log("updated pokemon \(pokemonId) data: \(updatedCount)")
} catch {
logWarn("could not update pokemon \(pokemonId) data: \(error)")
}
}
}
public func isPokemonFavorite(pokemonId: Int) -> Bool {
let pokemonTable = Table("pokemon")
let idColumn = Expression<Int>("id")
let favoriteColumn = Expression<Bool>("favorite")
let query = pokemonTable.select(favoriteColumn)
.filter(idColumn == pokemonId)
let row = db.pluck(query)
return (row?.get(favoriteColumn))!
}
// public func loadPokemons() -> [Pokemon] {
public func loadPokemons(limit: Int = 0) -> [String] {
log("loadPokemons() start")
let pokemonTable = Table("pokemon")
let apiCacheTable = Table("api_cache")
let nameColumn = Expression<String>("name")
let pokemonIdColumn = Expression<Int>("id")
let idColumn = Expression<Int>("id")
let jsonColumn = Expression<String>("jsonResponse")
let apiTypeColumn = Expression<String>("apiType")
let joinQuery = pokemonTable.join(apiCacheTable, on: apiCacheTable[idColumn] == pokemonTable[pokemonIdColumn])
.filter(apiTypeColumn == APIType.Pokemon.rawValue)
.order(nameColumn)
let query = joinQuery.select(jsonColumn).order(nameColumn)
// let query = joinQuery.select(pokemonTable[pokemonIdColumn]).order(nameColumn)
var rows: AnySequence<Row>? = nil
if limit > 0 {
rows = try! db.prepare(query.limit(limit))
} else {
rows = try! db.prepare(query)
}
// NOTE(dkg): Using the JSONDecoder like this in the loop is really, really slow.
// Especially if we have more than a few Pokemons in the list.
// var result = [Pokemon]() ==> SLOWEST OF ALL!
// var result = [Int]() ==> Fastest of all, however then the actual cell drawing/rendering takes longer because
// each cell has to query the db again for the json and then parse it to a Pokemon object.
var result = [String]() // middle ground: no need for individual JSON lookup, but needs extra parsing for each cell
// when drawing
for row in rows! {
// NOTE(dkg): this autoreleasepool has a performance impact, but it also solve the memory pressure
// will need further profiling to figure out what the best course of action would be
autoreleasepool({
let json = row.get(jsonColumn)
// let data: NSData = json.dataUsingEncoding(NSUTF8StringEncoding)!
// let pokemon = try! Pokemon(JSONDecoder(data))
// let id: Int = row.get(pokemonTable[pokemonIdColumn])
// TODO(dkg): Actually replace the name with the custom name the user may have given this pokemon?!
// That is, if we ever figure out how we want this feature to work.
// Or remove this incomplete feature again.
// result.append(pokemon)
result.append(json)
})
}
log("loadPokemons() end")
return result
}
func loadPokemonsWithFilter(term: String) -> [String] {
log("loadPokemonsWithFilter(\(term))")
let pokemonTable = Table("pokemon")
let apiCacheTable = Table("api_cache")
let nameColumn = Expression<String>("name")
let pokemonIdColumn = Expression<Int>("id")
let idColumn = Expression<Int>("id")
let jsonColumn = Expression<String>("jsonResponse")
let apiTypeColumn = Expression<String>("apiType")
let joinQuery = pokemonTable.join(apiCacheTable, on: apiCacheTable[idColumn] == pokemonTable[pokemonIdColumn])
.filter(apiTypeColumn == APIType.Pokemon.rawValue)
.filter(pokemonTable[nameColumn].lowercaseString.like("%\(term.lowercaseString)%"))
.order(nameColumn)
let query = joinQuery.select(jsonColumn)
let rows = try! db.prepare(query)
var result = [String]()
for row in rows {
let json = row.get(jsonColumn)
result.append(json)
}
return result
}
public func loadFavoritePokemons() -> [Pokemon] {
log("loadFavoritePokemons() start")
let pokemonTable = Table("pokemon")
let apiCacheTable = Table("api_cache")
let nameColumn = Expression<String>("name")
let pokemonIdColumn = Expression<Int>("id")
let idColumn = Expression<Int>("id")
let favoriteColumn = Expression<Bool>("favorite")
let jsonColumn = Expression<String>("jsonResponse")
let apiTypeColumn = Expression<String>("apiType")
let joinQuery = pokemonTable.join(apiCacheTable, on: apiCacheTable[idColumn] == pokemonTable[pokemonIdColumn])
.filter(apiTypeColumn == APIType.Pokemon.rawValue)
.filter(favoriteColumn == true)
.order(nameColumn)
let query = joinQuery.select(jsonColumn)
let rows = try! db.prepare(query)
let transformer = Transformer()
var result = [Pokemon]()
for row in rows {
autoreleasepool({
let json = row.get(jsonColumn)
if let pokemon = transformer.jsonToPokemonModel(json) {
result.append(pokemon)
}
})
}
log("loadFavoritePokemons() end")
return result
}
public func savePokemonInBackpack(pokemon: Pokemon, latitude: Double, longitude: Double, name: String? = nil) {
let backpackTable = Table("backpack")
let pokemonColumn = Expression<Int>("pokemon_id")
let latColumn = Expression<Double>("foundlat")
let longColumn = Expression<Double>("foundlong")
let dateColumn = Expression<NSDate>("founddate")
let nameColumn = Expression<String>("name")
let newName = name == nil ? pokemon.name : name!
// always insert - we can have several pokemons of the same type/name in the backpack
let insert = backpackTable.insert(pokemonColumn <- pokemon.id,
nameColumn <- newName,
latColumn <- latitude,
longColumn <- longitude,
dateColumn <- NSDate())
do {
let rowid = try db.run(insert)
log("inserted pokemon \(pokemon.id) data in backpack: \(rowid)")
} catch {
logWarn("could not insert pokemon \(pokemon.id) data in backpack: \(error)")
}
}
public func removePokemonFromBackpack(pokemon: Pokemon, caughtOnDate: NSDate) {
let backpackTable = Table("backpack")
let pokemonColumn = Expression<Int>("pokemon_id")
let dateColumn = Expression<NSDate>("founddate")
let pokemonRow = backpackTable.filter(pokemonColumn == pokemon.id)
.filter(dateColumn == caughtOnDate)
do {
let rowid = try db.run(pokemonRow.delete())
log("delete pokemon \(pokemon.id) data from backpack: \(rowid)")
} catch {
logWarn("could not delete pokemon \(pokemon.id) data from backpack: \(error)")
}
}
public func loadPokemonFromBackpack(pokemonId: Int) -> Pokemon? {
let backpackTable = Table("backpack")
let pokemonIdColumn = Expression<Int>("pokemon_id")
let apiCacheTable = Table("api_cache")
let apiTypeColumn = Expression<String>("apiType")
let idColumn = Expression<Int>("id")
let jsonColumn = Expression<String>("jsonResponse")
let joinQuery = backpackTable.join(apiCacheTable, on: apiCacheTable[idColumn] == backpackTable[pokemonIdColumn])
.filter(apiTypeColumn == APIType.Pokemon.rawValue)
.filter(backpackTable[pokemonIdColumn] == pokemonId)
let query = joinQuery.select(jsonColumn)
if let row = db.pluck(query) {
return Transformer().jsonToPokemonModel(row.get(jsonColumn))
} else {
return nil
}
}
// TODO(dkg): this is slow when there are a lot of pokemon in the backpack - find a more
// performant way to do this
public func loadPokemonsFromBackpackAsPokemonAnnotations() -> [PokemonAnnotation] {
log("loadPokemonsFromBackpack() start")
let backpackTable = Table("backpack")
let apiCacheTable = Table("api_cache")
let nameColumn = Expression<String>("name")
let pokemonIdColumn = Expression<Int>("pokemon_id")
let idColumn = Expression<Int>("id")
let jsonColumn = Expression<String>("jsonResponse")
let apiTypeColumn = Expression<String>("apiType")
let latColumn = Expression<Double>("foundlat")
let longColumn = Expression<Double>("foundlong")
let dateColumn = Expression<NSDate>("founddate")
let joinQuery = backpackTable.join(apiCacheTable, on: apiCacheTable[idColumn] == backpackTable[pokemonIdColumn])
.filter(apiTypeColumn == APIType.Pokemon.rawValue)
.order(nameColumn)
let query = joinQuery.select(jsonColumn, latColumn, longColumn, dateColumn)
let rows = try! db.prepare(query)
let transformer = Transformer()
let dl = Downloader()
var result = [PokemonAnnotation]()
for row in rows {
autoreleasepool({
let json = row.get(jsonColumn)
if let pokemon = transformer.jsonToPokemonModel(json) {
let lat = row.get(latColumn)
let lon = row.get(longColumn)
let coords: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: lat, longitude: lon)
let image = dl.getPokemonSpriteFromCache(pokemon)
let date = row.get(dateColumn)
let annotation = PokemonAnnotation(coordinate: coords, pokemon: pokemon, image: image, found: date)
result.append(annotation)
}
})
}
log("loadPokemonsFromBackpack() end")
return result
}
}
| mit | 97076c5bfc2489b689e51dcc315168dc | 42.023649 | 353 | 0.558029 | 4.867189 | false | false | false | false |
mohsenShakiba/ListView | Example/ListView/HeightTestViewController.swift | 1 | 2526 | //
// BooksViewController.swift
// ListView
//
// Created by mohsen shakiba on 2/6/1396 AP.
// Copyright © 1396 CocoaPods. All rights reserved.
//
import Foundation
import ListView
class HeightTestViewController: ListViewController {
override func viewDidLoad() {
super.viewDidLoad()
setContent()
}
deinit {
print("deinit...")
}
func setContent() {
cell(LabelCell.self)
.setup { (cell) in
cell.label.text = "beck"
cell.size(50, 20, 20, 20)
}
.click({ (_) in
self.dismiss(animated: true, completion: nil)
})
.commit()
//
cell(LabelCell.self)
.setup { (cell) in
cell.label.text = "click for more"
}
.click({ (_) in
self.more()
})
.commit()
section { (s) in
}
.finalize("list")
more()
}
func more() {
self.beginUpdates()
guard let list = sectionBy(id: "list") else { return }
for i in 0...10 {
let randomInt = randomIntFrom(start: 10, to: 500)
let str = randomString(length: randomInt)
// list.reusableCell(LabelCell.self)
//
// .update({ (cell) in
// cell.label.text = str
// })
// .height({ () -> CGFloat in
// return LabelCell.size(forStr: str)
// })
// .commit()
list.reusableRow(LabelRow.self, model: str)
.update({ (row) in
row.textAlignment = .right
})
.commit()
}
self.endUpdates(false)
}
}
func randomString(length: Int) -> String {
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let len = UInt32(letters.length)
var randomString = ""
for _ in 0 ..< length {
let rand = arc4random_uniform(len)
var nextChar = letters.character(at: Int(rand))
randomString += NSString(characters: &nextChar, length: 1) as String
}
return randomString
}
func randomIntFrom(start: Int, to end: Int) -> Int {
var a = start
var b = end
// swap to prevent negative integer crashes
if a > b {
swap(&a, &b)
}
return Int(arc4random_uniform(UInt32(b - a + 1))) + a
}
| mit | 16cc8917a73c11410368ccf2cf608547 | 23.278846 | 93 | 0.490297 | 4.360967 | false | false | false | false |
Yokong/douyu | douyu/douyu/Classes/Home/Controller/HomeBaseController.swift | 1 | 3818 | //
// HomeBaseController.swift
// douyu
//
// Created by Yoko on 2017/5/4.
// Copyright © 2017年 Yokooll. All rights reserved.
//
import UIKit
//MARK:- ------内部常量------
fileprivate let itemMargin: CGFloat = 10
fileprivate let normalCellID = "normalCellID"
fileprivate let prettyCellID = "prettyCellID"
fileprivate let headerID = "headerID"
fileprivate let itemW = (Screen_W - 3 * itemMargin) / 2
fileprivate let itemH = itemW * 3 / 4
fileprivate let topViewH: CGFloat = 80 + 130
class HomeBaseController: UIViewController {
lazy var collectionView: UICollectionView = UICollectionView()
override func viewDidLoad() {
super.viewDidLoad()
setUp()
}
}
extension HomeBaseController {
func setUp() {
addCollcetionView()
}
func addCollcetionView() {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: itemW, height: itemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = itemMargin
layout.headerReferenceSize = CGSize(width: Screen_W, height: 44)
layout.sectionInset = UIEdgeInsets(top: 0, left: itemMargin, bottom: 0, right: itemMargin)
collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: normalCellID)
collectionView.register(UINib(nibName: "RecommendHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerID)
collectionView.register(UINib(nibName: "PrettyCollectionCell", bundle: nil), forCellWithReuseIdentifier: prettyCellID)
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
collectionView.contentInset = UIEdgeInsets(top: topViewH, left: 0, bottom: TabBar_H + itemMargin, right: 0)
view.addSubview(collectionView)
}
}
extension HomeBaseController: UICollectionViewDataSource, UICollectionViewDelegate {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return RecommentViewModel.shared.cates.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let cates = RecommentViewModel.shared.cates[section]
return cates.showers.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 取出模型
let cate = RecommentViewModel.shared.cates[indexPath.section]
let shower = cate.showers[indexPath.item]
if indexPath.section == 1 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: prettyCellID, for: indexPath) as! PrettyCollectionCell
cell.shower = shower
return cell
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: normalCellID, for: indexPath) as! CollectionNormalCell
cell.shower = shower
return cell
}
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerID, for: indexPath) as! RecommendHeaderView
header.cate = RecommentViewModel.shared.cates[indexPath.section]
return header
}
}
| mit | 5f4815997877abb46007d9f4aefb3acc | 31.75 | 180 | 0.691498 | 5.419401 | false | false | false | false |
gmertk/Moya | Demo/DemoTests/MoyaProviderSpec.swift | 1 | 10958 | import Quick
import Nimble
import Alamofire
import Moya
class MoyaProviderSpec: QuickSpec {
override func spec() {
var provider: MoyaProvider<GitHub>!
beforeEach {
provider = MoyaProvider<GitHub>(stubClosure: MoyaProvider.ImmediatelyStub)
}
it("returns stubbed data for zen request") {
var message: String?
let target: GitHub = .Zen
provider.request(target) { (data, statusCode, response, error) in
if let data = data {
message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
}
}
let sampleData = target.sampleData as NSData
expect(message).to(equal(NSString(data: sampleData, encoding: NSUTF8StringEncoding)))
}
it("returns stubbed data for user profile request") {
var message: String?
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target) { (data, statusCode, response, error) in
if let data = data {
message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
}
}
let sampleData = target.sampleData as NSData
expect(message).to(equal(NSString(data: sampleData, encoding: NSUTF8StringEncoding)))
}
it("returns equivalent Endpoint instances for the same target") {
let target: GitHub = .Zen
let endpoint1 = provider.endpoint(target)
let endpoint2 = provider.endpoint(target)
expect(endpoint1.urlRequest).to(equal(endpoint2.urlRequest))
}
it("returns a cancellable object when a request is made") {
let target: GitHub = .UserProfile("ashfurrow")
let cancellable: Cancellable = provider.request(target) { (_, _, _, _) in }
expect(cancellable).toNot(beNil())
}
it("uses the Alamofire.Manager.sharedInstance by default") {
expect(provider.manager).to(beIdenticalTo(Alamofire.Manager.sharedInstance))
}
it("credential closure returns nil") {
var called = false
let plugin = CredentialsPlugin<HTTPBin> { (target) -> NSURLCredential? in
called = true
return nil
}
let provider = MoyaProvider<HTTPBin>(stubClosure: MoyaProvider.ImmediatelyStub, plugins: [plugin])
let target: HTTPBin = .BasicAuth
provider.request(target) { (data, statusCode, response, error) in }
expect(called) == true
}
it("credential closure returns valid username and password") {
var called = false
let plugin = CredentialsPlugin<HTTPBin> { (target) -> NSURLCredential? in
called = true
return NSURLCredential(user: "user", password: "passwd", persistence: .None)
}
let provider = MoyaProvider<HTTPBin>(stubClosure: MoyaProvider.ImmediatelyStub, plugins: [plugin])
let target: HTTPBin = .BasicAuth
provider.request(target) { (data, statusCode, response, error) in }
expect(called) == true
}
it("accepts a custom Alamofire.Manager") {
let manager = Manager()
let provider = MoyaProvider<GitHub>(manager: manager)
expect(provider.manager).to(beIdenticalTo(manager))
}
it("uses a custom Alamofire.Manager for session challenges") {
var called = false
let manager = Manager()
manager.delegate.sessionDidReceiveChallenge = { (session, challenge) in
called = true
let disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
return (disposition, nil)
}
let provider = MoyaProvider<GitHub>(manager: manager)
let target: GitHub = .Zen
waitUntil(timeout: 3) { done in
provider.request(target) { (data, statusCode, response, error) in
done()
}
return
}
expect(called) == true
}
it("notifies at the beginning of network requests") {
var called = false
let plugin = NetworkActivityPlugin<GitHub> { (change) -> () in
if change == .Began {
called = true
}
}
let provider = MoyaProvider<GitHub>(stubClosure: MoyaProvider.ImmediatelyStub, plugins: [plugin])
let target: GitHub = .Zen
provider.request(target) { (data, statusCode, response, error) in }
expect(called) == true
}
it("notifies at the end of network requests") {
var called = false
let plugin = NetworkActivityPlugin<GitHub> { (change) -> () in
if change == .Ended {
called = true
}
}
let provider = MoyaProvider<GitHub>(stubClosure: MoyaProvider.ImmediatelyStub, plugins: [plugin])
let target: GitHub = .Zen
provider.request(target) { (data, statusCode, response, error) in }
expect(called) == true
}
it("delays execution when appropriate") {
let provider = MoyaProvider<GitHub>(stubClosure: MoyaProvider.DelayedStub(2))
let startDate = NSDate()
var endDate: NSDate?
let target: GitHub = .Zen
waitUntil(timeout: 3) { done in
provider.request(target) { (data, statusCode, response, error) in
endDate = NSDate()
done()
}
return
}
expect {
return endDate?.timeIntervalSinceDate(startDate)
}.to( beGreaterThanOrEqualTo(NSTimeInterval(2)) )
}
describe("a provider with a custom endpoint resolver") {
var provider: MoyaProvider<GitHub>!
var executed = false
beforeEach {
executed = false
let endpointResolution = { (endpoint: Endpoint<GitHub>, done: NSURLRequest -> Void) in
executed = true
done(endpoint.urlRequest)
}
provider = MoyaProvider<GitHub>(requestClosure: endpointResolution, stubClosure: MoyaProvider.ImmediatelyStub)
}
it("executes the endpoint resolver") {
let target: GitHub = .Zen
provider.request(target, completion: { (data, statusCode, response, error) in })
expect(executed).to(beTruthy())
}
}
describe("with stubbed errors") {
var provider: MoyaProvider<GitHub>!
beforeEach {
provider = MoyaProvider(endpointClosure: failureEndpointClosure, stubClosure: MoyaProvider.ImmediatelyStub)
}
it("returns stubbed data for zen request") {
var errored = false
let target: GitHub = .Zen
provider.request(target) { (object, statusCode, response, error) in
if error != nil {
errored = true
}
}
let _ = target.sampleData
expect(errored).toEventually(beTruthy())
}
it("returns stubbed data for user profile request") {
var errored = false
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target) { (object, statusCode, response, error) in
if error != nil {
errored = true
}
}
let _ = target.sampleData
expect{errored}.toEventually(beTruthy(), timeout: 1, pollInterval: 0.1)
}
it("returns stubbed error data when present") {
var receivedError: NSError?
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target) { (object, statusCode, response, error) in
receivedError = error as NSError?
}
expect(receivedError?.localizedDescription) == "Houston, we have a problem"
}
}
}
}
private extension String {
var URLEscapedString: String {
return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())!
}
}
private enum GitHub {
case Zen
case UserProfile(String)
}
extension GitHub : MoyaTarget {
var baseURL: NSURL { return NSURL(string: "https://api.github.com")! }
var path: String {
switch self {
case .Zen:
return "/zen"
case .UserProfile(let name):
return "/users/\(name.URLEscapedString)"
}
}
var method: Moya.Method {
return .GET
}
var parameters: [String: AnyObject]? {
return nil
}
var sampleData: NSData {
switch self {
case .Zen:
return "Half measures are as bad as nothing at all.".dataUsingEncoding(NSUTF8StringEncoding)!
case .UserProfile(let name):
return "{\"login\": \"\(name)\", \"id\": 100}".dataUsingEncoding(NSUTF8StringEncoding)!
}
}
}
private func url(route: MoyaTarget) -> String {
return route.baseURL.URLByAppendingPathComponent(route.path).absoluteString
}
private let failureEndpointClosure = { (target: GitHub) -> Endpoint<GitHub> in
let error = NSError(domain: "com.moya.error", code: 0, userInfo: [NSLocalizedDescriptionKey: "Houston, we have a problem"])
return Endpoint<GitHub>(URL: url(target), sampleResponseClosure: {.NetworkError(error)}, method: target.method, parameters: target.parameters)
}
private enum HTTPBin: MoyaTarget {
case BasicAuth
var baseURL: NSURL { return NSURL(string: "http://httpbin.org")! }
var path: String {
switch self {
case .BasicAuth:
return "/basic-auth/user/passwd"
}
}
var method: Moya.Method {
return .GET
}
var parameters: [String: AnyObject]? {
switch self {
default:
return [:]
}
}
var sampleData: NSData {
switch self {
case .BasicAuth:
return "{\"authenticated\": true, \"user\": \"user\"}".dataUsingEncoding(NSUTF8StringEncoding)!
}
}
}
| mit | 78d7cfbabdbf58488b76c093e091e047 | 34.577922 | 146 | 0.541705 | 5.501004 | false | false | false | false |
djwbrown/swift | test/Constraints/diagnostics.swift | 2 | 49046 | // RUN: %target-typecheck-verify-swift
protocol P {
associatedtype SomeType
}
protocol P2 {
func wonka()
}
extension Int : P {
typealias SomeType = Int
}
extension Double : P {
typealias SomeType = Double
}
func f0(_ x: Int,
_ y: Float) { }
func f1(_: @escaping (Int, Float) -> Int) { }
func f2(_: (_: (Int) -> Int)) -> Int {}
func f3(_: @escaping (_: @escaping (Int) -> Float) -> Int) {}
func f4(_ x: Int) -> Int { }
func f5<T : P2>(_ : T) { }
func f6<T : P, U : P>(_ t: T, _ u: U) where T.SomeType == U.SomeType {}
var i : Int
var d : Double
// Check the various forms of diagnostics the type checker can emit.
// Tuple size mismatch.
f1(
f4 // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '(Int, Float) -> Int'}}
)
// Tuple element unused.
f0(i, i,
i) // expected-error{{extra argument in call}}
// Position mismatch
f5(f4) // expected-error {{argument type '(Int) -> Int' does not conform to expected type 'P2'}}
// Tuple element not convertible.
f0(i,
d // expected-error {{cannot convert value of type 'Double' to expected argument type 'Float'}}
)
// Function result not a subtype.
f1(
f0 // expected-error {{cannot convert value of type '(Int, Float) -> ()' to expected argument type '(Int, Float) -> Int'}}
)
f3(
f2 // expected-error {{cannot convert value of type '(@escaping ((Int) -> Int)) -> Int' to expected argument type '(@escaping (Int) -> Float) -> Int'}}
)
f4(i, d) // expected-error {{extra argument in call}}
// Missing member.
i.wobble() // expected-error{{value of type 'Int' has no member 'wobble'}}
// Generic member does not conform.
extension Int {
func wibble<T: P2>(_ x: T, _ y: T) -> T { return x }
func wubble<T>(_ x: (Int) -> T) -> T { return x(self) }
}
i.wibble(3, 4) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}}
// Generic member args correct, but return type doesn't match.
struct A : P2 {
func wonka() {}
}
let a = A()
for j in i.wibble(a, a) { // expected-error {{type 'A' does not conform to protocol 'Sequence'}}
}
// Generic as part of function/tuple types
func f6<T:P2>(_ g: (Void) -> T) -> (c: Int, i: T) { // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{20-26=()}}
return (c: 0, i: g())
}
func f7() -> (c: Int, v: A) {
let g: (Void) -> A = { return A() } // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{10-16=()}}
return f6(g) // expected-error {{cannot convert return expression of type '(c: Int, i: A)' to return type '(c: Int, v: A)'}}
}
func f8<T:P2>(_ n: T, _ f: @escaping (T) -> T) {}
f8(3, f4) // expected-error {{in argument type '(Int) -> Int', 'Int' does not conform to expected type 'P2'}}
typealias Tup = (Int, Double)
func f9(_ x: Tup) -> Tup { return x }
f8((1,2.0), f9) // expected-error {{in argument type '(Tup) -> Tup' (aka '(Int, Double) -> (Int, Double)'), 'Tup' (aka '(Int, Double)') does not conform to expected type 'P2'}}
// <rdar://problem/19658691> QoI: Incorrect diagnostic for calling nonexistent members on literals
1.doesntExist(0) // expected-error {{value of type 'Int' has no member 'doesntExist'}}
[1, 2, 3].doesntExist(0) // expected-error {{value of type '[Int]' has no member 'doesntExist'}}
"awfawf".doesntExist(0) // expected-error {{value of type 'String' has no member 'doesntExist'}}
// Does not conform to protocol.
f5(i) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}}
// Make sure we don't leave open existentials when diagnosing.
// <rdar://problem/20598568>
func pancakes(_ p: P2) {
f4(p.wonka) // expected-error{{cannot convert value of type '() -> ()' to expected argument type 'Int'}}
f4(p.wonka()) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}}
}
protocol Shoes {
static func select(_ subject: Shoes) -> Self
}
// Here the opaque value has type (metatype_type (archetype_type ... ))
func f(_ x: Shoes, asType t: Shoes.Type) {
return t.select(x) // expected-error{{unexpected non-void return value in void function}}
}
precedencegroup Starry {
associativity: left
higherThan: MultiplicationPrecedence
}
infix operator **** : Starry
func ****(_: Int, _: String) { }
i **** i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}}
infix operator ***~ : Starry
func ***~(_: Int, _: String) { }
i ***~ i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}}
@available(*, unavailable, message: "call the 'map()' method on the sequence")
public func myMap<C : Collection, T>(
_ source: C, _ transform: (C.Iterator.Element) -> T
) -> [T] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message: "call the 'map()' method on the optional value")
public func myMap<T, U>(_ x: T?, _ f: (T) -> U) -> U? {
fatalError("unavailable function can't be called")
}
// <rdar://problem/20142523>
// FIXME: poor diagnostic, to be fixed in 20142462. For now, we just want to
// make sure that it doesn't crash.
func rdar20142523() {
myMap(0..<10, { x in // expected-error{{ambiguous reference to member '..<'}}
()
return x
})
}
// <rdar://problem/21080030> Bad diagnostic for invalid method call in boolean expression: (_, ExpressibleByIntegerLiteral)' is not convertible to 'ExpressibleByIntegerLiteral
func rdar21080030() {
var s = "Hello"
if s.characters.count() == 0 {} // expected-error{{cannot call value of non-function type 'String.CharacterView.IndexDistance'}}{{24-26=}}
}
// <rdar://problem/21248136> QoI: problem with return type inference mis-diagnosed as invalid arguments
func r21248136<T>() -> T { preconditionFailure() } // expected-note 2 {{in call to function 'r21248136()'}}
r21248136() // expected-error {{generic parameter 'T' could not be inferred}}
let _ = r21248136() // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/16375647> QoI: Uncallable funcs should be compile time errors
func perform<T>() {} // expected-error {{generic parameter 'T' is not used in function signature}}
// <rdar://problem/17080659> Error Message QOI - wrong return type in an overload
func recArea(_ h: Int, w : Int) {
return h * w // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/17224804> QoI: Error In Ternary Condition is Wrong
func r17224804(_ monthNumber : Int) {
// expected-error @+2 {{binary operator '+' cannot be applied to operands of type 'String' and 'Int'}}
// expected-note @+1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (UnsafeMutablePointer<Pointee>, Int), (UnsafePointer<Pointee>, Int)}}
let monthString = (monthNumber <= 9) ? ("0" + monthNumber) : String(monthNumber)
}
// <rdar://problem/17020197> QoI: Operand of postfix '!' should have optional type; type is 'Int?'
func r17020197(_ x : Int?, y : Int) {
if x! { } // expected-error {{'Int' is not convertible to 'Bool'}}
// <rdar://problem/12939553> QoI: diagnostic for using an integer in a condition is utterly terrible
if y {} // expected-error {{'Int' is not convertible to 'Bool'}}
}
// <rdar://problem/20714480> QoI: Boolean expr not treated as Bool type when function return type is different
func validateSaveButton(_ text: String) {
return (text.characters.count > 0) ? true : false // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/20201968> QoI: poor diagnostic when calling a class method via a metatype
class r20201968C {
func blah() {
r20201968C.blah() // expected-error {{instance member 'blah' cannot be used on type 'r20201968C'; did you mean to use a value of this type instead?}}
}
}
// <rdar://problem/21459429> QoI: Poor compilation error calling assert
func r21459429(_ a : Int) {
assert(a != nil, "ASSERT COMPILATION ERROR")
// expected-warning @-1 {{comparing non-optional value of type 'Int' to nil always returns true}}
}
// <rdar://problem/21362748> [WWDC Lab] QoI: cannot subscript a value of type '[Int]?' with an index of type 'Int'
struct StructWithOptionalArray {
var array: [Int]?
}
func testStructWithOptionalArray(_ foo: StructWithOptionalArray) -> Int {
return foo.array[0] // expected-error {{value of optional type '[Int]?' not unwrapped; did you mean to use '!' or '?'?}} {{19-19=!}}
}
// <rdar://problem/19774755> Incorrect diagnostic for unwrapping non-optional bridged types
var invalidForceUnwrap = Int()! // expected-error {{cannot force unwrap value of non-optional type 'Int'}} {{31-32=}}
// <rdar://problem/20905802> Swift using incorrect diagnostic sometimes on String().asdf
String().asdf // expected-error {{value of type 'String' has no member 'asdf'}}
// <rdar://problem/21553065> Spurious diagnostic: '_' can only appear in a pattern or on the left side of an assignment
protocol r21553065Protocol {}
class r21553065Class<T : AnyObject> {}
_ = r21553065Class<r21553065Protocol>() // expected-error {{'r21553065Protocol' is not convertible to 'AnyObject'}}
// Type variables not getting erased with nested closures
struct Toe {
let toenail: Nail // expected-error {{use of undeclared type 'Nail'}}
func clip() {
toenail.inspect { x in
toenail.inspect { y in }
}
}
}
// <rdar://problem/21447318> dot'ing through a partially applied member produces poor diagnostic
class r21447318 {
var x = 42
func doThing() -> r21447318 { return self }
}
func test21447318(_ a : r21447318, b : () -> r21447318) {
a.doThing.doThing() // expected-error {{method 'doThing' was used as a property; add () to call it}} {{12-12=()}}
b.doThing() // expected-error {{function 'b' was used as a property; add () to call it}} {{4-4=()}}
}
// <rdar://problem/20409366> Diagnostics for init calls should print the class name
class r20409366C {
init(a : Int) {}
init?(a : r20409366C) {
let req = r20409366C(a: 42)? // expected-error {{cannot use optional chaining on non-optional value of type 'r20409366C'}} {{32-33=}}
}
}
// <rdar://problem/18800223> QoI: wrong compiler error when swift ternary operator branches don't match
func r18800223(_ i : Int) {
// 20099385
_ = i == 0 ? "" : i // expected-error {{result values in '? :' expression have mismatching types 'String' and 'Int'}}
// 19648528
_ = true ? [i] : i // expected-error {{result values in '? :' expression have mismatching types '[Int]' and 'Int'}}
var buttonTextColor: String?
_ = (buttonTextColor != nil) ? 42 : {$0}; // expected-error {{result values in '? :' expression have mismatching types 'Int' and '(_) -> _'}}
}
// <rdar://problem/21883806> Bogus "'_' can only appear in a pattern or on the left side of an assignment" is back
_ = { $0 } // expected-error {{unable to infer closure type in the current context}}
_ = 4() // expected-error {{cannot call value of non-function type 'Int'}}{{6-8=}}
_ = 4(1) // expected-error {{cannot call value of non-function type 'Int'}}
// <rdar://problem/21784170> Incongruous `unexpected trailing closure` error in `init` function which is cast and called without trailing closure.
func rdar21784170() {
let initial = (1.0 as Double, 2.0 as Double)
(Array.init as (Double...) -> Array<Double>)(initial as (Double, Double)) // expected-error {{cannot convert value of type '(Double, Double)' to expected argument type 'Double'}}
}
// <rdar://problem/21829141> BOGUS: unexpected trailing closure
func expect<T, U>(_: T) -> (U.Type) -> Int { return { a in 0 } }
func expect<T, U>(_: T, _: Int = 1) -> (U.Type) -> String { return { a in "String" } }
let expectType1 = expect(Optional(3))(Optional<Int>.self)
let expectType1Check: Int = expectType1
// <rdar://problem/19804707> Swift Enum Scoping Oddity
func rdar19804707() {
enum Op {
case BinaryOperator((Double, Double) -> Double)
}
var knownOps : Op
knownOps = Op.BinaryOperator({$1 - $0})
knownOps = Op.BinaryOperator(){$1 - $0}
knownOps = Op.BinaryOperator{$1 - $0}
knownOps = .BinaryOperator({$1 - $0})
// rdar://19804707 - trailing closures for contextual member references.
knownOps = .BinaryOperator(){$1 - $0}
knownOps = .BinaryOperator{$1 - $0}
_ = knownOps
}
func f7(_ a: Int) -> (_ b: Int) -> Int {
return { b in a+b }
}
_ = f7(1)(1)
f7(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(b: 1.0) // expected-error{{extraneous argument label 'b:' in call}}
let f8 = f7(2)
_ = f8(1)
f8(10) // expected-warning {{result of call is unused, but produces 'Int'}}
f8(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f8(b: 1.0) // expected-error {{extraneous argument label 'b:' in call}}
class CurriedClass {
func method1() {}
func method2(_ a: Int) -> (_ b : Int) -> () { return { b in () } }
func method3(_ a: Int, b : Int) {} // expected-note 5 {{'method3(_:b:)' declared here}}
}
let c = CurriedClass()
_ = c.method1
c.method1(1) // expected-error {{argument passed to call that takes no arguments}}
_ = c.method2(1)
_ = c.method2(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1)(2)
c.method2(1)(c: 2) // expected-error {{extraneous argument label 'c:' in call}}
c.method2(1)(c: 2.0) // expected-error {{extraneous argument label 'c:' in call}}
c.method2(1)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method1(c)()
_ = CurriedClass.method1(c)
CurriedClass.method1(c)(1) // expected-error {{argument passed to call that takes no arguments}}
CurriedClass.method1(2.0)(1) // expected-error {{instance member 'method1' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method2(c)(32)(b: 1) // expected-error{{extraneous argument label 'b:' in call}}
_ = CurriedClass.method2(c)
_ = CurriedClass.method2(c)(32)
_ = CurriedClass.method2(1,2) // expected-error {{instance member 'method2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method2(c)(1.0)(b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method2(c)(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method2(c)(2)(c: 1.0) // expected-error {{extraneous argument label 'c:'}}
CurriedClass.method3(c)(32, b: 1)
_ = CurriedClass.method3(c)
_ = CurriedClass.method3(c)(1, 2) // expected-error {{missing argument label 'b:' in call}} {{32-32=b: }}
_ = CurriedClass.method3(c)(1, b: 2)(32) // expected-error {{cannot call value of non-function type '()'}}
_ = CurriedClass.method3(1, 2) // expected-error {{instance member 'method3' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method3(c)(1.0, b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method3(c)(1) // expected-error {{missing argument for parameter 'b' in call}}
CurriedClass.method3(c)(c: 1.0) // expected-error {{missing argument for parameter 'b' in call}}
extension CurriedClass {
func f() {
method3(1, b: 2)
method3() // expected-error {{missing argument for parameter #1 in call}}
method3(42) // expected-error {{missing argument for parameter 'b' in call}}
method3(self) // expected-error {{missing argument for parameter 'b' in call}}
}
}
extension CurriedClass {
func m1(_ a : Int, b : Int) {}
func m2(_ a : Int) {}
}
// <rdar://problem/23718816> QoI: "Extra argument" error when accidentally currying a method
CurriedClass.m1(2, b: 42) // expected-error {{instance member 'm1' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// <rdar://problem/22108559> QoI: Confusing error message when calling an instance method as a class method
CurriedClass.m2(12) // expected-error {{instance member 'm2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// <rdar://problem/20491794> Error message does not tell me what the problem is
enum Color {
case Red
case Unknown(description: String)
static func rainbow() -> Color {}
static func overload(a : Int) -> Color {}
static func overload(b : Int) -> Color {}
static func frob(_ a : Int, b : inout Int) -> Color {}
}
let _: (Int, Color) = [1,2].map({ ($0, .Unknown("")) }) // expected-error {{'map' produces '[T]', not the expected contextual result type '(Int, Color)'}}
let _: [(Int, Color)] = [1,2].map({ ($0, .Unknown("")) })// expected-error {{missing argument label 'description:' in call}} {{51-51=description: }}
let _: [Color] = [1,2].map { _ in .Unknown("") }// expected-error {{missing argument label 'description:' in call}} {{44-44=description: }}
let _: (Int) -> (Int, Color) = { ($0, .Unknown("")) } // expected-error {{missing argument label 'description:' in call}} {{48-48=description: }}
let _: Color = .Unknown("") // expected-error {{missing argument label 'description:' in call}} {{25-25=description: }}
let _: Color = .Unknown // expected-error {{member 'Unknown' expects argument of type '(description: String)'}}
let _: Color = .Unknown(42) // expected-error {{missing argument label 'description:' in call}}
let _ : Color = .rainbow(42) // expected-error {{argument passed to call that takes no arguments}}
let _ : (Int, Float) = (42.0, 12) // expected-error {{cannot convert value of type 'Double' to specified type 'Int'}}
let _ : Color = .rainbow // expected-error {{member 'rainbow' is a function; did you mean to call it?}} {{25-25=()}}
let _: Color = .overload(a : 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .overload(1.0) // expected-error {{ambiguous reference to member 'overload'}}
// expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}}
let _: Color = .overload(1) // expected-error {{ambiguous reference to member 'overload'}}
// expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}}
let _: Color = .frob(1.0, &i) // expected-error {{missing argument label 'b:' in call}}
let _: Color = .frob(1.0, b: &i) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .frob(1, i) // expected-error {{missing argument label 'b:' in call}}
let _: Color = .frob(1, b: i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}}
let _: Color = .frob(1, &d) // expected-error {{missing argument label 'b:' in call}}
let _: Color = .frob(1, b: &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
var someColor : Color = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'}}
someColor = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'}}
func testTypeSugar(_ a : Int) {
typealias Stride = Int
let x = Stride(a)
x+"foo" // expected-error {{binary operator '+' cannot be applied to operands of type 'Stride' (aka 'Int') and 'String'}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}}
}
// <rdar://problem/21974772> SegFault in FailureDiagnosis::visitInOutExpr
func r21974772(_ y : Int) {
let x = &(1.0 + y) // expected-error {{binary operator '+' cannot be applied to operands of type 'Double' and 'Int'}}
//expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: }}
}
// <rdar://problem/22020088> QoI: missing member diagnostic on optional gives worse error message than existential/bound generic/etc
protocol r22020088P {}
func r22020088Foo<T>(_ t: T) {}
func r22020088bar(_ p: r22020088P?) {
r22020088Foo(p.fdafs) // expected-error {{value of type 'r22020088P?' has no member 'fdafs'}}
}
// <rdar://problem/22288575> QoI: poor diagnostic involving closure, bad parameter label, and mismatch return type
func f(_ arguments: [String]) -> [ArraySlice<String>] {
return arguments.split(maxSplits: 1, omittingEmptySubsequences: false, whereSeparator: { $0 == "--" })
}
struct AOpts : OptionSet {
let rawValue : Int
}
class B {
func function(_ x : Int8, a : AOpts) {}
func f2(_ a : AOpts) {}
static func f1(_ a : AOpts) {}
}
func test(_ a : B) {
B.f1(nil) // expected-error {{nil is not compatible with expected argument type 'AOpts'}}
a.function(42, a: nil) //expected-error {{nil is not compatible with expected argument type 'AOpts'}}
a.function(42, nil) //expected-error {{missing argument label 'a:' in call}}
a.f2(nil) // expected-error {{nil is not compatible with expected argument type 'AOpts'}}
}
// <rdar://problem/21684487> QoI: invalid operator use inside a closure reported as a problem with the closure
typealias MyClosure = ([Int]) -> Bool
func r21684487() {
var closures = Array<MyClosure>()
let testClosure = {(list: [Int]) -> Bool in return true}
let closureIndex = closures.index{$0 === testClosure} // expected-error {{cannot check reference equality of functions; operands here have types '_' and '([Int]) -> Bool'}}
}
// <rdar://problem/18397777> QoI: special case comparisons with nil
func r18397777(_ d : r21447318?) {
let c = r21447318()
if c != nil { // expected-warning {{comparing non-optional value of type 'r21447318' to nil always returns true}}
}
if d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{6-6=(}} {{7-7= != nil)}}
}
if !d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{7-7=(}} {{8-8= != nil)}}
}
if !Optional(c) { // expected-error {{optional type 'Optional<r21447318>' cannot be used as a boolean; test for '!= nil' instead}} {{7-7=(}} {{18-18= != nil)}}
}
}
// <rdar://problem/22255907> QoI: bad diagnostic if spurious & in argument list
func r22255907_1<T>(_ a : T, b : Int) {}
func r22255907_2<T>(_ x : Int, a : T, b: Int) {}
func reachabilityForInternetConnection() {
var variable: Int = 42
r22255907_1(&variable, b: 2.1) // expected-error {{'&' used with non-inout argument of type 'Int'}} {{15-16=}}
r22255907_2(1, a: &variable, b: 2.1)// expected-error {{'&' used with non-inout argument of type 'Int'}} {{21-22=}}
}
// <rdar://problem/21601687> QoI: Using "=" instead of "==" in if statement leads to incorrect error message
if i = 6 { } // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{6-7===}}
_ = (i = 6) ? 42 : 57 // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{8-9===}}
// <rdar://problem/22263468> QoI: Not producing specific argument conversion diagnostic for tuple init
func r22263468(_ a : String?) {
typealias MyTuple = (Int, String)
_ = MyTuple(42, a) // expected-error {{value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?}} {{20-20=!}}
}
// rdar://22470302 - Crash with parenthesized call result.
class r22470302Class {
func f() {}
}
func r22470302(_ c: r22470302Class) {
print((c.f)(c)) // expected-error {{argument passed to call that takes no arguments}}
}
// <rdar://problem/21928143> QoI: Pointfree reference to generic initializer in generic context does not compile
extension String {
@available(*, unavailable, message: "calling this is unwise")
func unavail<T : Sequence> // expected-note 2 {{'unavail' has been explicitly marked unavailable here}}
(_ a : T) -> String where T.Iterator.Element == String {}
}
extension Array {
func g() -> String {
return "foo".unavail([""]) // expected-error {{'unavail' is unavailable: calling this is unwise}}
}
func h() -> String {
return "foo".unavail([0]) // expected-error {{'unavail' is unavailable: calling this is unwise}}
}
}
// <rdar://problem/22519983> QoI: Weird error when failing to infer archetype
func safeAssign<T: RawRepresentable>(_ lhs: inout T) -> Bool {}
// expected-note @-1 {{in call to function 'safeAssign'}}
let a = safeAssign // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/21692808> QoI: Incorrect 'add ()' fixit with trailing closure
struct Radar21692808<Element> {
init(count: Int, value: Element) {}
}
func radar21692808() -> Radar21692808<Int> {
return Radar21692808<Int>(count: 1) { // expected-error {{cannot invoke initializer for type 'Radar21692808<Int>' with an argument list of type '(count: Int, () -> Int)'}}
// expected-note @-1 {{expected an argument list of type '(count: Int, value: Element)'}}
return 1
}
}
// <rdar://problem/17557899> - This shouldn't suggest calling with ().
func someOtherFunction() {}
func someFunction() -> () {
// Producing an error suggesting that this
return someOtherFunction // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/23560128> QoI: trying to mutate an optional dictionary result produces bogus diagnostic
func r23560128() {
var a : (Int,Int)?
a.0 = 42 // expected-error {{value of optional type '(Int, Int)?' not unwrapped; did you mean to use '!' or '?'?}} {{4-4=?}}
}
// <rdar://problem/21890157> QoI: wrong error message when accessing properties on optional structs without unwrapping
struct ExampleStruct21890157 {
var property = "property"
}
var example21890157: ExampleStruct21890157?
example21890157.property = "confusing" // expected-error {{value of optional type 'ExampleStruct21890157?' not unwrapped; did you mean to use '!' or '?'?}} {{16-16=?}}
struct UnaryOp {}
_ = -UnaryOp() // expected-error {{unary operator '-' cannot be applied to an operand of type 'UnaryOp'}}
// expected-note @-1 {{overloads for '-' exist with these partially matching parameter lists: (Float), (Double)}}
// <rdar://problem/23433271> Swift compiler segfault in failure diagnosis
func f23433271(_ x : UnsafePointer<Int>) {}
func segfault23433271(_ a : UnsafeMutableRawPointer) {
f23433271(a[0]) // expected-error {{type 'UnsafeMutableRawPointer' has no subscript members}}
}
// <rdar://problem/23272739> Poor diagnostic due to contextual constraint
func r23272739(_ contentType: String) {
let actualAcceptableContentTypes: Set<String> = []
return actualAcceptableContentTypes.contains(contentType) // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/23641896> QoI: Strings in Swift cannot be indexed directly with integer offsets
func r23641896() {
var g = "Hello World"
g.replaceSubrange(0...2, with: "ce") // expected-error {{cannot convert value of type 'CountableClosedRange<Int>' to expected argument type 'Range<String.Index>'}}
_ = g[12] // expected-error {{'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion}}
}
// <rdar://problem/23718859> QoI: Incorrectly flattening ((Int,Int)) argument list to (Int,Int) when printing note
func test17875634() {
var match: [(Int, Int)] = []
var row = 1
var col = 2
match.append(row, col) // expected-error {{instance method 'append' expects a single parameter of type '(Int, Int)'}} {{16-16=(}} {{24-24=)}}
}
// <https://github.com/apple/swift/pull/1205> Improved diagnostics for enums with associated values
enum AssocTest {
case one(Int)
}
if AssocTest.one(1) == AssocTest.one(1) {} // expected-error{{binary operator '==' cannot be applied to two 'AssocTest' operands}}
// expected-note @-1 {{binary operator '==' cannot be synthesized for enums with associated values}}
// <rdar://problem/24251022> Swift 2: Bad Diagnostic Message When Adding Different Integer Types
func r24251022() {
var a = 1
var b: UInt32 = 2
_ = a + b // expected-warning {{deprecated}}
a += a + // expected-error {{binary operator '+=' cannot be applied to operands of type 'Int' and 'UInt32'}} expected-note {{overloads for '+=' exist}}
b
}
func overloadSetResultType(_ a : Int, b : Int) -> Int {
// https://twitter.com/_jlfischer/status/712337382175952896
// TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
return a == b && 1 == 2 // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
postfix operator +++
postfix func +++ <T>(_: inout T) -> T { fatalError() }
// <rdar://problem/21523291> compiler error message for mutating immutable field is incorrect
func r21523291(_ bytes : UnsafeMutablePointer<UInt8>) {
let i = 42 // expected-note {{change 'let' to 'var' to make it mutable}}
_ = bytes[i+++] // expected-error {{cannot pass immutable value as inout argument: 'i' is a 'let' constant}}
}
// SR-1594: Wrong error description when using === on non-class types
class SR1594 {
func sr1594(bytes : UnsafeMutablePointer<Int>, _ i : Int?) {
_ = (i === nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15===}}
_ = (bytes === nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}}
_ = (self === nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to nil always returns false}}
_ = (i !== nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15=!=}}
_ = (bytes !== nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}}
_ = (self !== nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to nil always returns true}}
}
}
func nilComparison(i: Int, o: AnyObject) {
_ = i == nil // expected-warning {{comparing non-optional value of type 'Int' to nil always returns false}}
_ = nil == i // expected-warning {{comparing non-optional value of type 'Int' to nil always returns false}}
_ = i != nil // expected-warning {{comparing non-optional value of type 'Int' to nil always returns true}}
_ = nil != i // expected-warning {{comparing non-optional value of type 'Int' to nil always returns true}}
// FIXME(integers): uncomment these tests once the < is no longer ambiguous
// _ = i < nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil < i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i <= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil <= i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i > nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil > i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i >= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil >= i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
_ = o === nil // expected-warning {{comparing non-optional value of type 'AnyObject' to nil always returns false}}
_ = o !== nil // expected-warning {{comparing non-optional value of type 'AnyObject' to nil always returns true}}
}
func secondArgumentNotLabeled(a: Int, _ b: Int) { }
secondArgumentNotLabeled(10, 20)
// expected-error@-1 {{missing argument label 'a' in call}}
// <rdar://problem/23709100> QoI: incorrect ambiguity error due to implicit conversion
func testImplConversion(a : Float?) -> Bool {}
func testImplConversion(a : Int?) -> Bool {
let someInt = 42
let a : Int = testImplConversion(someInt) // expected-error {{argument labels '(_:)' do not match any available overloads}}
// expected-note @-1 {{overloads for 'testImplConversion' exist with these partially matching parameter lists: (a: Float?), (a: Int?)}}
}
// <rdar://problem/23752537> QoI: Bogus error message: Binary operator '&&' cannot be applied to two 'Bool' operands
class Foo23752537 {
var title: String?
var message: String?
}
extension Foo23752537 {
func isEquivalent(other: Foo23752537) {
// TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
// expected-error @+1 {{unexpected non-void return value in void function}}
return (self.title != other.title && self.message != other.message)
}
}
// <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
func rdar27391581(_ a : Int, b : Int) -> Int {
return a == b && b != 0
// expected-error @-1 {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// <rdar://problem/22276040> QoI: not great error message with "withUnsafePointer" sametype constraints
func read2(_ p: UnsafeMutableRawPointer, maxLength: Int) {}
func read<T : BinaryInteger>() -> T? {
var buffer : T
let n = withUnsafePointer(to: &buffer) { (p) in
read2(UnsafePointer(p), maxLength: MemoryLayout<T>.size) // expected-error {{cannot convert value of type 'UnsafePointer<_>' to expected argument type 'UnsafeMutableRawPointer'}}
}
}
func f23213302() {
var s = Set<Int>()
s.subtractInPlace(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'Set<Int>'}}
}
// <rdar://problem/24202058> QoI: Return of call to overloaded function in void-return context
func rdar24202058(a : Int) {
return a <= 480 // expected-error {{unexpected non-void return value in void function}}
}
// SR-1752: Warning about unused result with ternary operator
struct SR1752 {
func foo() {}
}
let sr1752: SR1752?
true ? nil : sr1752?.foo() // don't generate a warning about unused result since foo returns Void
// <rdar://problem/27891805> QoI: FailureDiagnosis doesn't look through 'try'
struct rdar27891805 {
init(contentsOf: String, encoding: String) throws {}
init(contentsOf: String, usedEncoding: inout String) throws {}
init<T>(_ t: T) {}
}
try rdar27891805(contentsOfURL: nil, usedEncoding: nil)
// expected-error@-1 {{argument labels '(contentsOfURL:, usedEncoding:)' do not match any available overloads}}
// expected-note@-2 {{overloads for 'rdar27891805' exist with these partially matching parameter lists: (contentsOf: String, encoding: String), (contentsOf: String, usedEncoding: inout String)}}
// Make sure RawRepresentable fix-its don't crash in the presence of type variables
class NSCache<K, V> {
func object(forKey: K) -> V? {}
}
class CacheValue {
func value(x: Int) -> Int {} // expected-note {{found this candidate}}
func value(y: String) -> String {} // expected-note {{found this candidate}}
}
func valueForKey<K>(_ key: K) -> CacheValue? {
let cache = NSCache<K, CacheValue>()
return cache.object(forKey: key)?.value // expected-error {{ambiguous reference to member 'value(x:)'}}
}
// SR-2242: poor diagnostic when argument label is omitted
func r27212391(x: Int, _ y: Int) {
let _: Int = x + y
}
func r27212391(a: Int, x: Int, _ y: Int) {
let _: Int = a + x + y
}
r27212391(3, 5) // expected-error {{missing argument label 'x' in call}}
r27212391(3, y: 5) // expected-error {{missing argument label 'x' in call}}
r27212391(3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #1}} {{11-11=x: 5, }} {{12-18=}}
r27212391(y: 3, x: 5) // expected-error {{argument 'x' must precede argument 'y'}} {{11-11=x: 5, }} {{15-21=}}
r27212391(y: 3, 5) // expected-error {{incorrect argument label in call (have 'y:_:', expected 'x:_:')}}
r27212391(x: 3, x: 5) // expected-error {{extraneous argument label 'x:' in call}}
r27212391(a: 1, 3, y: 5) // expected-error {{missing argument label 'x' in call}}
r27212391(1, x: 3, y: 5) // expected-error {{missing argument label 'a' in call}}
r27212391(a: 1, y: 3, x: 5) // expected-error {{argument 'x' must precede argument 'y'}} {{17-17=x: 5, }} {{21-27=}}
r27212391(a: 1, 3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #2}} {{17-17=x: 5, }} {{18-24=}}
// SR-1255
func foo1255_1() {
return true || false // expected-error {{unexpected non-void return value in void function}}
}
func foo1255_2() -> Int {
return true || false // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// SR-2505: "Call arguments did not match up" assertion
// Here we're simulating the busted Swift 3 behavior -- see
// test/Constraints/diagnostics_swift4.swift for the correct
// behavior.
func sr_2505(_ a: Any) {} // expected-note {{}}
sr_2505() // expected-error {{missing argument for parameter #1 in call}}
sr_2505(a: 1) // FIXME: emit a warning saying this becomes an error in Swift 4
sr_2505(1, 2) // expected-error {{extra argument in call}}
sr_2505(a: 1, 2) // expected-error {{extra argument in call}}
struct C_2505 {
init(_ arg: Any) {
}
}
protocol P_2505 {
}
extension C_2505 {
init<T>(from: [T]) where T: P_2505 {
}
}
class C2_2505: P_2505 {
}
// FIXME: emit a warning saying this becomes an error in Swift 4
let c_2505 = C_2505(arg: [C2_2505()])
// Diagnostic message for initialization with binary operations as right side
let foo1255_3: String = 1 + 2 + 3 // expected-error {{cannot convert value of type 'Int' to specified type 'String'}}
let foo1255_4: Dictionary<String, String> = ["hello": 1 + 2] // expected-error {{cannot convert value of type 'Int' to expected dictionary value type 'String'}}
let foo1255_5: Dictionary<String, String> = [(1 + 2): "world"] // expected-error {{cannot convert value of type 'Int' to expected dictionary key type 'String'}}
let foo1255_6: [String] = [1 + 2 + 3] // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}}
// SR-2208
struct Foo2208 {
func bar(value: UInt) {}
}
func test2208() {
let foo = Foo2208()
let a: Int = 1
let b: Int = 2
let result = a / b
foo.bar(value: a / b) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
foo.bar(value: result) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
foo.bar(value: UInt(result)) // Ok
}
// SR-2164: Erroneous diagnostic when unable to infer generic type
struct SR_2164<A, B> { // expected-note 3 {{'B' declared as parameter to type 'SR_2164'}} expected-note 2 {{'A' declared as parameter to type 'SR_2164'}} expected-note * {{generic type 'SR_2164' declared here}}
init(a: A) {}
init(b: B) {}
init(c: Int) {}
init(_ d: A) {}
init(e: A?) {}
}
struct SR_2164_Array<A, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Array'}} expected-note * {{generic type 'SR_2164_Array' declared here}}
init(_ a: [A]) {}
}
struct SR_2164_Dict<A: Hashable, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Dict'}} expected-note * {{generic type 'SR_2164_Dict' declared here}}
init(a: [A: Double]) {}
}
SR_2164(a: 0) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(b: 1) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(c: 2) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(3) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164_Array([4]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(e: 5) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164_Dict(a: ["pi": 3.14]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164<Int>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}}
SR_2164<Int>(b: 1) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}}
let _ = SR_2164<Int, Bool>(a: 0) // Ok
let _ = SR_2164<Int, Bool>(b: true) // Ok
SR_2164<Int, Bool, Float>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}}
SR_2164<Int, Bool, Float>(b: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}}
// <rdar://problem/29850459> Swift compiler misreports type error in ternary expression
let r29850459_flag = true
let r29850459_a: Int = 0
let r29850459_b: Int = 1
func r29850459() -> Bool { return false }
let _ = (r29850459_flag ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}}
let _ = ({ true }() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}}
let _ = (r29850459() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}}
let _ = ((r29850459_flag || r29850459()) ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}}
// Ambiguous overload inside a trailing closure
func ambiguousCall() -> Int {} // expected-note {{found this candidate}}
func ambiguousCall() -> Float {} // expected-note {{found this candidate}}
func takesClosure(fn: () -> ()) {}
takesClosure() { ambiguousCall() } // expected-error {{ambiguous use of 'ambiguousCall()'}}
// SR-4692: Useless diagnostics calling non-static method
class SR_4692_a {
private static func foo(x: Int, y: Bool) {
self.bar(x: x)
// expected-error@-1 {{instance member 'bar' cannot be used on type 'SR_4692_a'}}
}
private func bar(x: Int) {
}
}
class SR_4692_b {
static func a() {
self.f(x: 3, y: true)
// expected-error@-1 {{instance member 'f' cannot be used on type 'SR_4692_b'}}
}
private func f(a: Int, b: Bool, c: String) {
self.f(x: a, y: b)
}
private func f(x: Int, y: Bool) {
}
}
// rdar://problem/32101765 - Keypath diagnostics are not actionable/helpful
struct R32101765 { let prop32101765 = 0 }
let _: KeyPath<R32101765, Float> = \.prop32101765
// expected-error@-1 {{KeyPath value type 'Int' cannot be converted to contextual type 'Float'}}
let _: KeyPath<R32101765, Float> = \R32101765.prop32101765
// expected-error@-1 {{KeyPath value type 'Int' cannot be converted to contextual type 'Float'}}
let _: KeyPath<R32101765, Float> = \.prop32101765.unknown
// expected-error@-1 {{type 'Int' has no member 'unknown'}}
let _: KeyPath<R32101765, Float> = \R32101765.prop32101765.unknown
// expected-error@-1 {{type 'Int' has no member 'unknown'}}
// rdar://problem/32390726 - Bad Diagnostic: Don't suggest `var` to `let` when binding inside for-statement
for var i in 0..<10 { // expected-warning {{variable 'i' was never mutated; consider changing to 'let' constant}} {{5-9=}}
_ = i + 1
}
// rdar://problem/32726044 - shrink reduced domains too far
public protocol P_32726044 {}
extension Int: P_32726044 {}
extension Float: P_32726044 {}
public func *(lhs: P_32726044, rhs: P_32726044) -> Double {
fatalError()
}
func rdar32726044() -> Float {
var f: Float = 0
f = Float(1) * 100 // Ok
let _: Float = Float(42) + 0 // Ok
return f
}
// SR-5045 - Attempting to return result of reduce(_:_:) in a method with no return produces ambiguous error
func sr5045() {
let doubles: [Double] = [1, 2, 3]
return doubles.reduce(0, +)
// expected-error@-1 {{unexpected non-void return value in void function}}
}
// rdar://problem/32934129 - QoI: misleading diagnostic
class L_32934129<T : Comparable> {
init(_ value: T) { self.value = value }
init(_ value: T, _ next: L_32934129<T>?) {
self.value = value
self.next = next
}
var value: T
var next: L_32934129<T>? = nil
func length() -> Int {
func inner(_ list: L_32934129<T>?, _ count: Int) {
guard let list = list else { return count } // expected-error {{unexpected non-void return value in void function}}
return inner(list.next, count + 1)
}
return inner(self, 0) // expected-error {{cannot convert return expression of type '()' to return type 'Int'}}
}
}
// rdar://problem/31671195 - QoI: erroneous diagnostic - cannot call value of non-function type
class C_31671195 {
var name: Int { fatalError() }
func name(_: Int) { fatalError() }
}
C_31671195().name(UInt(0))
// expected-error@-1 {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
// rdar://problem/28456467 - QoI: erroneous diagnostic - cannot call value of non-function type
class AST_28456467 {
var hasStateDef: Bool { return false }
}
protocol Expr_28456467 {}
class ListExpr_28456467 : AST_28456467, Expr_28456467 {
let elems: [Expr_28456467]
init(_ elems:[Expr_28456467] ) {
self.elems = elems
}
override var hasStateDef: Bool {
return elems.first(where: { $0.hasStateDef }) != nil
// expected-error@-1 {{value of type 'Expr_28456467' has no member 'hasStateDef'}}
}
}
// rdar://problem/31849281 - Let's play "bump the argument"
struct rdar31849281 { var foo, a, b, c: Int }
_ = rdar31849281(a: 101, b: 102, c: 103, foo: 104) // expected-error {{argument 'foo' must precede argument 'a'}} {{18-18=foo: 104, }} {{40-50=}}
_ = rdar31849281(a: 101, c: 103, b: 102, foo: 104) // expected-error {{argument 'foo' must precede argument 'a'}} {{18-18=foo: 104, }} {{40-50=}}
_ = rdar31849281(foo: 104, a: 101, c: 103, b: 102) // expected-error {{argument 'b' must precede argument 'c'}} {{36-36=b: 102, }} {{42-50=}}
_ = rdar31849281(b: 102, c: 103, a: 101, foo: 104) // expected-error {{argument 'foo' must precede argument 'b'}} {{18-18=foo: 104, }} {{40-50=}}
_ = rdar31849281(foo: 104, b: 102, c: 103, a: 101) // expected-error {{argument 'a' must precede argument 'b'}} {{28-28=a: 101, }} {{42-50=}}
func var_31849281(_ a: Int, _ b: Int..., c: Int) {}
var_31849281(1, c: 10, 3, 4, 5, 6, 7, 8, 9) // expected-error {{unnamed argument #3 must precede argument 'c'}} {{17-17=3, 4, 5, 6, 7, 8, 9, }} {{22-43=}}
func fun_31849281(a: (Bool) -> Bool, b: (Int) -> (String), c: [Int?]) {}
fun_31849281(c: [nil, 42], a: { !$0 }, b: { (num: Int) -> String in return "\(num)" })
// expected-error @-1 {{argument 'a' must precede argument 'c'}} {{14-14=a: { !$0 }, }} {{26-38=}}
fun_31849281(a: { !$0 }, c: [nil, 42], b: { (num: Int) -> String in return String(describing: num) })
// expected-error @-1 {{argument 'b' must precede argument 'c'}} {{26-26=b: { (num: Int) -> String in return String(describing: num) }, }} {{38-101=}}
fun_31849281(a: { !$0 }, c: [nil, 42], b: { "\($0)" })
// expected-error @-1 {{argument 'b' must precede argument 'c'}} {{26-26=b: { "\\($0)" }, }} {{38-54=}}
func f_31849281(x: Int, y: Int, z: Int) {}
f_31849281(42, y: 10, x: 20) // expected-error {{argument 'x' must precede unnamed argument #1}} {{12-12=x: 20, }} {{21-28=}}
| apache-2.0 | b158b42f30c1c00cdec47e141081325d | 44.120515 | 210 | 0.66717 | 3.550199 | false | false | false | false |
Zeitblick/Zeitblick-iOS | Zeitblick/ResultController.swift | 1 | 4749 | //
// ResultController.swift
// Zeitblick
//
// Created by Bastian Clausdorff on 30.10.16.
// Copyright © 2016 Zeitblick. All rights reserved.
//
import UIKit
import SwiftyJSON
import SnapKit
class ResultController: UIViewController {
private lazy var scroller: UIScrollView = {
let scroller = UIScrollView(frame: .zero)
scroller.delegate = self
return scroller
}()
lazy var resultView: UIImageView = {
let view = UIImageView(frame: .zero)
view.sizeToFit()
view.contentMode = .scaleAspectFill
return view
}()
private lazy var selfieView: UIImageView = {
let view = UIImageView()
view.layer.cornerRadius = 49
view.layer.borderWidth = 2
view.layer.borderColor = UIColor.white.cgColor
view.clipsToBounds = true
view.contentMode = .scaleAspectFill
return view
}()
private lazy var infoButton: UIButton = {
let button = UIButton(frame: .zero)
let image = R.image.button_info()
button.setImage(image, for: .normal)
return button
}()
private lazy var againButton: UIButton = {
let button = UIButton(frame: .zero)
let image = R.image.button_plus()
button.setImage(image, for: .normal)
return button
}()
var selfieImage: UIImage!
var resultImage: UIImage!
var metadata: ImageMetadata!
var errorHappened: Bool!
init(resultImage: UIImage, metadata: ImageMetadata, selfieImage: UIImage, errorHappened: Bool = false) {
super.init(nibName: nil, bundle: nil)
self.resultImage = resultImage
self.metadata = metadata
self.selfieImage = selfieImage
self.errorHappened = errorHappened
}
convenience init(resultImage: UIImage, errorHappened: Bool) {
self.init(resultImage: resultImage, metadata: ImageMetadata(), selfieImage: UIImage(), errorHappened: true)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
infoButton.addTarget(self, action: #selector(tappedInfo), for: .touchUpInside)
againButton.addTarget(self, action: #selector(tappedAgain), for: .touchUpInside)
resultView.image = resultImage
selfieView.image = selfieImage
scroller.delegate = self
scroller.minimumZoomScale = 1.0
scroller.maximumZoomScale = 3.0
view.addSubview(scroller)
scroller.addSubview(resultView)
scroller.snp.makeConstraints { make in
make.edges.equalTo(view)
}
view.addSubview(selfieView)
resultView.snp.makeConstraints { make in
make.edges.equalTo(scroller)
make.width.height.equalTo(view)
}
selfieView.snp.makeConstraints { make in
make.width.height.equalTo(100)
make.centerX.equalTo(view)
make.bottom.equalTo(view).inset(30)
}
view.addSubview(infoButton)
infoButton.snp.makeConstraints { make in
make.width.height.equalTo(50)
make.left.bottom.equalTo(view).inset(32)
}
view.addSubview(againButton)
againButton.snp.makeConstraints { make in
make.width.height.equalTo(50)
make.right.bottom.equalTo(view).inset(32)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIApplication.shared.setStatusBarHidden(true, with: .fade)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if errorHappened == true {
self.infoButton.isHidden = true
self.selfieView.isHidden = true
self.againButton.isHidden = true
Alerts.error(viewController: self) { [weak self] in
self?.tappedAgain()
}
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.shared.setStatusBarHidden(false, with: .fade)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Actions
func tappedInfo() {
let controller = InfoController(image: resultImage, metadata: metadata)
present(controller, animated: true, completion: nil)
}
func tappedAgain() {
dismiss(animated: true, completion: nil)
}
}
extension ResultController: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return resultView
}
}
| gpl-3.0 | df3d8ae29b21f8b8fcb27988838669a3 | 27.261905 | 115 | 0.634372 | 4.632195 | false | false | false | false |
HarukaMa/iina | iina/InspectorWindowController.swift | 1 | 9677 | //
// InspectorWindowController.swift
// iina
//
// Created by lhc on 21/12/2016.
// Copyright © 2016 lhc. All rights reserved.
//
import Cocoa
class InspectorWindowController: NSWindowController, NSTableViewDelegate, NSTableViewDataSource {
override var windowNibName: String {
return "InspectorWindowController"
}
var updateTimer: Timer?
var watchProperties: [String] = []
@IBOutlet weak var tabView: NSTabView!
@IBOutlet weak var trackPopup: NSPopUpButton!
@IBOutlet weak var pathField: NSTextField!
@IBOutlet weak var fileSizeField: NSTextField!
@IBOutlet weak var fileFormatField: NSTextField!
@IBOutlet weak var chaptersField: NSTextField!
@IBOutlet weak var editionsField: NSTextField!
@IBOutlet weak var durationField: NSTextField!
@IBOutlet weak var vformatField: NSTextField!
@IBOutlet weak var vcodecField: NSTextField!
@IBOutlet weak var vdecoderField: NSTextField!
@IBOutlet weak var voField: NSTextField!
@IBOutlet weak var vsizeField: NSTextField!
@IBOutlet weak var vbitrateField: NSTextField!
@IBOutlet weak var vfpsField: NSTextField!
@IBOutlet weak var aformatField: NSTextField!
@IBOutlet weak var acodecField: NSTextField!
@IBOutlet weak var aoField: NSTextField!
@IBOutlet weak var achannelsField: NSTextField!
@IBOutlet weak var abitrateField: NSTextField!
@IBOutlet weak var asamplerateField: NSTextField!
@IBOutlet weak var trackIdField: NSTextField!
@IBOutlet weak var trackDefaultField: NSTextField!
@IBOutlet weak var trackForcedField: NSTextField!
@IBOutlet weak var trackSelectedField: NSTextField!
@IBOutlet weak var trackExternalField: NSTextField!
@IBOutlet weak var trackSourceIdField: NSTextField!
@IBOutlet weak var trackTitleField: NSTextField!
@IBOutlet weak var trackLangField: NSTextField!
@IBOutlet weak var trackFilePathField: NSTextField!
@IBOutlet weak var trackCodecField: NSTextField!
@IBOutlet weak var trackDecoderField: NSTextField!
@IBOutlet weak var trackFPSField: NSTextField!
@IBOutlet weak var trackChannelsField: NSTextField!
@IBOutlet weak var trackSampleRateField: NSTextField!
@IBOutlet weak var avsyncField: NSTextField!
@IBOutlet weak var totalAvsyncField: NSTextField!
@IBOutlet weak var droppedFramesField: NSTextField!
@IBOutlet weak var mistimedFramesField: NSTextField!
@IBOutlet weak var displayFPSField: NSTextField!
@IBOutlet weak var voFPSField: NSTextField!
@IBOutlet weak var edispFPSField: NSTextField!
@IBOutlet weak var watchTableView: NSTableView!
override func windowDidLoad() {
super.windowDidLoad()
window?.appearance = NSAppearance(named: NSAppearanceNameVibrantDark)
watchProperties = UserDefaults.standard.array(forKey: Preference.Key.watchProperties) as! [String]
watchTableView.delegate = self
watchTableView.dataSource = self
updateInfo()
updateTimer = Timer.scheduledTimer(timeInterval: TimeInterval(1), target: self, selector: #selector(dynamicUpdate), userInfo: nil, repeats: true)
NotificationCenter.default.addObserver(self, selector: #selector(fileLoaded), name: Constants.Noti.fileLoaded, object: nil)
}
deinit {
ObjcUtils.silenced {
NotificationCenter.default.removeObserver(self)
}
}
func updateInfo(dynamic: Bool = false) {
let controller = PlayerCore.shared.mpvController
let info = PlayerCore.shared.info
if !dynamic {
// string properties
let strProperties: [String: NSTextField] = [
MPVProperty.path: pathField,
MPVProperty.fileFormat: fileFormatField,
MPVProperty.chapters: chaptersField,
MPVProperty.editions: editionsField,
MPVProperty.videoFormat: vformatField,
MPVProperty.videoCodec: vcodecField,
MPVProperty.hwdecCurrent: vdecoderField,
MPVProperty.containerFps: vfpsField,
MPVProperty.currentVo: voField,
MPVProperty.audioCodec: acodecField,
MPVProperty.currentAo: aoField,
MPVProperty.audioParamsFormat: aformatField,
MPVProperty.audioParamsChannels: achannelsField,
MPVProperty.audioBitrate: abitrateField,
MPVProperty.audioParamsSamplerate: asamplerateField
]
for (k, v) in strProperties {
let value = controller.getString(k)
v.stringValue = value ?? "N/A"
setLabelColor(v, by: value != nil)
}
// other properties
let duration = controller.getDouble(MPVProperty.duration)
durationField.stringValue = VideoTime(duration).stringRepresentation
let vwidth = controller.getInt(MPVProperty.width)
let vheight = controller.getInt(MPVProperty.height)
vsizeField.stringValue = "\(vwidth)\u{d7}\(vheight)"
let fileSize = controller.getInt(MPVProperty.fileSize)
fileSizeField.stringValue = FileSize.format(fileSize, unit: .b)
// track list
trackPopup.removeAllItems()
for track in info.videoTracks {
trackPopup.menu?.addItem(withTitle: "Video" + track.readableTitle,
action: nil, tag: nil, obj: track, stateOn: false)
}
trackPopup.menu?.addItem(NSMenuItem.separator())
for track in info.audioTracks {
trackPopup.menu?.addItem(withTitle: "Audio" + track.readableTitle,
action: nil, tag: nil, obj: track, stateOn: false)
}
trackPopup.menu?.addItem(NSMenuItem.separator())
for track in info.subTracks {
trackPopup.menu?.addItem(withTitle: "Sub" + track.readableTitle,
action: nil, tag: nil, obj: track, stateOn: false)
}
trackPopup.selectItem(at: 0)
updateTrack()
}
let vbitrate = controller.getInt(MPVProperty.videoBitrate)
vbitrateField.stringValue = FileSize.format(vbitrate, unit: .b) + "bps"
let abitrate = controller.getInt(MPVProperty.audioBitrate)
abitrateField.stringValue = FileSize.format(abitrate, unit: .b) + "bps"
let dynamicStrProperties: [String: NSTextField] = [
MPVProperty.avsync: avsyncField,
MPVProperty.totalAvsyncChange: totalAvsyncField,
MPVProperty.frameDropCount: droppedFramesField,
MPVProperty.mistimedFrameCount: mistimedFramesField,
MPVProperty.displayFps: displayFPSField,
MPVProperty.estimatedVfFps: voFPSField,
MPVProperty.estimatedDisplayFps: edispFPSField
]
for (k, v) in dynamicStrProperties {
let value = controller.getString(k)
v.stringValue = value ?? "N/A"
setLabelColor(v, by: value != nil)
}
}
func fileLoaded() {
updateInfo()
}
func dynamicUpdate() {
updateInfo(dynamic: true)
watchTableView.reloadData()
}
func updateTrack() {
guard let track = trackPopup.selectedItem?.representedObject as? MPVTrack else { return }
trackIdField.stringValue = "\(track.id)"
setLabelColor(trackDefaultField, by: track.isDefault)
setLabelColor(trackForcedField, by: track.isForced)
setLabelColor(trackSelectedField, by: track.isSelected)
setLabelColor(trackExternalField, by: track.isExternal)
let strProperties: [(String?, NSTextField)] = [
(track.srcId?.toStr(), trackSourceIdField),
(track.title, trackTitleField),
(track.lang, trackLangField),
(track.externalFilename, trackFilePathField),
(track.codec, trackCodecField),
(track.decoderDesc, trackDecoderField),
(track.demuxFps?.toStr(), trackFPSField),
(track.demuxChannels, trackChannelsField),
(track.demuxSamplerate?.toStr(), trackSampleRateField)
]
for (str, field) in strProperties {
field.stringValue = str ?? "N/A"
setLabelColor(field, by: str != nil)
}
}
// MARK: NSTableView
func numberOfRows(in tableView: NSTableView) -> Int {
return watchProperties.count
}
func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
guard let identifier = tableColumn?.identifier else { return nil }
guard let property = watchProperties.at(row) else { return nil }
if identifier == Constants.Identifier.key {
return property
} else if identifier == Constants.Identifier.value {
return PlayerCore.shared.mpvController.getString(property) ?? "<Error>"
}
return ""
}
func tableView(_ tableView: NSTableView, setObjectValue object: Any?, for tableColumn: NSTableColumn?, row: Int) {
guard let value = object as? String,
let identifier = tableColumn?.identifier else { return }
if identifier == Constants.Identifier.key {
watchProperties[row] = value
}
saveWatchList()
}
@IBAction func addWatchAction(_ sender: AnyObject) {
let _ = Utility.quickPromptPanel(messageText: "Add watch property", informativeText: "Please enter a valid MPV property name.") { str in
watchProperties.append(str)
watchTableView.reloadData()
saveWatchList()
}
}
@IBAction func removeWatchAction(_ sender: AnyObject) {
if watchTableView.selectedRow >= 0 {
watchProperties.remove(at: watchTableView.selectedRow)
watchTableView.reloadData()
}
saveWatchList()
}
// MARK: IBActions
@IBAction func tabSwitched(_ sender: NSSegmentedControl) {
tabView.selectTabViewItem(at: sender.selectedSegment)
}
@IBAction func trackSwitched(_ sender: AnyObject) {
updateTrack()
}
// MARK: Utils
private func setLabelColor(_ label: NSTextField, by state: Bool) {
label.textColor = state ? NSColor.textColor : NSColor.disabledControlTextColor
}
private func saveWatchList() {
UserDefaults.standard.set(watchProperties, forKey: Preference.Key.watchProperties)
}
}
| gpl-3.0 | 54891e671828e3166373a2ff90cc5399 | 33.190813 | 149 | 0.714138 | 4.339013 | false | false | false | false |
Azure-Samples/active-directory-ios | QuickStart/ViewController.swift | 1 | 14833 | //------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//------------------------------------------------------------------------------
import UIKit
import ADAL
/// 😃 A View Controller that will respond to the events of the Storyboard.
// Note that this is written to be one QuickStart file and meant to demonstrate basic concepts
// with easy to follow flow control and readable syntax. For a sample that demonstrates production
// quality Swift code check out the /Samples folder in the SDK repository.
class ViewController: UIViewController, UITextFieldDelegate, URLSessionDelegate {
// Update the below to your client ID you received in the portal. The below is for running the demo only
let kClientID = "227fe97b-c455-4039-b618-5af215c48d71"
// These settings you don't need to edit unless you wish to attempt deeper scenarios with the app.
let kGraphURI = "https://graph.microsoft.com"
let kAuthority = "https://login.microsoftonline.com/common"
let kRedirectUri = URL(string: "adal-sample-app://com.microsoft.identity.client.sample.quickstart")
let defaultSession = URLSession(configuration: .default)
var applicationContext : ADALAuthenticationContext?
var dataTask: URLSessionDataTask?
@IBOutlet weak var loggingText: UITextView!
@IBOutlet weak var signoutButton: UIButton!
override func viewDidLoad() {
/**
Initialize a ADAuthenticationContext with a given authority
- authority: A URL indicating a directory that ADAL can use to obtain tokens. In Azure AD
it is of the form https://<instance/<tenant>, where <instance> is the
directory host (e.g. https://login.microsoftonline.com) and <tenant> is a
identifier within the directory itself (e.g. a domain associated to the
tenant, such as contoso.onmicrosoft.com, or the GUID representing the
TenantID property of the directory)
- error The error that occurred creating the application object, if any, if you're
not interested in the specific error pass in nil.
*/
self.applicationContext = ADALAuthenticationContext(authority: kAuthority, error: nil)
self.applicationContext?.credentialsType = AD_CREDENTIALS_AUTO
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let currentAccount = currentAccount(),
currentAccount.accessToken != nil {
signoutButton.isEnabled = true
} else {
signoutButton.isEnabled = false
}
}
/**
This button will invoke the authorization flow.
*/
@IBAction func callGraphButton(_ sender: UIButton) {
self.callAPI()
}
func acquireToken(completion: @escaping (_ success: Bool) -> Void) {
guard let applicationContext = self.applicationContext else { return }
guard let kRedirectUri = kRedirectUri else { return }
/**
Acquire a token for an account
- withResource: The resource you wish to access. This will the Microsoft Graph API for this sample.
- clientId: The clientID of your application, you should get this from the app portal.
- redirectUri: The redirect URI that your application will listen for to get a response of the
Auth code after authentication. Since this a native application where authentication
happens inside the app itself, we can listen on a custom URI that the SDK knows to
look for from within the application process doing authentication.
- completionBlock: The completion block that will be called when the authentication
flow completes, or encounters an error.
*/
applicationContext.acquireToken(withResource: kGraphURI, clientId: kClientID, redirectUri: kRedirectUri){ (result) in
if (result.status != AD_SUCCEEDED) {
if let error = result.error {
if error.domain == ADAuthenticationErrorDomain,
error.code == ADALErrorCode.AD_ERROR_UNEXPECTED.rawValue {
self.updateLogging(text: "Unexpected internal error occured: \(error.description))");
} else {
self.updateLogging(text: error.description)
}
}
completion(false)
} else {
self.updateLogging(text: "Access token is \(String(describing: result.accessToken))")
self.updateSignoutButton(enabled: true)
completion(true)
}
}
}
func acquireTokenSilently(completion: @escaping (_ success: Bool) -> Void) {
guard let applicationContext = self.applicationContext else { return }
guard let kRedirectUri = kRedirectUri else { return }
/**
Acquire a token for an existing account silently
- withResource: The resource you wish to access. This will the Microsoft Graph API for this sample.
- clientId: The clientID of your application, you should get this from the app portal.
- redirectUri: The redirect URI that your application will listen for to get a response of the
Auth code after authentication. Since this a native application where authentication
happens inside the app itself, we can listen on a custom URI that the SDK knows to
look for from within the application process doing authentication.
- completionBlock: The completion block that will be called when the authentication
flow completes, or encounters an error.
*/
applicationContext.acquireTokenSilent(withResource: kGraphURI, clientId: kClientID, redirectUri: kRedirectUri) { (result) in
if (result.status != AD_SUCCEEDED) {
// USER_INPUT_NEEDED means we need to ask the user to sign-in. This usually happens
// when the user's Refresh Token is expired or if the user has changed their password
// among other possible reasons.
if let error = result.error {
if error.domain == ADAuthenticationErrorDomain,
error.code == ADALErrorCode.AD_ERROR_SERVER_USER_INPUT_NEEDED.rawValue {
DispatchQueue.main.async {
self.acquireToken() { (success) -> Void in
if success {
completion(true)
} else {
self.updateLogging(text: "After determining we needed user input, could not acquire token: \(error.description)")
completion(false)
}
}
}
} else {
self.updateLogging(text: "Could not acquire token silently: \(error.description)")
completion(false)
}
}
} else {
self.updateLogging(text: "Refreshed Access token is \(String(describing: result.accessToken))")
self.updateSignoutButton(enabled: true)
completion(true)
}
}
}
func currentAccount() -> ADALTokenCacheItem? {
// We retrieve our current account by getting the last account from cache. This isn't best practice. You should rely
// on AcquireTokenSilent and store the UPN separately in your application. For simplicity of the sample, we just use the cache.
// In multi-account applications, account should be retrieved by home account identifier or username instead
guard let cachedTokens = ADALKeychainTokenCache.defaultKeychain().allItems(nil) else {
self.updateLogging(text: "Didn't find a default cache. This is very unusual.")
return nil
}
if !(cachedTokens.isEmpty) {
// In the token cache, refresh tokens and access tokens are separate cache entries.
// Therefore, you need to keep looking until you find an entry with an access token.
for (_, cachedToken) in cachedTokens.enumerated() {
if cachedToken.accessToken != nil {
return cachedToken
}
}
}
return nil
}
func updateLogging(text : String) {
DispatchQueue.main.async {
self.loggingText.text += text + "\n\n"
let bottom = NSMakeRange(self.loggingText.text.count - 1, 1)
self.loggingText.scrollRangeToVisible(bottom)
}
}
func updateSignoutButton(enabled : Bool) {
DispatchQueue.main.async {
self.signoutButton.isEnabled = enabled
}
}
/**
This button will invoke the call to the Microsoft Graph API. It uses the
built in URLSession to create a connection.
*/
func callAPI(retry: Bool = true) {
// Specify the Graph API endpoint
let url = URL(string: kGraphURI + "/v1.0/me/")
var request = URLRequest(url: url!)
guard let accessToken = currentAccount()?.accessToken else {
// We haven't signed in yet, so let's do so now, then retry.
// To ensure we don't prompt the user twice,
// we set retry to false. If acquireToken() has some
// other issue we don't want an infinite loop.
if retry {
self.acquireToken() { (success) -> Void in
if success {
self.callAPI(retry: false)
}
}
} else {
self.updateLogging(text: "Couldn't get access token and we were told to not retry.")
}
return
}
// Set the Authorization header for the request. We use Bearer tokens, so we specify Bearer + the token we got from the result
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
dataTask = defaultSession.dataTask(with: request) { data, response, error in
if let error = error {
self.updateLogging(text: "Couldn't get graph result: \(error)")
}
guard let httpResponse = response as? HTTPURLResponse else {
self.updateLogging(text: "Couldn't get graph result")
return
}
// If we get HTTP 200: Success, go ahead and parse the JSON
if httpResponse.statusCode == 200 {
guard let result = try? JSONSerialization.jsonObject(with: data!, options: []) else {
self.updateLogging(text: "Couldn't deserialize result JSON")
return
}
self.updateLogging(text: "Result from Graph: \(result))")
}
// Sometimes the server API will throw HTTP 401: Unauthorized if it is expired or needs some
// other interaction from the authentication service. You should always refresh the
// token on first failure just to make sure that you cannot recover.
if httpResponse.statusCode == 401 {
if retry {
// We will try to refresh the token silently first. This way if there are any
// issues that can be resolved by getting a new access token from the refresh
// token, we avoid prompting the user. If user interaction is required, the
// acquireTokenSilently() will call acquireToken()
self.acquireTokenSilently() { (success) -> Void in
if success {
self.callAPI(retry: false)
}
}
} else {
self.updateLogging(text: "Couldn't access API with current access token, and we were told to not retry.")
}
}
}
dataTask?.resume()
}
/**
This button will invoke the signout APIs to clear the token cache.
*/
@IBAction func signoutButton(_ sender: UIButton) {
/**
Removes all tokens from the cache for this application for the current account in use
- account: The account user ID to remove from the cache
*/
guard let account = currentAccount()?.userInformation?.userId else {
self.updateLogging(text: "Didn't find a logged in account in the cache.")
return
}
ADALKeychainTokenCache.defaultKeychain().removeAll(forUserId: account, clientId: kClientID, error: nil)
self.signoutButton.isEnabled = false
self.updateLogging(text: "Removed account for: \(account)" )
}
}
| mit | d815922c5706ecb4432842499d80fd12 | 42.746313 | 149 | 0.581996 | 5.531518 | false | false | false | false |
zcLu/DanTangSwift | DanTangSwift/DanTangSwift/Classes/DanTang/Model/HomeListModel.swift | 1 | 849 | //
// HomeListModel.swift
// DanTangSwift
//
// Created by LuzhiChao on 2017/4/11.
// Copyright © 2017年 LuzhiChao. All rights reserved.
//
import UIKit
class HomeListModel: NSObject {
var cover_image_url: String?
var content_url: String?
var url: String?
var share_msg: String?
var title: String?
var short_title: String?
var liked: String?
var likes_count: Int?
init(dict: [String: AnyObject]) {
cover_image_url = dict["cover_image_url"] as? String
content_url = dict["content_url"] as? String
url = dict["url"] as? String
share_msg = dict["share_msg"] as? String
title = dict["title"] as? String
short_title = dict["short_title"] as? String
liked = dict["liked"] as? String
likes_count = dict["likes_count"] as? Int
}
}
| mit | 45aa6015d5ea0b8e2f39ace87e514723 | 25.4375 | 60 | 0.604019 | 3.467213 | false | false | false | false |
ello/ello-ios | Sources/Controllers/Stream/Cells/StreamTextCell.swift | 1 | 4379 | ////
/// StreamTextCell.swift
//
import WebKit
import SnapKit
class StreamTextCell: StreamRegionableCell, UIWebViewDelegate, UIGestureRecognizerDelegate {
static let reuseIdentifier = "StreamTextCell"
struct Size {
static let postMargin: CGFloat = 15
static let trailingMargin: CGFloat = 15
static let commentMargin: CGFloat = 60
static let repostMargin: CGFloat = 30
}
enum Margin {
case post
case comment
case repost
var value: CGFloat {
switch self {
case .post:
return Size.postMargin
case .comment:
return Size.commentMargin
case .repost:
return Size.repostMargin
}
}
}
typealias WebContentReady = (_ webView: UIWebView) -> Void
var webContentReady: WebContentReady?
var margin: Margin = .post {
didSet {
leadingConstraint.update(offset: margin.value)
}
}
var html: String = "" {
didSet {
if html != oldValue {
installWebView(ElloWebView())
let wrappedHtml = StreamTextCellHTML.postHTML(html)
webView.loadHTMLString(wrappedHtml, baseURL: URL(string: "/"))
}
}
}
private var webView = ElloWebView()
private var webViewContainer = Container()
private var leadingConstraint: Constraint!
private let doubleTapGesture = UITapGestureRecognizer()
private let longPressGesture = UILongPressGestureRecognizer()
func installWebView(_ webView: ElloWebView) {
self.webView.delegate = nil
self.webView.removeFromSuperview()
webView.delegate = self
webView.scrollView.isScrollEnabled = false
webView.scrollView.scrollsToTop = false
doubleTapGesture.delegate = self
doubleTapGesture.numberOfTapsRequired = 2
doubleTapGesture.addTarget(self, action: #selector(doubleTapped(_:)))
webView.addGestureRecognizer(doubleTapGesture)
longPressGesture.addTarget(self, action: #selector(longPressed(_:)))
webView.addGestureRecognizer(longPressGesture)
webViewContainer.addSubview(webView)
webView.snp.makeConstraints { make in
make.edges.equalTo(webViewContainer)
}
self.webView = webView
}
override func arrange() {
installWebView(webView)
contentView.addSubview(webViewContainer)
webViewContainer.snp.makeConstraints { make in
make.top.bottom.equalTo(contentView)
make.trailing.equalTo(contentView).offset(-Size.trailingMargin)
leadingConstraint = make.leading.equalTo(contentView).offset(Size.postMargin).constraint
}
}
func gestureRecognizer(
_: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith _: UIGestureRecognizer
) -> Bool {
return true
}
@IBAction func doubleTapped(_ gesture: UIGestureRecognizer) {
guard let appViewController:AppViewController = findResponder() else { return }
let location = gesture.location(in: appViewController.view)
let responder: StreamEditingResponder? = findResponder()
responder?.cellDoubleTapped(cell: self, location: location)
}
@IBAction func longPressed(_ gesture: UIGestureRecognizer) {
guard gesture.state == .began else { return }
let responder: StreamEditingResponder? = findResponder()
responder?.cellLongPressed(cell: self)
}
func onWebContentReady(_ handler: WebContentReady?) {
webContentReady = handler
}
override func prepareForReuse() {
super.prepareForReuse()
hideBorder()
webContentReady = nil
}
func webView(
_ webView: UIWebView,
shouldStartLoadWith request: URLRequest,
navigationType: UIWebView.NavigationType
) -> Bool {
if let scheme = request.url?.scheme, scheme == "default" {
let responder: StreamCellResponder? = findResponder()
responder?.streamCellTapped(cell: self)
return false
}
else {
return ElloWebViewHelper.handle(request: request, origin: self)
}
}
func webViewDidFinishLoad(_ webView: UIWebView) {
webContentReady?(webView)
}
}
| mit | 78eb0460ce42fab505e88296165f8349 | 29.409722 | 100 | 0.638274 | 5.466916 | false | false | false | false |
ello/ello-ios | Sources/Controllers/Profile/ProfileHeaderGhostCell.swift | 1 | 8788 | ////
/// ProfileHeaderGhostCell.swift
//
class ProfileHeaderGhostCell: CollectionViewCell {
static let reuseIdentifier = "ProfileHeaderGhostCell"
struct Size {
static let height: CGFloat = 460
static let sideMargin: CGFloat = 15
static let whiteTopMargin: CGFloat = 212
static let avatarTopMargin: CGFloat = 90
static let avatarSize: CGFloat = 180
static let ghostNameHeight: CGFloat = 20
static let ghostHeight: CGFloat = 10
static let nameTopMargin: CGFloat = 20
static let nameWidth: CGFloat = 135
static let nameBottomMargin: CGFloat = 15
static let totalCountTopMargin: CGFloat = 24
static let totalCountLeftWidth: CGFloat = 30
static let totalCountInnerMargin: CGFloat = 13
static let totalCountRightWidth: CGFloat = 60
static let totalCountBottomMargin: CGFloat = 24
static let statsTopMargin: CGFloat = 15
static let statsInnerMargin: CGFloat = 7
static let statsTopWidth: CGFloat = 30
static let statsBottomWidth: CGFloat = 60
static let statsBottomMargin: CGFloat = 28
}
private let whiteBackground = UIView()
private let avatar = UIView()
private let name = UIView()
private let nameGrayLine = UIView()
private let totalCountContainer = Container()
private let totalCountLeft = UIView()
private let totalCountRight = UIView()
private let totalCountGrayLine = UIView()
private let statsContainer = Container()
private let stat1Container = Container()
private let stat1Top = UIView()
private let stat1Bottom = UIView()
private let stat2Container = Container()
private let stat2Top = UIView()
private let stat2Bottom = UIView()
private let stat3Container = Container()
private let stat3Top = UIView()
private let stat3Bottom = UIView()
private let stat4Container = Container()
private let stat4Top = UIView()
private let stat4Bottom = UIView()
override func style() {
whiteBackground.backgroundColor = .white
let ghostsViews = [
avatar, name, totalCountLeft, totalCountRight, stat1Top, stat1Bottom, stat2Top,
stat2Bottom, stat3Top, stat3Bottom, stat4Top, stat4Bottom
]
for view in ghostsViews {
view.backgroundColor = .greyF2
}
avatar.layer.cornerRadius = Size.avatarSize / 2
let lines = [nameGrayLine, totalCountGrayLine]
for view in lines {
view.backgroundColor = .greyF2
}
}
override func arrange() {
contentView.addSubview(whiteBackground)
contentView.addSubview(avatar)
contentView.addSubview(name)
contentView.addSubview(nameGrayLine)
contentView.addSubview(totalCountContainer)
totalCountContainer.addSubview(totalCountLeft)
totalCountContainer.addSubview(totalCountRight)
contentView.addSubview(totalCountGrayLine)
contentView.addSubview(statsContainer)
statsContainer.addSubview(stat1Container)
stat1Container.addSubview(stat1Top)
stat1Container.addSubview(stat1Bottom)
statsContainer.addSubview(stat2Container)
stat2Container.addSubview(stat2Top)
stat2Container.addSubview(stat2Bottom)
statsContainer.addSubview(stat3Container)
stat3Container.addSubview(stat3Top)
stat3Container.addSubview(stat3Bottom)
statsContainer.addSubview(stat4Container)
stat4Container.addSubview(stat4Top)
stat4Container.addSubview(stat4Bottom)
whiteBackground.snp.makeConstraints { make in
make.top.equalTo(contentView).offset(Size.whiteTopMargin)
make.leading.trailing.bottom.equalTo(contentView)
}
avatar.snp.makeConstraints { make in
make.centerX.equalTo(contentView)
make.top.equalTo(contentView).offset(Size.avatarTopMargin)
make.width.height.equalTo(Size.avatarSize)
}
name.snp.makeConstraints { make in
make.centerX.equalTo(contentView)
make.top.equalTo(avatar.snp.bottom).offset(Size.nameTopMargin)
make.width.equalTo(Size.nameWidth)
make.height.equalTo(Size.ghostNameHeight)
}
nameGrayLine.snp.makeConstraints { make in
make.leading.trailing.equalTo(contentView).inset(Size.sideMargin)
make.top.equalTo(name.snp.bottom).offset(Size.nameBottomMargin)
make.height.equalTo(1)
}
totalCountContainer.snp.makeConstraints { make in
make.centerX.equalTo(contentView)
make.top.equalTo(nameGrayLine.snp.bottom).offset(Size.totalCountTopMargin)
make.leading.equalTo(totalCountLeft)
make.trailing.equalTo(totalCountRight)
make.height.equalTo(Size.ghostHeight)
}
totalCountLeft.snp.makeConstraints { make in
make.width.equalTo(Size.totalCountLeftWidth)
make.top.bottom.equalTo(totalCountContainer)
}
totalCountRight.snp.makeConstraints { make in
make.width.equalTo(Size.totalCountRightWidth)
make.leading.equalTo(totalCountLeft.snp.trailing).offset(Size.totalCountInnerMargin)
make.top.bottom.equalTo(totalCountContainer)
}
totalCountGrayLine.snp.makeConstraints { make in
make.leading.trailing.equalTo(contentView).inset(Size.sideMargin)
make.top.equalTo(totalCountContainer.snp.bottom).offset(Size.totalCountBottomMargin)
make.height.equalTo(1)
}
statsContainer.snp.makeConstraints { make in
make.leading.equalTo(contentView).offset(Size.sideMargin)
make.trailing.equalTo(contentView)
make.bottom.equalTo(contentView).offset(-Size.statsBottomMargin)
make.top.equalTo(totalCountGrayLine.snp.bottom).offset(Size.statsTopMargin)
}
stat1Container.snp.makeConstraints { make in
make.top.bottom.leading.equalTo(statsContainer)
make.width.equalTo(statsContainer).dividedBy(4)
}
stat1Top.snp.makeConstraints { make in
make.top.leading.equalTo(stat1Container)
make.width.equalTo(Size.statsTopWidth)
make.height.equalTo(Size.ghostHeight)
}
stat1Bottom.snp.makeConstraints { make in
make.top.equalTo(stat1Top.snp.bottom).offset(Size.statsInnerMargin)
make.leading.equalTo(stat1Container)
make.width.equalTo(Size.statsBottomWidth)
make.height.equalTo(Size.ghostHeight)
}
stat2Container.snp.makeConstraints { make in
make.top.bottom.width.equalTo(stat1Container)
make.leading.equalTo(stat1Container.snp.trailing)
}
stat2Top.snp.makeConstraints { make in
make.top.leading.equalTo(stat2Container)
make.width.equalTo(Size.statsTopWidth)
make.height.equalTo(Size.ghostHeight)
}
stat2Bottom.snp.makeConstraints { make in
make.top.equalTo(stat2Top.snp.bottom).offset(Size.statsInnerMargin)
make.leading.equalTo(stat2Container)
make.width.equalTo(Size.statsBottomWidth)
make.height.equalTo(Size.ghostHeight)
}
stat3Container.snp.makeConstraints { make in
make.leading.equalTo(stat2Container.snp.trailing)
make.top.bottom.width.equalTo(stat1Container)
}
stat3Top.snp.makeConstraints { make in
make.top.leading.equalTo(stat3Container)
make.width.equalTo(Size.statsTopWidth)
make.height.equalTo(Size.ghostHeight)
}
stat3Bottom.snp.makeConstraints { make in
make.top.equalTo(stat3Top.snp.bottom).offset(Size.statsInnerMargin)
make.leading.equalTo(stat3Container)
make.width.equalTo(Size.statsBottomWidth)
make.height.equalTo(Size.ghostHeight)
}
stat4Container.snp.makeConstraints { make in
make.trailing.equalTo(statsContainer)
make.leading.equalTo(stat3Container.snp.trailing)
make.top.bottom.width.equalTo(stat1Container)
}
stat4Top.snp.makeConstraints { make in
make.top.leading.equalTo(stat4Container)
make.width.equalTo(Size.statsTopWidth)
make.height.equalTo(Size.ghostHeight)
}
stat4Bottom.snp.makeConstraints { make in
make.top.equalTo(stat4Top.snp.bottom).offset(Size.statsInnerMargin)
make.leading.equalTo(stat4Container)
make.width.equalTo(Size.statsBottomWidth)
make.height.equalTo(Size.ghostHeight)
}
}
}
| mit | 8788d8e5e721d8a3a3b384dc8bfb9373 | 41.25 | 96 | 0.669322 | 4.525232 | false | false | false | false |
ask-fm/AFMActionSheet | Example/Tests/ActionSheetControllerSpec.swift | 1 | 10597 | // https://github.com/Quick/Quick
import Quick
import Nimble
import Nimble_Snapshots
@testable import AFMActionSheet
class ActionSheetControllerSpec: QuickSpec {
override func spec() {
describe("created action sheet controller") {
it("should have correct transition delegate, correct presentation style and controller style") {
let controller = AFMActionSheetController(transitioningDelegate: AFMActionSheetTransitioningDelegate())
expect(controller.transitioningDelegate).toNot(beNil())
expect(controller.modalPresentationStyle).to(equal(UIModalPresentationStyle.custom))
expect(controller.controllerStyle).to(equal(AFMActionSheetController.ControllerStyle.actionSheet))
}
it("should have gesture recognizers set up") {
let controller = AFMActionSheetController()
expect(controller.view.gestureRecognizers!.count).to(equal(2))
expect(controller.view.gestureRecognizers!.first as? UISwipeGestureRecognizer).toNot(beNil())
expect(controller.view.gestureRecognizers!.last as? UITapGestureRecognizer).toNot(beNil())
}
}
describe("basic controller setup") {
var controller: AFMActionSheetController!
var action : AFMAction!
beforeEach {
controller = MockActionSheetController()
action = AFMAction(title: "action", enabled: true, handler: nil)
}
it("should have correct number of actions and subviews when adding 1 action") {
controller.add(action)
expect(controller.actions.count).to(equal(1))
expect(controller.actionControls.count).to(equal(1))
expect(controller.actionGroupView.subviews.count).to(equal(1))
}
it("should have correct number of actions and subviews when adding 2 actions") {
controller.add(action)
controller.add(action)
expect(controller.actions.count).to(equal(2))
expect(controller.actionControls.count).to(equal(2))
expect(controller.actionGroupView.subviews.count).to(equal(2))
}
it("should have correct number of actions and subviews when inserting an action") {
controller.add(action)
controller.add(action)
let insertedControl = UIButton.control(with: action)
controller.insert(action, with: insertedControl, at: 0)
expect(controller.actions.count).to(equal(3))
expect(controller.actionControls.count).to(equal(3))
expect(controller.actionControls.first).to(equal(insertedControl))
expect(controller.actionGroupView.subviews.count).to(equal(3))
}
it("should have correct number of actions and subviews when inserting an action at wrong position") {
controller.add(action)
controller.add(action)
let insertedControl = UIButton.control(with: action)
controller.insert(action, with: insertedControl, at: 42)
expect(controller.actions.count).to(equal(2))
expect(controller.actionControls.count).to(equal(2))
expect(controller.actionControls.first).toNot(equal(insertedControl))
expect(controller.actionGroupView.subviews.count).to(equal(2))
}
it("should have correct number of subviews when adding title view") {
let titleView = UIView()
controller.add(title: titleView)
expect(controller.actionGroupView.subviews.count).to(equal(1))
}
it("should have label as title view view when adding title") {
controller.add(titleLabelWith: "title")
expect(controller.titleView as? UILabel).toNot(beNil())
expect((controller.titleView as! UILabel).text).to(equal("title"))
expect(controller.actionGroupView.subviews.count).to(equal(1))
}
it("should have control enabled if added action was enabled") {
action.enabled = true
controller.add(action)
expect(controller.actionControls.first?.isEnabled).to(beTrue())
}
it("should have control disabled if added action was disabled") {
action.enabled = false
controller.add(action)
expect(controller.actionControls.first?.isEnabled).to(beFalse())
}
it("should call correct action's handler when tapping on correspoding control") {
var calledAction1 = false
let action1 = AFMAction(title: "action1", enabled: true) { _ in
calledAction1 = true
}
var calledAction2 = false
let action2 = AFMAction(title: "action2", enabled: true) { _ in
calledAction2 = true
}
controller.add(action1)
controller.add(action2)
controller.handleTaps(controller.actionControls.first!)
expect(calledAction1).to(beTrue())
expect(calledAction2).to(beFalse())
}
it("should not call action's handler if action was disabled") {
var calledAction1 = false
let action1 = AFMAction(title: "action1", enabled: false) { _ in
calledAction1 = true
}
controller.add(action1)
controller.handleTaps(controller.actionControls.last!)
expect(calledAction1).to(beFalse())
}
}
describe("action sheet controller setup") {
var controller: AFMActionSheetController!
var action : AFMAction!
beforeEach {
controller = MockActionSheetController()
action = AFMAction(title: "action", enabled: true, handler: nil)
}
it("should have set up action and cancel group views correctly") {
expect(controller.actionGroupView.superview == controller.view).to(beTrue())
expect(controller.cancelGroupView.superview == controller.view).to(beTrue())
}
it("should have correct number of actions and subviews when adding 1 cancel action") {
controller.add(cancelling: action)
expect(controller.actions.count).to(equal(1))
expect(controller.cancelControls.count).to(equal(1))
expect(controller.cancelGroupView.subviews.count).to(equal(1))
}
it("should have correct number of actions and subviews when adding different actions") {
controller.add(action)
controller.add(cancelling: action)
controller.add(cancelling: action)
controller.add(action)
expect(controller.actions.count).to(equal(4))
expect(controller.actionControls.count).to(equal(2))
expect(controller.cancelControls.count).to(equal(2))
expect(controller.actionGroupView.subviews.count).to(equal(2))
expect(controller.cancelGroupView.subviews.count).to(equal(2))
}
}
describe("alert controller setup") {
var controller: AFMActionSheetController!
var action : AFMAction!
beforeEach {
controller = MockActionSheetController(style: .alert)
action = AFMAction(title: "action", enabled: true, handler: nil)
}
it("should have set up action and cancel group views correctly") {
expect(controller.actionGroupView.superview == controller.view).to(beTrue())
expect(controller.cancelGroupView.superview == nil).to(beTrue())
}
it("should have correct number of actions and subviews when adding 1 cancel action") {
controller.add(cancelling: action)
expect(controller.actions.count).to(equal(1))
expect(controller.cancelControls.count).to(equal(1))
expect(controller.cancelGroupView.subviews.count).to(equal(0))
}
it("should have correct number of actions and subviews when adding different actions") {
controller.add(action)
controller.add(cancelling: action)
controller.add(cancelling: action)
controller.add(action)
expect(controller.actions.count).to(equal(4))
expect(controller.actionControls.count).to(equal(2))
expect(controller.cancelControls.count).to(equal(2))
expect(controller.actionGroupView.subviews.count).to(equal(4))
expect(controller.cancelGroupView.subviews.count).to(equal(0))
}
}
describe("AFMActionSheetController", {
it("has valid snapshot for action sheet setup") {
let controller = AFMActionSheetController(style: .actionSheet, transitioningDelegate: AFMActionSheetTransitioningDelegate())
self.setup(controller: controller)
expect(controller.view).to(haveValidSnapshot(named: "AFMActionSheetController-ActionSheet-Snapshot"))
}
it("has valid snapshot for alert setup") {
let controller = AFMActionSheetController(style: .alert, transitioningDelegate: AFMActionSheetTransitioningDelegate())
self.setup(controller: controller)
expect(controller.view).to(haveValidSnapshot(named: "AFMActionSheetController-Alert-Snapshot"))
}
});
}
func setup(controller: AFMActionSheetController) {
let action1 = AFMAction(title: "Action 1", enabled: true, handler: nil)
let action2 = AFMAction(title: "Action 2", enabled: false, handler: nil)
let action3 = AFMAction(title: "Action 3", handler: nil)
controller.add(action1)
controller.add(action2)
controller.add(cancelling: action3)
controller.add(titleLabelWith: "Title")
}
class MockActionSheetController : AFMActionSheetController {
override func dismiss(animated flag: Bool, completion: (() -> Void)?) {
completion?()
}
}
}
| mit | 9a64df6e28eb151d6748b04008297ceb | 46.520179 | 140 | 0.602623 | 5.161715 | false | false | false | false |
PasDeChocolat/LearningSwift | PLAYGROUNDS/LSB_B021_FunctionalZippers.playground/section-2.swift | 2 | 5970 | import UIKit
/*
// Functional Zippers
//
// Based on:
// Learn You a Haskell for Great Good,
// Chapter 15, Zippers
// - by Miran Lipovača
/===================================*/
/*---------------------------------------------------------------------/
// Box, a hack
/---------------------------------------------------------------------*/
class Box<T> {
let unbox: T
init(_ value: T) { self.unbox = value }
}
/*---------------------------------------------------------------------/
// Tree
/---------------------------------------------------------------------*/
enum Tree<T> {
case Empty
case Node(Box<T>, Box<Tree<T>>, Box<Tree<T>>)
}
let empty: Tree<String> = Tree.Empty
let five: Tree<String> = Tree.Node(Box("five"), Box(empty), Box(empty))
// create a tree with a single value
func singleton<T>(x: T) -> Tree<T> {
return Tree.Node(Box(x), Box(Tree.Empty), Box(Tree.Empty))
}
func node<T>(x: T, l: Tree<T>, r: Tree<T>) -> Tree<T> {
return Tree.Node(Box(x), Box(l), Box(r))
}
let freeTree = node("P",
node("O",
node("L",
node("N", empty, empty),
node("T", empty, empty)),
node("Y",
node("S", empty, empty),
node("A", empty, empty))),
node("L",
node("W",
node("C", empty, empty),
node("R", empty, empty)),
node("A",
node("A", empty, empty),
node("C", empty, empty))))
/*---------------------------------------------------------------------/
// Breadcrumbs
/---------------------------------------------------------------------*/
enum Crumb<T> {
case Left(Box<T>, Tree<T>)
case Right(Box<T>, Tree<T>)
}
func goLeft<T>(zipper: (Tree<T>, [Crumb<T>])) -> (Tree<T>, [Crumb<T>])? {
let (t, crumbs) = zipper
switch t {
case .Empty:
return nil
case let .Node(x, l, r):
return (l.unbox, [Crumb.Left(x, r.unbox)] + crumbs)
}
}
func goRight<T>(zipper: (Tree<T>, [Crumb<T>])) -> (Tree<T>, [Crumb<T>])? {
let (t, crumbs) = zipper
switch t {
case .Empty:
return nil
case let .Node(x, l, r):
return (r.unbox, [Crumb.Right(x, l.unbox)] + crumbs)
}
}
/*---------------------------------------------------------------------/
// `decompose` is a helper for `goUp`
/---------------------------------------------------------------------*/
extension Array {
var decompose: (head: T, tail: [T])? {
return (count > 0) ? (self[0], Array(self[1..<count])) : nil
}
}
func goUp<T>(zipper: (Tree<T>, [Crumb<T>])) -> (Tree<T>, [Crumb<T>])? {
let (t, crumbs) = zipper
if let (c, bs) = crumbs.decompose {
switch c {
case let .Left(x, r):
return (node(x.unbox, t, r), bs)
case let .Right(x, l):
return (node(x.unbox, l, t), bs)
}
} else {
return nil
}
}
/*---------------------------------------------------------------------/
// elements
/---------------------------------------------------------------------*/
// list elements
func elements<T>(tree: Tree<T>) -> [T] {
switch tree {
case .Empty:
return []
case let .Node(x, left, right):
return elements(left.unbox) + [x.unbox] + elements(right.unbox)
}
}
elements(freeTree)
/*---------------------------------------------------------------------/
// modify
/---------------------------------------------------------------------*/
func modify<T>(f: T->T, zipper: (Tree<T>, [Crumb<T>])) -> (Tree<T>, [Crumb<T>]) {
let (t, crumbs) = zipper
switch t {
case .Empty:
return (Tree.Empty, crumbs)
case let .Node(x, l, r):
return (node(f(x.unbox), l.unbox, r.unbox), crumbs)
}
}
let freeZipper = (freeTree, [Crumb<String>]())
goRight(freeZipper)!
goLeft(freeZipper)!
let (leftTree, leftCrumbs) = goLeft(freeZipper)!
elements(leftTree)
leftCrumbs
goRight( goLeft(freeZipper)! )!
func makeP(x: String) -> String {
return "P"
}
let newFocus = modify(makeP, goRight(goLeft(freeZipper)!)!)
elements(newFocus.0)
/*---------------------------------------------------------------------/
// Allow modification to any letter
/---------------------------------------------------------------------*/
func makeLetter(letter: String) -> String -> String {
func makeX(_: String) -> String {
return letter
}
return makeX
}
let newFocus1 = modify(makeLetter("P"), goRight(goLeft(freeZipper)!)!)
elements(newFocus1.0)
let newFocus2 = modify(makeLetter("X"), goUp(newFocus1)!)
elements(newFocus2.0)
/*---------------------------------------------------------------------/
// attach
/---------------------------------------------------------------------*/
func attach<T>(t: Tree<T>, zipper: (Tree<T>, [Crumb<T>])) -> (Tree<T>, [Crumb<T>]) {
let (_, crumbs) = zipper
return (t, crumbs)
}
let farLeft = goLeft( goLeft( goLeft( goLeft( freeZipper )!)!)!)!
let newFocus3 = attach(node("Z", empty, empty), farLeft)
elements(newFocus3.0)
/*---------------------------------------------------------------------/
// topMost
/---------------------------------------------------------------------*/
func topMost<T>(zipper: (Tree<T>, [Crumb<T>])) -> (Tree<T>, [Crumb<T>]) {
let (t, crumbs) = zipper
if crumbs.isEmpty { return zipper }
return topMost(goUp( zipper )!)
}
let top = topMost(newFocus3)
elements(top.0)
/*---------------------------------------------------------------------/
// Optionals are monads!... use >>=
/---------------------------------------------------------------------*/
infix operator >>= { associativity left}
func >>=<U, T>(optional: T?, f: T -> U?) -> U? {
return optional.map { f($0)! }
}
func opt<T>(x: T) -> T? {
return x
}
let bindRight = opt(freeZipper) >>= goRight
elements(bindRight!.0)
let bindLeft = opt(freeZipper) >>= goLeft
elements(bindLeft!.0)
let bindLLLeft = opt(freeZipper) >>= goLeft >>= goLeft >>= goLeft
elements(bindLLLeft!.0)
| gpl-3.0 | 8d14b1ff58636675ec1d2c2ea0f2b087 | 24.728448 | 84 | 0.424024 | 3.652999 | false | false | false | false |
MikeCorpus/Part-Timr_Employer | Part-Timr/AuthProvider.swift | 1 | 3518 | //
// AuthProvider.swift
// Part-Timr for Employer
//
// Created by Michael V. Corpus on 04/02/2017.
// Copyright © 2017 Michael V. Corpus. All rights reserved.
//
import Foundation
import Firebase
typealias LoginHandler = (_ msg: String?) -> Void
struct LoginErrorCode {
static let WRONG_PASSWORD = "Wrong password, please try again."
static let INVALID_EMAIL = "Invalid email address, please provide a real email address."
static let USER_NOT_FOUND = "User not found, please register"
static let EMAIL_ALREADY_IN_USE = "Email already in use, please use another email"
static let WEAK_PASSWORD = "Password should be at least 6 characters long"
static let PROBLEM_CONNECTING = "Problem connecting to database"
}
class AuthProvider {
private static let _instance = AuthProvider()
static var Instance: AuthProvider{
return _instance
}
func login(withEmail: String, password: String, loginHandler: LoginHandler?) {
FIRAuth.auth()?.signIn(withEmail: withEmail, password: password, completion: { (user, error) in
if error != nil {
self.handleErrors(err: error as! NSError, loginHandler: loginHandler)
} else {
loginHandler?(nil)
}
})
}//login
func signUp(withEmail: String, password: String, loginHandler: LoginHandler?) {
FIRAuth.auth()?.createUser(withEmail: withEmail, password: password, completion: {(user, error) in
if error != nil {
self.handleErrors(err: error as! NSError, loginHandler: loginHandler)
} else {
if user?.uid != nil {
// store the user to database
DBProvider.Instance.saveUser(withID: user!.uid, email: withEmail, password: password)
// login in the user
self.login(withEmail: withEmail, password: password, loginHandler: loginHandler)
}
}
});
} // sign up function
func logOut() -> Bool {
if FIRAuth.auth()?.currentUser != nil {
do {
try FIRAuth.auth()?.signOut()
return true
} catch {
return false
}
}
return true
} // log out function
func handleErrors(err: NSError, loginHandler: LoginHandler?) {
if let errCode = FIRAuthErrorCode(rawValue: err.code) {
switch errCode {
case .errorCodeWrongPassword:
loginHandler?(LoginErrorCode.WRONG_PASSWORD)
break
case .errorCodeInvalidEmail:
loginHandler?(LoginErrorCode.INVALID_EMAIL)
break
case .errorCodeUserNotFound:
loginHandler?(LoginErrorCode.USER_NOT_FOUND)
break
case .errorCodeEmailAlreadyInUse:
loginHandler?(LoginErrorCode.EMAIL_ALREADY_IN_USE)
break
case .errorCodeWeakPassword:
loginHandler?(LoginErrorCode.WEAK_PASSWORD)
default:
loginHandler?(LoginErrorCode.PROBLEM_CONNECTING)
break
}
}
}
} //AuthProvider
| mit | dcc55aa3fe57e6593ba3aa672dcb553a | 30.401786 | 106 | 0.540802 | 5.21037 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.