repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
xiaoxionglaoshi/DNSwiftProject | DNSwiftProject/DNSwiftProject/Classes/Vendor/DNLaunchImage/DNLaunchImageAction.swift | 1 | 847 | //
// DNLaunchImageAction.swift
// DNSwiftProject
//
// Created by mainone on 16/12/16.
// Copyright © 2016年 wjn. All rights reserved.
//
import UIKit
class DNLaunchImageAction: UIImageView {
var target: AnyObject?
var action: Selector?
override init(frame: CGRect) {
super.init(frame: frame)
isUserInteractionEnabled = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addTarget(target: AnyObject, action: Selector) {
self.target = target
self.action = action
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if (self.target?.responds(to: self.action))! {
target?.perform(self.action!, with: self, afterDelay: 0.0)
}
}
}
| apache-2.0 |
hermantai/samples | ios/cs193p/EmojiArt/EmojiArt/EmojiArtApp.swift | 1 | 365 | //
// EmojiArtApp.swift
// EmojiArt
//
// Created by CS193p Instructor on 4/26/21.
// Copyright © 2021 Stanford University. All rights reserved.
//
import SwiftUI
@main
struct EmojiArtApp: App {
let document = EmojiArtDocument()
var body: some Scene {
WindowGroup {
EmojiArtDocumentView(document: document)
}
}
}
| apache-2.0 |
thanhcuong1990/swift-sample-code | SampleCode/Modules/Search/SearchViewController.swift | 1 | 668 | //
// SearchViewController.swift
// SampleCode
//
// Created by Cuong Lam on 11/9/15.
// Copyright © 2015 Cuong Lam. All rights reserved.
//
import UIKit
class SearchViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationItem.title = "Search"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
}
| unlicense |
diogot/MyWeight | MyWeight/Screens/List/EmptyListViewModel.swift | 2 | 894 | //
// EmptyListViewModel.swift
// MyWeight
//
// Created by Diogo on 18/10/16.
// Copyright © 2016 Diogo Tridapalli. All rights reserved.
//
import Foundation
public struct EmptyListViewModel: TitleDescriptionViewModelProtocol {
public let title: NSAttributedString
public let description: NSAttributedString
public let flexibleHeight: Bool
}
extension EmptyListViewModel {
public init() {
let style: StyleProvider = Style()
title = NSAttributedString(string: Localization.noDataTitle,
font: style.title1,
color: style.textColor)
description = NSAttributedString(string: Localization.noDataDescription,
font: style.body,
color: style.textLightColor)
flexibleHeight = true
}
}
| mit |
byu-oit-appdev/ios-byuSuite | byuSuite/Apps/JobOpenings/controller/JobOpeningsFamilyViewController.swift | 1 | 1371 | //
// JobOpeningsFamilyViewController.swift
// byuSuite
//
// Created by Alex Boswell on 2/16/18.
// Copyright © 2018 Brigham Young University. All rights reserved.
//
import UIKit
class JobOpeningsFamilyViewController: ByuTableDataViewController {
//MARK: Outlets
@IBOutlet private weak var spinner: UIActivityIndicatorView!
//MARK: Public Variables
var category: JobOpeningsCategory!
//MARK: View controller lifecycle
override func viewDidLoad() {
super.viewDidLoad()
title = category.siteDescription
loadPostings()
}
//MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showFamily",
let family: JobOpeningsFamily = objectForSender(tableView: tableView, cellSender: sender),
let vc = segue.destination as? JobOpeningsPostingsViewController {
vc.family = family
}
}
//MARK: Custom Methods
private func loadPostings() {
JobOpeningsClient.getJobPostings(categoryId: category.siteId) { (families, error) in
self.spinner.stopAnimating()
if let families = families {
self.tableData = TableData(rows: families.map { Row(text: $0.jobTitle, object: $0) })
self.tableView.reloadData()
} else {
super.displayAlert(error: error)
}
}
}
//MARK: TableData
override func getEmptyTableViewText() -> String {
return "No Job Openings"
}
}
| apache-2.0 |
TENDIGI/Obsidian-iOS-SDK | Obsidian-iOS-SDK/Debounce.swift | 1 | 550 | //
// Debounce.swift
// ObsidianSDK
//
// Created by Nick Lee on 7/17/15.
// Copyright (c) 2015 TENDIGI, LLC. All rights reserved.
//
import Foundation
internal func throttle(delay: NSTimeInterval, queue: dispatch_queue_t = dispatch_get_main_queue(), action: (() -> ())) -> () -> () {
var lastFire = NSDate.distantPast()
return {
let now = NSDate()
let delta = now.timeIntervalSinceDate(lastFire)
if delta > delay {
lastFire = now
action()
}
}
}
| mit |
iyepes/SFMobileFood | SFMobileFood/HCMFCartTableViewCell.swift | 1 | 641 | //
// HCMFCartTableViewCell.swift
// sfmobilefood
//
// Created by Isabel Yepes on 22/10/15.
// Copyright © 2015 Hacemos Contactos. All rights reserved.
//
import UIKit
class HCMFCartTableViewCell: UITableViewCell {
@IBOutlet weak var cartAddress: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
// line commented to avoid cell to be highligted when selected
//super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| apache-2.0 |
manavgabhawala/swift | test/SILGen/objc_currying.swift | 1 | 14665 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %build-silgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -new-mangling-for-tests -emit-silgen %s | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import gizmo
func curry_pod(_ x: CurryTest) -> (Int) -> Int {
return x.pod
}
// CHECK-LABEL: sil hidden @_T013objc_currying9curry_podS2icSo9CurryTestCF : $@convention(thin) (@owned CurryTest) -> @owned @callee_owned (Int) -> Int
// CHECK: bb0([[ARG1:%.*]] : $CurryTest):
// CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]]
// CHECK: [[THUNK:%.*]] = function_ref @[[THUNK_FOO_1:_T0So9CurryTestC3podS2iFTcTO]] : $@convention(thin) (@owned CurryTest) -> @owned @callee_owned (Int) -> Int
// CHECK: [[COPIED_ARG1:%.*]] = copy_value [[BORROWED_ARG1]]
// CHECK: [[FN:%.*]] = apply [[THUNK]]([[COPIED_ARG1]])
// CHECK: end_borrow [[BORROWED_ARG1]] from [[ARG1]]
// CHECK: destroy_value [[ARG1]]
// CHECK: return [[FN]]
// CHECK: } // end sil function '_T013objc_currying9curry_podS2icSo9CurryTestCF'
// CHECK: sil shared [thunk] @[[THUNK_FOO_1]] : $@convention(thin) (@owned CurryTest) -> @owned @callee_owned (Int) -> Int
// CHECK: [[THUNK:%.*]] = function_ref @[[THUNK_FOO_2:_T0So9CurryTestC3podS2iFTO]]
// CHECK: [[FN:%.*]] = partial_apply [[THUNK]](%0)
// CHECK: return [[FN]]
// CHECK: } // end sil function '[[THUNK_FOO_1]]'
// CHECK: sil shared [thunk] @[[THUNK_FOO_2]] : $@convention(method) (Int, @guaranteed CurryTest) -> Int
// CHECK: bb0([[ARG1:%.*]] : $Int, [[ARG2:%.*]] : $CurryTest):
// CHECK: [[COPIED_ARG2:%.*]] = copy_value [[ARG2]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[COPIED_ARG2]] : $CurryTest, #CurryTest.pod!1.foreign
// CHECK: [[RESULT:%.*]] = apply [[METHOD]]([[ARG1]], [[COPIED_ARG2]])
// CHECK: destroy_value [[COPIED_ARG2]]
// CHECK: return [[RESULT]]
// CHECK: } // end sil function '[[THUNK_FOO_2]]'
func curry_bridged(_ x: CurryTest) -> (String!) -> String! {
return x.bridged
}
// CHECK-LABEL: sil hidden @_T013objc_currying13curry_bridgedSQySSGACcSo9CurryTestCF : $@convention(thin) (@owned CurryTest) -> @owned @callee_owned (@owned Optional<String>) -> @owned Optional<String>
// CHECK: bb0([[ARG1:%.*]] : $CurryTest):
// CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]]
// CHECK: [[THUNK:%.*]] = function_ref @[[THUNK_BAR_1:_T0So9CurryTestC7bridgedSQySSGADFTcTO]]
// CHECK: [[ARG1_COPY:%.*]] = copy_value [[BORROWED_ARG1]]
// CHECK: [[FN:%.*]] = apply [[THUNK]]([[ARG1_COPY]])
// CHECK: end_borrow [[BORROWED_ARG1]] from [[ARG1]]
// CHECK: destroy_value [[ARG1]]
// CHECK: return [[FN]]
// CHECK: } // end sil function '_T013objc_currying13curry_bridgedSQySSGACcSo9CurryTestCF'
// CHECK: sil shared [thunk] @[[THUNK_BAR_1]] : $@convention(thin) (@owned CurryTest) -> @owned @callee_owned (@owned Optional<String>) -> @owned Optional<String>
// CHECK: bb0([[ARG1:%.*]] : $CurryTest):
// CHECK: [[THUNK:%.*]] = function_ref @[[THUNK_BAR_2:_T0So9CurryTestC7bridgedSQySSGADFTO]]
// CHECK: [[FN:%.*]] = partial_apply [[THUNK]]([[ARG1]])
// CHECK: return [[FN]]
// CHECK: } // end sil function '[[THUNK_BAR_1]]'
// CHECK: sil shared [thunk] @[[THUNK_BAR_2]] : $@convention(method) (@owned Optional<String>, @guaranteed CurryTest) -> @owned Optional<String>
// CHECK: bb0([[OPT_STRING:%.*]] : $Optional<String>, [[SELF:%.*]] : $CurryTest):
// CHECK: switch_enum [[OPT_STRING]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]],
//
// CHECK: [[SOME_BB]]([[STRING:%.*]] : $String):
// CHECK: [[BRIDGING_FUNC:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BORROWED_STRING:%.*]] = begin_borrow [[STRING]]
// CHECK: [[NSSTRING:%.*]] = apply [[BRIDGING_FUNC]]([[BORROWED_STRING]])
// CHECK: [[OPT_NSSTRING:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTRING]] : $NSString
// CHECK: end_borrow [[BORROWED_STRING]] from [[STRING]]
// CHECK: destroy_value [[STRING]]
// CHECK: br bb3([[OPT_NSSTRING]] : $Optional<NSString>)
// CHECK: bb2:
// CHECK: [[OPT_NONE:%.*]] = enum $Optional<NSString>, #Optional.none!enumelt
// CHECK: br bb3([[OPT_NONE]] : $Optional<NSString>)
// CHECK: bb3([[OPT_NSSTRING:%.*]] : $Optional<NSString>):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF_COPY]] : $CurryTest, #CurryTest.bridged!1.foreign
// CHECK: [[RESULT_OPT_NSSTRING:%.*]] = apply [[METHOD]]([[OPT_NSSTRING]], [[SELF_COPY]]) : $@convention(objc_method) (Optional<NSString>, CurryTest) -> @autoreleased Optional<NSString>
// CHECK: switch_enum [[RESULT_OPT_NSSTRING]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]],
// CHECK: [[SOME_BB]]([[RESULT_NSSTRING:%.*]] : $NSString):
// CHECK: [[BRIDGE_FUNC:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
// CHECK: [[REWRAP_RESULT_NSSTRING:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[RESULT_NSSTRING]]
// CHECK: [[RESULT_STRING:%.*]] = apply [[BRIDGE_FUNC]]([[REWRAP_RESULT_NSSTRING]]
// CHECK: [[WRAPPED_RESULT_STRING:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[RESULT_STRING]]
// CHECK: br bb6([[WRAPPED_RESULT_STRING]] : $Optional<String>)
// CHECK: bb5:
// CHECK: [[OPT_NONE:%.*]] = enum $Optional<String>, #Optional.none!enumelt
// CHECK: br bb6([[OPT_NONE]] : $Optional<String>)
// CHECK: bb6([[FINAL_RESULT:%.*]] : $Optional<String>):
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: destroy_value [[OPT_NSSTRING]]
// CHECK: return [[FINAL_RESULT]] : $Optional<String>
// CHECK: } // end sil function '[[THUNK_BAR_2]]'
func curry_returnsInnerPointer(_ x: CurryTest) -> () -> UnsafeMutableRawPointer! {
return x.returnsInnerPointer
}
// CHECK-LABEL: sil hidden @_T013objc_currying25curry_returnsInnerPointerSQySvGycSo9CurryTestCF : $@convention(thin) (@owned CurryTest) -> @owned @callee_owned () -> Optional<UnsafeMutableRawPointer> {
// CHECK: bb0([[SELF:%.*]] : $CurryTest):
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[THUNK:%.*]] = function_ref @[[THUNK_RETURNSINNERPOINTER:_T0So9CurryTestC19returnsInnerPointerSQySvGyFTcTO]]
// CHECK: [[SELF_COPY:%.*]] = copy_value [[BORROWED_SELF]]
// CHECK: [[FN:%.*]] = apply [[THUNK]]([[SELF_COPY]])
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
// CHECK: destroy_value [[SELF]]
// CHECK: return [[FN]]
// CHECK: } // end sil function '_T013objc_currying25curry_returnsInnerPointerSQySvGycSo9CurryTestCF'
// CHECK: sil shared [thunk] @[[THUNK_RETURNSINNERPOINTER]] : $@convention(thin) (@owned CurryTest) -> @owned @callee_owned () -> Optional<UnsafeMutableRawPointer>
// CHECK: [[THUNK:%.*]] = function_ref @[[THUNK_RETURNSINNERPOINTER_2:_T0So9CurryTestC19returnsInnerPointerSQySvGyFTO]]
// CHECK: [[FN:%.*]] = partial_apply [[THUNK]](%0)
// CHECK: return [[FN]]
// CHECK: } // end sil function '[[THUNK_RETURNSINNERPOINTER]]'
// CHECK: sil shared [thunk] @[[THUNK_RETURNSINNERPOINTER_2]] : $@convention(method) (@guaranteed CurryTest) -> Optional<UnsafeMutableRawPointer>
// CHECK: bb0([[ARG1:%.*]] : $CurryTest):
// CHECK: [[ARG1_COPY:%.*]] = copy_value [[ARG1]]
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[ARG1_COPY]] : $CurryTest, #CurryTest.returnsInnerPointer!1.foreign
// CHECK: [[RES:%.*]] = apply [[METHOD]]([[ARG1_COPY]]) : $@convention(objc_method) (CurryTest) -> @unowned_inner_pointer Optional<UnsafeMutableRawPointer>
// CHECK: autorelease_value
// CHECK: return [[RES]]
// CHECK: } // end sil function '[[THUNK_RETURNSINNERPOINTER_2]]'
// CHECK-LABEL: sil hidden @_T013objc_currying19curry_pod_AnyObjectS2ics0eF0_pF : $@convention(thin) (@owned AnyObject) -> @owned @callee_owned (Int) -> Int
// CHECK: bb0([[ANY:%.*]] : $AnyObject):
// CHECK: [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]]
// CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]]
// CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
// CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened({{.*}}) AnyObject, #CurryTest.pod!1.foreign, [[HAS_METHOD:bb[0-9]+]]
// CHECK: [[HAS_METHOD]]([[METHOD:%.*]] : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int):
// CHECK: [[OPENED_ANY_COPY_2:%.*]] = copy_value [[OPENED_ANY_COPY]]
// CHECK: partial_apply [[METHOD]]([[OPENED_ANY_COPY_2]])
// CHECK: } // end sil function '_T013objc_currying19curry_pod_AnyObjectS2ics0eF0_pF'
func curry_pod_AnyObject(_ x: AnyObject) -> (Int) -> Int {
return x.pod!
}
// normalOwnership requires a thunk to bring the method to Swift conventions
// CHECK-LABEL: sil hidden @_T013objc_currying31curry_normalOwnership_AnyObjectSQySo9CurryTestCGAEcs0fG0_pF : $@convention(thin) (@owned AnyObject) -> @owned @callee_owned (@owned Optional<CurryTest>) -> @owned Optional<CurryTest> {
// CHECK: bb0([[ANY:%.*]] : $AnyObject):
// CHECK: [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]]
// CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]]
// CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
// CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened({{.*}}) AnyObject, #CurryTest.normalOwnership!1.foreign, [[HAS_METHOD:bb[0-9]+]]
// CHECK: [[HAS_METHOD]]([[METHOD:%.*]] : $@convention(objc_method) (Optional<CurryTest>, @opened({{.*}}) AnyObject) -> @autoreleased Optional<CurryTest>):
// CHECK: [[OPENED_ANY_COPY_2:%.*]] = copy_value [[OPENED_ANY_COPY]]
// CHECK: [[PA:%.*]] = partial_apply [[METHOD]]([[OPENED_ANY_COPY_2]])
// CHECK: [[THUNK:%.*]] = function_ref @_T0So9CurryTestCSgACIxyo_A2CIxxo_TR
// CHECK: partial_apply [[THUNK]]([[PA]])
// CHECK: } // end sil function '_T013objc_currying31curry_normalOwnership_AnyObjectSQySo9CurryTestCGAEcs0fG0_pF'
func curry_normalOwnership_AnyObject(_ x: AnyObject) -> (CurryTest!) -> CurryTest! {
return x.normalOwnership!
}
// weirdOwnership is NS_RETURNS_RETAINED and NS_CONSUMES_SELF so already
// follows Swift conventions
// CHECK-LABEL: sil hidden @_T013objc_currying30curry_weirdOwnership_AnyObjectSQySo9CurryTestCGAEcs0fG0_pF : $@convention(thin) (@owned AnyObject) -> @owned @callee_owned (@owned Optional<CurryTest>) -> @owned Optional<CurryTest>
// CHECK: bb0([[ANY:%.*]] : $AnyObject):
// CHECK: [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]]
// CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]]
// CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
// CHECK: dynamic_method_br [[SELF:%.*]] : $@opened({{.*}}) AnyObject, #CurryTest.weirdOwnership!1.foreign, [[HAS_METHOD:bb[0-9]+]]
// CHECK: bb1([[METHOD:%.*]] : $@convention(objc_method) (@owned Optional<CurryTest>, @owned @opened({{.*}}) AnyObject) -> @owned Optional<CurryTest>):
// CHECK: [[OPENED_ANY_COPY_2:%.*]] = copy_value [[OPENED_ANY_COPY]]
// CHECK: partial_apply [[METHOD]]([[OPENED_ANY_COPY_2]])
// CHECK: } // end sil function '_T013objc_currying30curry_weirdOwnership_AnyObjectSQySo9CurryTestCGAEcs0fG0_pF'
func curry_weirdOwnership_AnyObject(_ x: AnyObject) -> (CurryTest!) -> CurryTest! {
return x.weirdOwnership!
}
// bridged requires a thunk to handle bridging conversions
// CHECK-LABEL: sil hidden @_T013objc_currying23curry_bridged_AnyObjectSQySSGACcs0eF0_pF : $@convention(thin) (@owned AnyObject) -> @owned @callee_owned (@owned Optional<String>) -> @owned Optional<String>
// CHECK: bb0([[ANY:%.*]] : $AnyObject):
// CHECK: [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]]
// CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]]
// CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
// CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened({{.*}}) AnyObject, #CurryTest.bridged!1.foreign, [[HAS_METHOD:bb[0-9]+]]
// CHECK: [[HAS_METHOD]]([[METHOD:%.*]] : $@convention(objc_method) (Optional<NSString>, @opened({{.*}}) AnyObject) -> @autoreleased Optional<NSString>):
// CHECK: [[OPENED_ANY_COPY_2:%.*]] = copy_value [[OPENED_ANY_COPY]]
// CHECK: [[PA:%.*]] = partial_apply [[METHOD]]([[OPENED_ANY_COPY_2]])
// CHECK: [[THUNK:%.*]] = function_ref @_T0So8NSStringCSgACIxyo_SSSgADIxxo_TR
// CHECK: partial_apply [[THUNK]]([[PA]])
// CHECK: } // end sil function '_T013objc_currying23curry_bridged_AnyObjectSQySSGACcs0eF0_pF'
func curry_bridged_AnyObject(_ x: AnyObject) -> (String!) -> String! {
return x.bridged!
}
// check that we substitute Self = AnyObject correctly for Self-returning
// methods
// CHECK-LABEL: sil hidden @_T013objc_currying27curry_returnsSelf_AnyObjectSQys0fG0_pGycsAC_pF : $@convention(thin) (@owned AnyObject) -> @owned @callee_owned () -> @owned Optional<AnyObject> {
// CHECK: bb0([[ANY:%.*]] : $AnyObject):
// CHECK: [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]]
// CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]]
// CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
// CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened({{.*}}) AnyObject, #CurryTest.returnsSelf!1.foreign, [[HAS_METHOD:bb[0-9]+]]
// CHECK: [[HAS_METHOD]]([[METHOD:%.*]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> @autoreleased Optional<AnyObject>):
// CHECK: [[OPENED_ANY_COPY_2:%.*]] = copy_value [[OPENED_ANY_COPY]]
// CHECK: [[PA:%.*]] = partial_apply [[METHOD]]([[OPENED_ANY_COPY_2]])
// CHECK: } // end sil function '_T013objc_currying27curry_returnsSelf_AnyObjectSQys0fG0_pGycsAC_pF'
func curry_returnsSelf_AnyObject(_ x: AnyObject) -> () -> AnyObject! {
return x.returnsSelf!
}
// CHECK-LABEL: sil hidden @_T013objc_currying35curry_returnsInnerPointer_AnyObjectSQySvGycs0gH0_pF : $@convention(thin) (@owned AnyObject) -> @owned @callee_owned () -> Optional<UnsafeMutableRawPointer> {
// CHECK: bb0([[ANY:%.*]] : $AnyObject):
// CHECK: [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]]
// CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]]
// CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
// CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened({{.*}}) AnyObject, #CurryTest.returnsInnerPointer!1.foreign, [[HAS_METHOD:bb[0-9]+]]
// CHECK: [[HAS_METHOD]]([[METHOD:%.*]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> @unowned_inner_pointer Optional<UnsafeMutableRawPointer>):
// CHECK: [[OPENED_ANY_COPY_2:%.*]] = copy_value [[OPENED_ANY_COPY]]
// CHECK: [[PA:%.*]] = partial_apply [[METHOD]]([[OPENED_ANY_COPY_2]])
// CHECK: } // end sil function '_T013objc_currying35curry_returnsInnerPointer_AnyObjectSQySvGycs0gH0_pF'
func curry_returnsInnerPointer_AnyObject(_ x: AnyObject) -> () -> UnsafeMutableRawPointer! {
return x.returnsInnerPointer!
}
| apache-2.0 |
zhuyunfeng1224/XiheMtxx | XiheMtxx/VC/EditImage/GridBorderView.swift | 1 | 2384 | //
// GridBorderView.swift
// XiheMtxx
//
// Created by echo on 2017/2/23.
// Copyright © 2017年 羲和. All rights reserved.
//
import UIKit
class GridBorderView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
context?.setStrokeColor(UIColor.white.cgColor)
let lineWidth: CGFloat = 1
context?.setLineWidth(lineWidth)
context?.beginPath()
let shadowOffset = CGSize(width: 1, height: 1)
context?.setShadow(offset: shadowOffset, blur: 2, color: UIColor.black.withAlphaComponent(0.3).cgColor)
// 横线
context?.move(to: CGPoint(x: rect.origin.x, y: rect.origin.y + lineWidth/2))
context?.addLine(to: CGPoint(x: rect.size.width, y: rect.origin.y + lineWidth/2))
context?.move(to: CGPoint(x: rect.origin.x, y: rect.size.height * 1 / 3))
context?.addLine(to: CGPoint(x: rect.size.width, y: rect.size.height * 1 / 3))
context?.move(to: CGPoint(x: rect.origin.x, y: rect.size.height * 2 / 3))
context?.addLine(to: CGPoint(x: rect.size.width, y: rect.size.height * 2 / 3))
context?.move(to: CGPoint(x: rect.origin.x, y: rect.size.height - lineWidth/2))
context?.addLine(to: CGPoint(x: rect.size.width, y: rect.size.height - lineWidth/2))
// 竖线
context?.move(to: CGPoint(x: rect.origin.x + lineWidth/2, y: rect.origin.y))
context?.addLine(to: CGPoint(x: rect.origin.x + lineWidth/2, y: rect.size.height))
context?.move(to: CGPoint(x: rect.size.width * 1 / 3, y: rect.origin.y))
context?.addLine(to: CGPoint(x: rect.size.width * 1 / 3, y: rect.size.height))
context?.move(to: CGPoint(x: rect.size.width * 2 / 3, y: rect.origin.y))
context?.addLine(to: CGPoint(x: rect.size.width * 2 / 3, y: rect.size.height))
context?.move(to: CGPoint(x: rect.size.width - lineWidth/2, y: rect.origin.y))
context?.addLine(to: CGPoint(x: rect.size.width - lineWidth/2, y: rect.size.height))
context?.strokePath()
}
}
| mit |
pyconjp/pyconjp-ios | PyConJP/Model/Enum/Room.swift | 1 | 1365 | //
// Room.swift
// PyConJP
//
// Created by Yutaro Muta on 8/7/16.
// Copyright © 2016 PyCon JP. All rights reserved.
//
import UIKit
enum Room: CustomStringConvertible {
case room201
case room202
case room203
static var rooms: [Room] {
return [.room201, .room202, .room203]
}
var description: String {
switch self {
case .room201: return "Room 201"
case .room202: return "Room 202"
case .room203: return "Room 203"
}
}
var number: Int {
switch self {
case .room201: return 201
case .room202: return 202
case .room203: return 203
}
}
var color: UIColor {
switch self {
case .room201: return UIColor.navy
case .room202: return UIColor.goldenrod
case .room203: return UIColor.crimson
}
}
var hashTag: String {
switch self {
case .room201: return "#pyconjp_201"
case .room202: return "#pyconjp_202"
case .room203: return "#pyconjp_203"
}
}
init?(_ string: String) {
switch string {
case Room.room201.description: self = .room201
case Room.room202.description: self = .room202
case Room.room203.description: self = .room203
default: return nil
}
}
}
| mit |
jsslai/Action | Carthage/Checkouts/RxSwift/Tests/PerformanceTests/PerformanceTools.swift | 3 | 6066 | //
// PerformanceTools.swift
// RxTests
//
// Created by Krunoslav Zaher on 9/27/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
var mallocFunctions: [(@convention(c) (UnsafeMutablePointer<_malloc_zone_t>?, Int) -> UnsafeMutableRawPointer?)] = []
var allocCalls: Int64 = 0
var bytesAllocated: Int64 = 0
func call0(_ p: UnsafeMutablePointer<_malloc_zone_t>?, size: Int) -> UnsafeMutableRawPointer? {
OSAtomicIncrement64(&allocCalls)
OSAtomicAdd64(Int64(size), &bytesAllocated)
#if ALLOC_HOOK
allocation()
#endif
return mallocFunctions[0](p, size)
}
func call1(_ p: UnsafeMutablePointer<_malloc_zone_t>?, size: Int) -> UnsafeMutableRawPointer? {
OSAtomicIncrement64(&allocCalls)
OSAtomicAdd64(Int64(size), &bytesAllocated)
#if ALLOC_HOOK
allocation()
#endif
return mallocFunctions[1](p, size)
}
func call2(_ p: UnsafeMutablePointer<_malloc_zone_t>?, size: Int) -> UnsafeMutableRawPointer? {
OSAtomicIncrement64(&allocCalls)
OSAtomicAdd64(Int64(size), &bytesAllocated)
#if ALLOC_HOOK
allocation()
#endif
return mallocFunctions[2](p, size)
}
var proxies: [(@convention(c) (UnsafeMutablePointer<_malloc_zone_t>?, Int) -> UnsafeMutableRawPointer?)] = [call0, call1, call2]
func getMemoryInfo() -> (bytes: Int64, allocations: Int64) {
return (bytesAllocated, allocCalls)
}
var registeredMallocHooks = false
func registerMallocHooks() {
if registeredMallocHooks {
return
}
registeredMallocHooks = true
var _zones: UnsafeMutablePointer<vm_address_t>?
var count: UInt32 = 0
// malloc_zone_print(nil, 1)
let res = malloc_get_all_zones(mach_task_self_, nil, &_zones, &count)
assert(res == 0)
_zones?.withMemoryRebound(to: UnsafeMutablePointer<malloc_zone_t>.self, capacity: Int(count), { zones in
assert(Int(count) <= proxies.count)
for i in 0 ..< Int(count) {
let zoneArray = zones.advanced(by: i)
let name = malloc_get_zone_name(zoneArray.pointee)
var zone = zoneArray.pointee.pointee
//print(String.fromCString(name))
assert(name != nil)
mallocFunctions.append(zone.malloc)
zone.malloc = proxies[i]
let protectSize = vm_size_t(MemoryLayout<malloc_zone_t>.size) * vm_size_t(count)
if true {
zoneArray.withMemoryRebound(to: vm_address_t.self, capacity: Int(protectSize), { addressPointer in
let res = vm_protect(mach_task_self_, addressPointer.pointee, protectSize, 0, PROT_READ | PROT_WRITE)
assert(res == 0)
})
}
zoneArray.pointee.pointee = zone
if true {
let res = vm_protect(mach_task_self_, _zones!.pointee, protectSize, 0, PROT_READ)
assert(res == 0)
}
}
})
}
// MARK: Benchmark tools
let NumberOfIterations = 10000
class A {
let _0 = 0
let _1 = 0
let _2 = 0
let _3 = 0
let _4 = 0
let _5 = 0
let _6 = 0
}
class B {
var a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]
}
let numberOfObjects = 1000000
let aliveAtTheEnd = numberOfObjects / 10
var objects: [AnyObject] = []
func fragmentMemory() {
objects = [AnyObject](repeating: A(), count: aliveAtTheEnd)
for _ in 0 ..< numberOfObjects {
objects[Int(arc4random_uniform(UInt32(aliveAtTheEnd)))] = arc4random_uniform(2) == 0 ? A() : B()
}
}
func approxValuePerIteration(_ total: Int) -> UInt64 {
return UInt64(round(Double(total) / Double(NumberOfIterations)))
}
func approxValuePerIteration(_ total: UInt64) -> UInt64 {
return UInt64(round(Double(total) / Double(NumberOfIterations)))
}
func measureTime(_ work: () -> ()) -> UInt64 {
var timebaseInfo: mach_timebase_info = mach_timebase_info()
let res = mach_timebase_info(&timebaseInfo)
assert(res == 0)
let start = mach_absolute_time()
for _ in 0 ..< NumberOfIterations {
work()
}
let timeInNano = (mach_absolute_time() - start) * UInt64(timebaseInfo.numer) / UInt64(timebaseInfo.denom)
return approxValuePerIteration(timeInNano) / 1000
}
func measureMemoryUsage(work: () -> ()) -> (bytesAllocated: UInt64, allocations: UInt64) {
let (bytes, allocations) = getMemoryInfo()
for _ in 0 ..< NumberOfIterations {
work()
}
let (bytesAfter, allocationsAfter) = getMemoryInfo()
return (approxValuePerIteration(bytesAfter - bytes), approxValuePerIteration(allocationsAfter - allocations))
}
var fragmentedMemory = false
func compareTwoImplementations(benchmarkTime: Bool, benchmarkMemory: Bool, first: () -> (), second: () -> ()) {
if !fragmentedMemory {
print("Fragmenting memory ...")
fragmentMemory()
print("Benchmarking ...")
fragmentedMemory = true
}
// first warm up to keep it fair
let time1: UInt64
let time2: UInt64
if benchmarkTime {
first()
second()
time1 = measureTime(first)
time2 = measureTime(second)
}
else {
time1 = 0
time2 = 0
}
let memory1: (bytesAllocated: UInt64, allocations: UInt64)
let memory2: (bytesAllocated: UInt64, allocations: UInt64)
if benchmarkMemory {
registerMallocHooks()
first()
second()
memory1 = measureMemoryUsage(work: first)
memory2 = measureMemoryUsage(work: second)
}
else {
memory1 = (0, 0)
memory2 = (0, 0)
}
// this is good enough
print(String(format: "#1 implementation %8d bytes %4d allocations %5d useconds", arguments: [
memory1.bytesAllocated,
memory1.allocations,
time1
]))
print(String(format: "#2 implementation %8d bytes %4d allocations %5d useconds", arguments: [
memory2.bytesAllocated,
memory2.allocations,
time2
]))
}
| mit |
AKIRA-MIYAKE/OpenWeatherMapper | OpenWeatherMapper/Requests/GetWeatherRequest.swift | 1 | 3343 | //
// GetCurrentWeatherRequest.swift
// OpenWeatherMapper
//
// Created by MiyakeAkira on 2015/10/26.
// Copyright © 2015年 Miyake Akira. All rights reserved.
//
import Foundation
import Result
import SwiftyJSON
public class GetWeatherRequest: Request {
// MARK: - Typealias
public typealias Entity = Weather
// MARK: - Variables
public private (set) var method: String = "GET"
public private (set) var path: String = "/data/2.5/weather"
public var parameters: [String: AnyObject]
// MARK: - Initialize
public init(cityName: String) {
self.parameters = ["q": cityName]
}
public init(cityName: String, countryCode: String) {
self.parameters = ["q": "\(cityName),\(countryCode)"]
}
public init(cityId: Int) {
self.parameters = ["id": cityId]
}
public init(_ coordinate: Coordinate) {
self.parameters = ["lat": coordinate.latitude, "lon": coordinate.longitude]
}
// MARK: - Method
public func parse(data: AnyObject) -> Entity? {
let json = JSON(data)
let date: NSDate?
if let dt = json["dt"].double {
date = NSDate(timeIntervalSince1970: dt)
} else {
date = nil
}
let coordinate: Coordinate?
if let lat = json["coord"]["lat"].double, let lon = json["coord"]["lon"].double {
coordinate = Coordinate(latitude: lat, longitude: lon)
} else {
coordinate = nil
}
let city: City?
if let id = json["id"].int,
let name = json["name"].string,
let country = json["sys"]["country"].string
{
city = City(id: id, name: name, country: country)
} else {
city = nil
}
let temperatureMax: Temperature?
if let tempMax = json["main"]["temp_max"].double {
temperatureMax = Temperature(tempMax, degree: .Kelvin)
} else {
temperatureMax = nil
}
let temperatureMin: Temperature?
if let tempMin = json["main"]["temp_max"].double {
temperatureMin = Temperature(tempMin, degree: .Kelvin)
} else {
temperatureMin = nil
}
let temperatures: Temperatures?
if let max = temperatureMax, let min = temperatureMin {
temperatures = Temperatures(maximum: max, minimum: min)
} else {
temperatures = nil
}
let conditon: Condition?
if let id = json["weather"][0]["id"].int,
let description = json["weather"][0]["description"].string {
conditon = Condition(id: id, description: description)
} else {
conditon = nil
}
let weather: Weather?
if let condition = conditon, let temperatures = temperatures, let city = city, let coordinate = coordinate, let date = date {
weather = Weather(condition: condition, temperatures: temperatures, city: city, coordinate: coordinate, date: date)
} else {
weather = nil
}
return weather
}
}
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/02599-resolvetypedecl.swift | 11 | 222 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let v: A? {
struct c<T where f: Int -> <b
for b in c
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/04533-swift-parser-skipsingle.swift | 11 | 320 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class a<T : e
{
static let a {
case c,
{
class
case c,
{
(([Void{
protocol a {
(((e : e
let h = [Void{
struct B<T>: A {
([Void{
() as a<I : b { func c
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/20991-swift-sourcemanager-getmessage.swift | 11 | 244 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
init( ) {
case
var {
return ( ) {
if true {
var d {
class B {
class
case ,
| mit |
debugsquad/nubecero | nubecero/Model/OnboardForm/MOnboardFormItemPasswordRegister.swift | 1 | 324 | import UIKit
class MOnboardFormItemPasswordRegister:MOnboardFormItemPassword
{
override init()
{
super.init(password:nil)
}
override init(reusableIdentifier:String, cellHeight:CGFloat)
{
fatalError()
}
override init(password:String?)
{
fatalError()
}
}
| mit |
kuznetsovVladislav/KVSpinnerView | SwiftExample/ViewController.swift | 1 | 3830 | //
// ViewController.swift
// Example Project
//
// Created by Владислав on 01.02.17.
// Copyright © 2017 Vladislav. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
enum CellType {
case standart
case withStatus
case onView
case onViewWithStatus
case delayedDismiss
case imageProgress
}
var cells:[CellType] = [.standart, .withStatus,
.onView, .onViewWithStatus,
.delayedDismiss, .imageProgress]
let networkManager = NetworkManager()
override func viewDidLoad() {
super.viewDidLoad()
setupViewController()
addStopBarItem()
}
fileprivate func setupViewController() {
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 60
KVSpinnerView.settings.animationStyle = .standart
}
fileprivate func addStopBarItem() {
let settingsItem = UIBarButtonItem(title: "Stop",
style: .plain,
target: self,
action: #selector(stopAction(sender:)))
navigationItem.rightBarButtonItem = settingsItem
}
fileprivate func downloadHugeImage() {
KVSpinnerView.showProgress(saying: "Image loading")
networkManager.progressHandler = { progress in
KVSpinnerView.handle(progress: progress)
}
networkManager.downloadCompletion = { image in
KVSpinnerView.dismiss()
}
networkManager.downloadImage()
}
func stopAction(sender: Any) {
KVSpinnerView.dismiss()
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellID", for: indexPath) as! TableViewCell
switch cells[indexPath.row] {
case .standart:
cell.titleLabel.text = "Standart Animation with long text"
case .withStatus:
cell.titleLabel.text = "Standart Animation with status"
case .onView:
cell.titleLabel.text = "Standart Animation on view"
case .onViewWithStatus:
cell.titleLabel.text = "Standart Animation on view with status"
case .delayedDismiss:
cell.titleLabel.text = "Delayed Dismiss"
case .imageProgress:
cell.titleLabel.text = "Load huge image"
}
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cells.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
}
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch cells[indexPath.row] {
case .standart:
KVSpinnerView.settings.animationStyle = .standart
KVSpinnerView.show()
case .withStatus:
KVSpinnerView.settings.animationStyle = .infinite
KVSpinnerView.show(saying: "Infinite Animation with extremely ultimate fantastic long text")
case .onView:
KVSpinnerView.show(on: self.view)
case .onViewWithStatus:
KVSpinnerView.show(on: self.view, saying: "Shown on view")
case .delayedDismiss:
KVSpinnerView.show()
KVSpinnerView.dismiss(after: 2.0)
case .imageProgress:
downloadHugeImage()
}
}
}
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/25839-swift-iterabledeclcontext-getmembers.swift | 7 | 235 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func a<class a=enum B{class A{enum S{func e:AnyObject}}}class A:a
| mit |
IFTTT/RazzleDazzle | Source/HideAnimation.swift | 1 | 785 | //
// HideAnimation.swift
// RazzleDazzle
//
// Created by Laura Skelton on 6/27/15.
// Copyright © 2015 IFTTT. All rights reserved.
//
import UIKit
/**
Animates the `hidden` property of a `UIView`.
*/
public class HideAnimation : Animatable {
private let filmstrip = Filmstrip<Bool>()
private let view : UIView
public init(view: UIView, hideAt: CGFloat) {
self.view = view
filmstrip[hideAt] = false
filmstrip[hideAt + 0.00001] = true
}
public init(view: UIView, showAt: CGFloat) {
self.view = view
filmstrip[showAt] = true
filmstrip[showAt + 0.00001] = false
}
public func animate(_ time: CGFloat) {
if filmstrip.isEmpty {return}
view.isHidden = filmstrip[time]
}
}
| mit |
teambox/RealmResultsController | Example/RealmResultsController-iOSTests/RealmObjectSpec.swift | 2 | 6125 | //
// RealmObjectSpec.swift
// RealmResultsController
//
// Created by Pol Quintana on 22/9/15.
// Copyright © 2015 Redbooth. All rights reserved.
//
import Foundation
import Quick
import Nimble
import RealmSwift
@testable import RealmResultsController
class NotificationListener2 {
static let sharedInstance = NotificationListener2()
var notificationReceived: Bool = false
@objc func notificationReceived(_ notification: Foundation.Notification) {
notificationReceived = true
}
}
class RealmObjectSpec: QuickSpec {
override func spec() {
var realm: Realm!
beforeSuite {
RealmTestHelper.loadRealm()
realm = try! Realm()
}
describe("notifyChange()") {
afterEach {
NotificationCenter.default.removeObserver(NotificationListener2.sharedInstance)
NotificationListener2.sharedInstance.notificationReceived = false
}
context("With valid realm") {
let id = 22222222222222
beforeEach {
let user = Task()
try! realm.write {
user.id = id
user.name = "old name"
realm.addNotified(user, update: true)
}
NotificationCenter.default.addObserver(NotificationListener2.sharedInstance,
selector: #selector(NotificationListener2.notificationReceived(_:)),
name: user.objectIdentifier().map { NSNotification.Name(rawValue: $0) },
object: nil)
try! realm.write {
user.name = "new name"
user.notifyChange() //Notifies that there's a change on the object
}
}
afterEach {
try! realm.write {
let tasks = realm.objects(Task.self).toArray().filter { $0.id == id }
realm.delete(tasks.first!)
}
}
it("Should have received a notification for the change") {
expect(NotificationListener2.sharedInstance.notificationReceived).to(beTruthy())
}
}
context("With invalid realm") {
beforeEach {
let user = Task()
NotificationCenter.default.addObserver(NotificationListener2.sharedInstance,
selector: #selector(NotificationListener2.notificationReceived(_:)),
name: user.objectIdentifier().map { NSNotification.Name(rawValue: $0) },
object: nil)
user.name = "new name"
user.notifyChange() //Notifies that there's a change on the object
}
it("Should NOT have received a notification for the change") {
expect(NotificationListener2.sharedInstance.notificationReceived).to(beFalsy())
}
}
}
describe("primaryKeyValue()") {
var value: Any?
context("if the object does not have primary key") {
beforeEach {
let dummy = Dummy()
value = dummy.primaryKeyValue()
}
it("should be nil") {
expect(value).to(beNil())
}
}
context("if the object have primary key") {
beforeEach {
let dummy = Task()
value = dummy.primaryKeyValue()
}
it("should be 0") {
expect(value as? Int) == 0
}
}
}
describe("hasSamePrimaryKeyValue(object:)") {
var value: Bool!
context("if both object don't have primary key") {
beforeEach {
let dummy1 = Dummy()
let dummy2 = Dummy()
value = dummy1.hasSamePrimaryKeyValue(as: dummy2)
}
it("should return false") {
expect(value).to(beFalsy())
}
}
context("if passed object does not have primary key") {
beforeEach {
let dummy1 = Task()
let dummy2 = Dummy()
value = dummy1.hasSamePrimaryKeyValue(as: dummy2)
}
it("should return false") {
expect(value).to(beFalsy())
}
}
context("if only the instance object does not have primary key") {
beforeEach {
let dummy1 = Dummy()
let dummy2 = Task()
value = dummy1.hasSamePrimaryKeyValue(as: dummy2)
}
it("should return false") {
expect(value).to(beFalsy())
}
}
context("if both objects have primary key") {
context("when the primary keys match") {
beforeEach {
let dummy1 = Task()
let dummy2 = Task()
value = dummy1.hasSamePrimaryKeyValue(as: dummy2)
}
it("should return true") {
expect(value).to(beTruthy())
}
}
context("when primary keys do not match") {
beforeEach {
let dummy1 = Task()
let dummy2 = Task()
dummy2.id = 2
value = dummy1.hasSamePrimaryKeyValue(as: dummy2)
}
it("should return false") {
expect(value).to(beFalsy())
}
}
}
}
}
}
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/07833-swift-constraints-constraintgraph-gatherconstraints.swift | 11 | 222 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
[ ]
}
class A {
protocol c : b {
enum b : b
func b
| mit |
twostraws/HackingWithSwift | Classic/project6b/Project6b/ViewController.swift | 1 | 2195 | //
// ViewController.swift
// Project6b
//
// Created by TwoStraws on 15/08/2016.
// Copyright © 2016 Paul Hudson. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let label1 = UILabel()
label1.translatesAutoresizingMaskIntoConstraints = false
label1.backgroundColor = UIColor.red
label1.text = "THESE"
let label2 = UILabel()
label2.translatesAutoresizingMaskIntoConstraints = false
label2.backgroundColor = UIColor.cyan
label2.text = "ARE"
let label3 = UILabel()
label3.translatesAutoresizingMaskIntoConstraints = false
label3.backgroundColor = UIColor.yellow
label3.text = "SOME"
let label4 = UILabel()
label4.translatesAutoresizingMaskIntoConstraints = false
label4.backgroundColor = UIColor.green
label4.text = "AWESOME"
let label5 = UILabel()
label5.translatesAutoresizingMaskIntoConstraints = false
label5.backgroundColor = UIColor.orange
label5.text = "LABELS"
view.addSubview(label1)
view.addSubview(label2)
view.addSubview(label3)
view.addSubview(label4)
view.addSubview(label5)
// let viewsDictionary = ["label1": label1, "label2": label2, "label3": label3, "label4": label4, "label5": label5]
// for label in viewsDictionary.keys {
// view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[\(label)]|", options: [], metrics: nil, views: viewsDictionary))
// }
// let metrics = ["labelHeight": 88]
// view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat:"V:|[label1(labelHeight@999)]-[label2(label1)]-[label3(label1)]-[label4(label1)]-[label5(label1)]->=10-|", options: [], metrics: metrics, views: viewsDictionary))
var previous: UILabel?
for label in [label1, label2, label3, label4, label5] {
label.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
label.heightAnchor.constraint(equalToConstant: 88).isActive = true
if let previous = previous {
label.topAnchor.constraint(equalTo: previous.bottomAnchor, constant: 10).isActive = true
}
previous = label
}
}
override var prefersStatusBarHidden: Bool {
return true
}
}
| unlicense |
WestlakeAPC/game-off-2016 | external/Fiber2D/Fiber2D/PhysicsBody+Joints.swift | 1 | 272 | //
// PhysicsBody+Joints.swift
// Fiber2D
//
// Created by Andrey Volodin on 20.09.16.
// Copyright © 2016 s1ddok. All rights reserved.
//
public extension PhysicsBody {
internal func remove(joint: PhysicsJoint) {
joints.removeObject(joint)
}
}
| apache-2.0 |
Redshift-Dev-Group/Pluto | Pluto-tutorial1/Pluto-tutorial1/AppDelegate.swift | 1 | 2185 | //
// AppDelegate.swift
// Pluto-tutorial1
//
// Created by Jeremy Vatter on 8/14/14.
// Copyright (c) 2014 Redshift Dev Group. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> 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:.
}
}
| mit |
SuPair/firefox-ios | StorageTests/TestSQLiteHistory.swift | 1 | 71540 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
@testable import Storage
import Deferred
import XCTest
class BaseHistoricalBrowserSchema: Schema {
var name: String { return "BROWSER" }
var version: Int { return -1 }
func update(_ db: SQLiteDBConnection, from: Int) -> Bool {
fatalError("Should never be called.")
}
func create(_ db: SQLiteDBConnection) -> Bool {
return false
}
func drop(_ db: SQLiteDBConnection) -> Bool {
return false
}
var supportsPartialIndices: Bool {
let v = sqlite3_libversion_number()
return v >= 3008000 // 3.8.0.
}
let oldFaviconsSQL = """
CREATE TABLE IF NOT EXISTS favicons (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL UNIQUE,
width INTEGER,
height INTEGER,
type INTEGER NOT NULL,
date REAL NOT NULL
)
"""
func run(_ db: SQLiteDBConnection, sql: String?, args: Args? = nil) -> Bool {
if let sql = sql {
do {
try db.executeChange(sql, withArgs: args)
} catch {
return false
}
}
return true
}
func run(_ db: SQLiteDBConnection, queries: [String?]) -> Bool {
for sql in queries {
if let sql = sql {
if !run(db, sql: sql) {
return false
}
}
}
return true
}
func run(_ db: SQLiteDBConnection, queries: [String]) -> Bool {
for sql in queries {
if !run(db, sql: sql) {
return false
}
}
return true
}
}
// Versions of BrowserSchema that we care about:
// v6, prior to 001c73ea1903c238be1340950770879b40c41732, July 2015.
// This is when we first started caring about database versions.
//
// v7, 81e22fa6f7446e27526a5a9e8f4623df159936c3. History tiles.
//
// v8, 02c08ddc6d805d853bbe053884725dc971ef37d7. Favicons.
//
// v10, 4428c7d181ff4779ab1efb39e857e41bdbf4de67. Mirroring. We skipped v9.
//
// These tests snapshot the table creation code at each of these points.
class BrowserSchemaV6: BaseHistoricalBrowserSchema {
override var version: Int { return 6 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql = """
INSERT INTO bookmarks
(id, guid, type, url, title, parent)
VALUES
-- Root
(?, ?, ?, NULL, ?, ?),
-- Mobile
(?, ?, ?, NULL, ?, ?),
-- Menu
(?, ?, ?, NULL, ?, ?),
-- Toolbar
(?, ?, ?, NULL, ?, ?),
-- Unsorted
(?, ?, ?, NULL, ?, ?)
"""
return self.run(db, sql: sql, args: args)
}
func CreateHistoryTable() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
-- Not null, but the value might be replaced by the server's.
guid TEXT NOT NULL UNIQUE,
-- May only be null for deleted records.
url TEXT UNIQUE,
title TEXT NOT NULL,
-- Can be null. Integer milliseconds.
server_modified INTEGER,
-- Can be null. Client clock. In extremis only.
local_modified INTEGER,
-- Boolean. Locally deleted.
is_deleted TINYINT NOT NULL,
-- Boolean. Set when changed or visits added.
should_upload TINYINT NOT NULL,
domain_id INTEGER REFERENCES domains(id) ON DELETE CASCADE,
CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)
)
"""
return sql
}
func CreateDomainsTable() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS domains (
id INTEGER PRIMARY KEY AUTOINCREMENT,
domain TEXT NOT NULL UNIQUE,
showOnTopSites TINYINT NOT NULL DEFAULT 1
)
"""
return sql
}
func CreateQueueTable() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS queue (
url TEXT NOT NULL UNIQUE,
title TEXT
)
"""
return sql
}
override func create(_ db: SQLiteDBConnection) -> Bool {
let visits = """
CREATE TABLE IF NOT EXISTS visits (
id INTEGER PRIMARY KEY AUTOINCREMENT,
siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE,
-- Microseconds since epoch.
date REAL NOT NULL,
type INTEGER NOT NULL,
-- Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
is_local TINYINT NOT NULL,
UNIQUE (siteID, date, type)
)
"""
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS idx_visits_siteID_is_local_date ON visits (siteID, is_local, date)"
let faviconSites = """
CREATE TABLE IF NOT EXISTS favicon_sites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE,
faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE,
UNIQUE (siteID, faviconID)
)
"""
let widestFavicons = """
CREATE VIEW IF NOT EXISTS view_favicons_widest AS
SELECT
favicon_sites.siteID AS siteID,
favicons.id AS iconID,
favicons.url AS iconURL,
favicons.date AS iconDate,
favicons.type AS iconType,
max(favicons.width) AS iconWidth
FROM favicon_sites, favicons
WHERE favicon_sites.faviconID = favicons.id
GROUP BY siteID
"""
let historyIDsWithIcon = """
CREATE VIEW IF NOT EXISTS view_history_id_favicon AS
SELECT history.id AS id, iconID, iconURL, iconDate, iconType, iconWidth
FROM history LEFT OUTER JOIN view_favicons_widest ON
history.id = view_favicons_widest.siteID
"""
let iconForURL = """
CREATE VIEW IF NOT EXISTS view_icon_for_url AS
SELECT history.url AS url, icons.iconID AS iconID
FROM history, view_favicons_widest AS icons
WHERE history.id = icons.siteID
"""
let bookmarks = """
CREATE TABLE IF NOT EXISTS bookmarks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guid TEXT NOT NULL UNIQUE,
type TINYINT NOT NULL,
url TEXT,
parent INTEGER REFERENCES bookmarks(id) NOT NULL,
faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL,
title TEXT
)
"""
let queries = [
// This used to be done by FaviconsTable.
self.oldFaviconsSQL,
CreateDomainsTable(),
CreateHistoryTable(),
visits, bookmarks, faviconSites,
indexShouldUpload, indexSiteIDDate,
widestFavicons, historyIDsWithIcon, iconForURL,
CreateQueueTable(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class BrowserSchemaV7: BaseHistoricalBrowserSchema {
override var version: Int { return 7 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql = """
INSERT INTO bookmarks
(id, guid, type, url, title, parent)
VALUES
-- Root
(?, ?, ?, NULL, ?, ?),
-- Mobile
(?, ?, ?, NULL, ?, ?),
-- Menu
(?, ?, ?, NULL, ?, ?),
-- Toolbar
(?, ?, ?, NULL, ?, ?),
-- Unsorted
(?, ?, ?, NULL, ?, ?)
"""
return self.run(db, sql: sql, args: args)
}
func getHistoryTableCreationString() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
-- Not null, but the value might be replaced by the server's.
guid TEXT NOT NULL UNIQUE,
-- May only be null for deleted records.
url TEXT UNIQUE,
title TEXT NOT NULL,
-- Can be null. Integer milliseconds.
server_modified INTEGER,
-- Can be null. Client clock. In extremis only.
local_modified INTEGER,
-- Boolean. Locally deleted.
is_deleted TINYINT NOT NULL,
-- Boolean. Set when changed or visits added.
should_upload TINYINT NOT NULL,
domain_id INTEGER REFERENCES domains(id) ON DELETE CASCADE,
CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)
)
"""
return sql
}
func getDomainsTableCreationString() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS domains (
id INTEGER PRIMARY KEY AUTOINCREMENT,
domain TEXT NOT NULL UNIQUE,
showOnTopSites TINYINT NOT NULL DEFAULT 1
)
"""
return sql
}
func getQueueTableCreationString() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS queue (
url TEXT NOT NULL UNIQUE,
title TEXT
)
"""
return sql
}
override func create(_ db: SQLiteDBConnection) -> Bool {
// Right now we don't need to track per-visit deletions: Sync can't
// represent them! See Bug 1157553 Comment 6.
// We flip the should_upload flag on the history item when we add a visit.
// If we ever want to support logic like not bothering to sync if we added
// and then rapidly removed a visit, then we need an 'is_new' flag on each visit.
let visits = """
CREATE TABLE IF NOT EXISTS visits (
id INTEGER PRIMARY KEY AUTOINCREMENT,
siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE,
-- Microseconds since epoch.
date REAL NOT NULL,
type INTEGER NOT NULL,
-- Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
is_local TINYINT NOT NULL,
UNIQUE (siteID, date, type)
)
"""
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS idx_visits_siteID_is_local_date ON visits (siteID, is_local, date)"
let faviconSites = """
CREATE TABLE IF NOT EXISTS favicon_sites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE,
faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE,
UNIQUE (siteID, faviconID)
)
"""
let widestFavicons = """
CREATE VIEW IF NOT EXISTS view_favicons_widest AS
SELECT
favicon_sites.siteID AS siteID,
favicons.id AS iconID,
favicons.url AS iconURL,
favicons.date AS iconDate,
favicons.type AS iconType,
max(favicons.width) AS iconWidth
FROM favicon_sites, favicons
WHERE favicon_sites.faviconID = favicons.id
GROUP BY siteID
"""
let historyIDsWithIcon = """
CREATE VIEW IF NOT EXISTS view_history_id_favicon AS
SELECT history.id AS id, iconID, iconURL, iconDate, iconType, iconWidth
FROM history LEFT OUTER JOIN view_favicons_widest ON
history.id = view_favicons_widest.siteID
"""
let iconForURL = """
CREATE VIEW IF NOT EXISTS view_icon_for_url AS
SELECT history.url AS url, icons.iconID AS iconID
FROM history, view_favicons_widest AS icons
WHERE history.id = icons.siteID
"""
let bookmarks = """
CREATE TABLE IF NOT EXISTS bookmarks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guid TEXT NOT NULL UNIQUE,
type TINYINT NOT NULL,
url TEXT,
parent INTEGER REFERENCES bookmarks(id) NOT NULL,
faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL,
title TEXT
)
"""
let queries = [
// This used to be done by FaviconsTable.
self.oldFaviconsSQL,
getDomainsTableCreationString(),
getHistoryTableCreationString(),
visits, bookmarks, faviconSites,
indexShouldUpload, indexSiteIDDate,
widestFavicons, historyIDsWithIcon, iconForURL,
getQueueTableCreationString(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class BrowserSchemaV8: BaseHistoricalBrowserSchema {
override var version: Int { return 8 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql = """
INSERT INTO bookmarks
(id, guid, type, url, title, parent)
VALUES
-- Root
(?, ?, ?, NULL, ?, ?),
-- Mobile
(?, ?, ?, NULL, ?, ?),
-- Menu
(?, ?, ?, NULL, ?, ?),
-- Toolbar
(?, ?, ?, NULL, ?, ?),
-- Unsorted
(?, ?, ?, NULL, ?, ?)
"""
return self.run(db, sql: sql, args: args)
}
func getHistoryTableCreationString() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
-- Not null, but the value might be replaced by the server's.
guid TEXT NOT NULL UNIQUE,
-- May only be null for deleted records.
url TEXT UNIQUE,
title TEXT NOT NULL,
-- Can be null. Integer milliseconds.
server_modified INTEGER,
-- Can be null. Client clock. In extremis only.
local_modified INTEGER,
-- Boolean. Locally deleted.
is_deleted TINYINT NOT NULL,
-- Boolean. Set when changed or visits added.
should_upload TINYINT NOT NULL,
domain_id INTEGER REFERENCES domains(id) ON DELETE CASCADE,
CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)
)
"""
return sql
}
func getDomainsTableCreationString() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS domains (
id INTEGER PRIMARY KEY AUTOINCREMENT,
domain TEXT NOT NULL UNIQUE,
showOnTopSites TINYINT NOT NULL DEFAULT 1
)
"""
return sql
}
func getQueueTableCreationString() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS queue (
url TEXT NOT NULL UNIQUE,
title TEXT
)
"""
return sql
}
override func create(_ db: SQLiteDBConnection) -> Bool {
let favicons = """
CREATE TABLE IF NOT EXISTS favicons (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL UNIQUE,
width INTEGER,
height INTEGER,
type INTEGER NOT NULL,
date REAL NOT NULL
)
"""
// Right now we don't need to track per-visit deletions: Sync can't
// represent them! See Bug 1157553 Comment 6.
// We flip the should_upload flag on the history item when we add a visit.
// If we ever want to support logic like not bothering to sync if we added
// and then rapidly removed a visit, then we need an 'is_new' flag on each visit.
let visits = """
CREATE TABLE IF NOT EXISTS visits (
id INTEGER PRIMARY KEY AUTOINCREMENT,
siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE,
-- Microseconds since epoch.
date REAL NOT NULL,
type INTEGER NOT NULL,
-- Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
is_local TINYINT NOT NULL,
UNIQUE (siteID, date, type)
)
"""
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS idx_visits_siteID_is_local_date ON visits (siteID, is_local, date)"
let faviconSites = """
CREATE TABLE IF NOT EXISTS favicon_sites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE,
faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE,
UNIQUE (siteID, faviconID)
)
"""
let widestFavicons = """
CREATE VIEW IF NOT EXISTS view_favicons_widest AS
SELECT
favicon_sites.siteID AS siteID,
favicons.id AS iconID,
favicons.url AS iconURL,
favicons.date AS iconDate,
favicons.type AS iconType,
max(favicons.width) AS iconWidth
FROM favicon_sites, favicons
WHERE favicon_sites.faviconID = favicons.id
GROUP BY siteID
"""
let historyIDsWithIcon = """
CREATE VIEW IF NOT EXISTS view_history_id_favicon AS
SELECT history.id AS id, iconID, iconURL, iconDate, iconType, iconWidth
FROM history LEFT OUTER JOIN view_favicons_widest ON
history.id = view_favicons_widest.siteID
"""
let iconForURL = """
CREATE VIEW IF NOT EXISTS view_icon_for_url AS
SELECT history.url AS url, icons.iconID AS iconID
FROM history, view_favicons_widest AS icons
WHERE history.id = icons.siteID
"""
let bookmarks = """
CREATE TABLE IF NOT EXISTS bookmarks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guid TEXT NOT NULL UNIQUE,
type TINYINT NOT NULL,
url TEXT,
parent INTEGER REFERENCES bookmarks(id) NOT NULL,
faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL,
title TEXT
)
"""
let queries: [String] = [
getDomainsTableCreationString(),
getHistoryTableCreationString(),
favicons,
visits,
bookmarks,
faviconSites,
indexShouldUpload,
indexSiteIDDate,
widestFavicons,
historyIDsWithIcon,
iconForURL,
getQueueTableCreationString(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class BrowserSchemaV10: BaseHistoricalBrowserSchema {
override var version: Int { return 10 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql = """
INSERT INTO bookmarks
(id, guid, type, url, title, parent)
VALUES
-- Root
(?, ?, ?, NULL, ?, ?),
-- Mobile
(?, ?, ?, NULL, ?, ?),
-- Menu
(?, ?, ?, NULL, ?, ?),
-- Toolbar
(?, ?, ?, NULL, ?, ?),
-- Unsorted
(?, ?, ?, NULL, ?, ?)
"""
return self.run(db, sql: sql, args: args)
}
func getHistoryTableCreationString(forVersion version: Int = BrowserSchema.DefaultVersion) -> String {
let sql = """
CREATE TABLE IF NOT EXISTS history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
-- Not null, but the value might be replaced by the server's.
guid TEXT NOT NULL UNIQUE,
-- May only be null for deleted records.
url TEXT UNIQUE,
title TEXT NOT NULL,
-- Can be null. Integer milliseconds.
server_modified INTEGER,
-- Can be null. Client clock. In extremis only.
local_modified INTEGER,
-- Boolean. Locally deleted.
is_deleted TINYINT NOT NULL,
-- Boolean. Set when changed or visits added.
should_upload TINYINT NOT NULL,
domain_id INTEGER REFERENCES domains(id) ON DELETE CASCADE,
CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)
)
"""
return sql
}
func getDomainsTableCreationString() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS domains (
id INTEGER PRIMARY KEY AUTOINCREMENT,
domain TEXT NOT NULL UNIQUE,
showOnTopSites TINYINT NOT NULL DEFAULT 1
)
"""
return sql
}
func getQueueTableCreationString() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS queue (
url TEXT NOT NULL UNIQUE,
title TEXT
)
"""
return sql
}
func getBookmarksMirrorTableCreationString() -> String {
// The stupid absence of naming conventions here is thanks to pre-Sync Weave. Sorry.
// For now we have the simplest possible schema: everything in one.
let sql = """
CREATE TABLE IF NOT EXISTS bookmarksMirror
-- Shared fields.
( id INTEGER PRIMARY KEY AUTOINCREMENT
, guid TEXT NOT NULL UNIQUE
-- Type enum. TODO: BookmarkNodeType needs to be extended.
, type TINYINT NOT NULL
-- Record/envelope metadata that'll allow us to do merges.
-- Milliseconds.
, server_modified INTEGER NOT NULL
-- Boolean
, is_deleted TINYINT NOT NULL DEFAULT 0
-- Boolean, 0 (false) if deleted.
, hasDupe TINYINT NOT NULL DEFAULT 0
-- GUID
, parentid TEXT
, parentName TEXT
-- Type-specific fields. These should be NOT NULL in many cases, but we're going
-- for a sparse schema, so this'll do for now. Enforce these in the application code.
-- LIVEMARKS
, feedUri TEXT, siteUri TEXT
-- SEPARATORS
, pos INT
-- FOLDERS, BOOKMARKS, QUERIES
, title TEXT, description TEXT
-- BOOKMARKS, QUERIES
, bmkUri TEXT, tags TEXT, keyword TEXT
-- QUERIES
, folderName TEXT, queryId TEXT
, CONSTRAINT parentidOrDeleted CHECK (parentid IS NOT NULL OR is_deleted = 1)
, CONSTRAINT parentNameOrDeleted CHECK (parentName IS NOT NULL OR is_deleted = 1)
)
"""
return sql
}
/**
* We need to explicitly store what's provided by the server, because we can't rely on
* referenced child nodes to exist yet!
*/
func getBookmarksMirrorStructureTableCreationString() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS bookmarksMirrorStructure (
parent TEXT NOT NULL REFERENCES bookmarksMirror(guid) ON DELETE CASCADE,
-- Should be the GUID of a child.
child TEXT NOT NULL,
-- Should advance from 0.
idx INTEGER NOT NULL
)
"""
return sql
}
override func create(_ db: SQLiteDBConnection) -> Bool {
let favicons = """
CREATE TABLE IF NOT EXISTS favicons (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL UNIQUE,
width INTEGER,
height INTEGER,
type INTEGER NOT NULL,
date REAL NOT NULL
)
"""
// Right now we don't need to track per-visit deletions: Sync can't
// represent them! See Bug 1157553 Comment 6.
// We flip the should_upload flag on the history item when we add a visit.
// If we ever want to support logic like not bothering to sync if we added
// and then rapidly removed a visit, then we need an 'is_new' flag on each visit.
let visits = """
CREATE TABLE IF NOT EXISTS visits (
id INTEGER PRIMARY KEY AUTOINCREMENT,
siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE,
-- Microseconds since epoch.
date REAL NOT NULL,
type INTEGER NOT NULL,
-- Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
is_local TINYINT NOT NULL,
UNIQUE (siteID, date, type)
)
"""
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS idx_visits_siteID_is_local_date ON visits (siteID, is_local, date)"
let faviconSites = """
CREATE TABLE IF NOT EXISTS favicon_sites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE,
faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE,
UNIQUE (siteID, faviconID)
)
"""
let widestFavicons = """
CREATE VIEW IF NOT EXISTS view_favicons_widest AS
SELECT
favicon_sites.siteID AS siteID,
favicons.id AS iconID,
favicons.url AS iconURL,
favicons.date AS iconDate,
favicons.type AS iconType,
max(favicons.width) AS iconWidth
FROM favicon_sites, favicons
WHERE favicon_sites.faviconID = favicons.id
GROUP BY siteID
"""
let historyIDsWithIcon = """
CREATE VIEW IF NOT EXISTS view_history_id_favicon AS
SELECT history.id AS id, iconID, iconURL, iconDate, iconType, iconWidth
FROM history LEFT OUTER JOIN view_favicons_widest ON
history.id = view_favicons_widest.siteID
"""
let iconForURL = """
CREATE VIEW IF NOT EXISTS view_icon_for_url AS
SELECT history.url AS url, icons.iconID AS iconID
FROM history, view_favicons_widest AS icons
WHERE history.id = icons.siteID
"""
let bookmarks = """
CREATE TABLE IF NOT EXISTS bookmarks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guid TEXT NOT NULL UNIQUE,
type TINYINT NOT NULL,
url TEXT,
parent INTEGER REFERENCES bookmarks(id) NOT NULL,
faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL,
title TEXT
)
"""
let bookmarksMirror = getBookmarksMirrorTableCreationString()
let bookmarksMirrorStructure = getBookmarksMirrorStructureTableCreationString()
let indexStructureParentIdx =
"CREATE INDEX IF NOT EXISTS idx_bookmarksMirrorStructure_parent_idx ON bookmarksMirrorStructure (parent, idx)"
let queries: [String] = [
getDomainsTableCreationString(),
getHistoryTableCreationString(),
favicons,
visits,
bookmarks,
bookmarksMirror,
bookmarksMirrorStructure,
indexStructureParentIdx,
faviconSites,
indexShouldUpload,
indexSiteIDDate,
widestFavicons,
historyIDsWithIcon,
iconForURL,
getQueueTableCreationString(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class TestSQLiteHistory: XCTestCase {
let files = MockFiles()
fileprivate func deleteDatabases() {
for v in ["6", "7", "8", "10", "6-data"] {
do {
try files.remove("browser-v\(v).db")
} catch {}
}
do {
try files.remove("browser.db")
try files.remove("historysynced.db")
} catch {}
}
override func tearDown() {
super.tearDown()
self.deleteDatabases()
}
override func setUp() {
super.setUp()
// Just in case tearDown didn't run or succeed last time!
self.deleteDatabases()
}
// Test that our visit partitioning for frecency is correct.
func testHistoryLocalAndRemoteVisits() {
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let siteL = Site(url: "http://url1/", title: "title local only")
let siteR = Site(url: "http://url2/", title: "title remote only")
let siteB = Site(url: "http://url3/", title: "title local and remote")
siteL.guid = "locallocal12"
siteR.guid = "remoteremote"
siteB.guid = "bothbothboth"
let siteVisitL1 = SiteVisit(site: siteL, date: baseInstantInMicros + 1000, type: VisitType.link)
let siteVisitL2 = SiteVisit(site: siteL, date: baseInstantInMicros + 2000, type: VisitType.link)
let siteVisitR1 = SiteVisit(site: siteR, date: baseInstantInMicros + 1000, type: VisitType.link)
let siteVisitR2 = SiteVisit(site: siteR, date: baseInstantInMicros + 2000, type: VisitType.link)
let siteVisitR3 = SiteVisit(site: siteR, date: baseInstantInMicros + 3000, type: VisitType.link)
let siteVisitBL1 = SiteVisit(site: siteB, date: baseInstantInMicros + 4000, type: VisitType.link)
let siteVisitBR1 = SiteVisit(site: siteB, date: baseInstantInMicros + 5000, type: VisitType.link)
let deferred =
history.clearHistory()
>>> { history.addLocalVisit(siteVisitL1) }
>>> { history.addLocalVisit(siteVisitL2) }
>>> { history.addLocalVisit(siteVisitBL1) }
>>> { history.insertOrUpdatePlace(siteL.asPlace(), modified: baseInstantInMillis + 2) }
>>> { history.insertOrUpdatePlace(siteR.asPlace(), modified: baseInstantInMillis + 3) }
>>> { history.insertOrUpdatePlace(siteB.asPlace(), modified: baseInstantInMillis + 5) }
// Do this step twice, so we exercise the dupe-visit handling.
>>> { history.storeRemoteVisits([siteVisitR1, siteVisitR2, siteVisitR3], forGUID: siteR.guid!) }
>>> { history.storeRemoteVisits([siteVisitR1, siteVisitR2, siteVisitR3], forGUID: siteR.guid!) }
>>> { history.storeRemoteVisits([siteVisitBR1], forGUID: siteB.guid!) }
>>> {
history.getFrecentHistory().getSites(whereURLContains: nil, historyLimit: 3, bookmarksLimit: 0)
>>== { (sites: Cursor) -> Success in
XCTAssertEqual(3, sites.count)
// Two local visits beat a single later remote visit and one later local visit.
// Two local visits beat three remote visits.
XCTAssertEqual(siteL.guid!, sites[0]!.guid!)
XCTAssertEqual(siteB.guid!, sites[1]!.guid!)
XCTAssertEqual(siteR.guid!, sites[2]!.guid!)
return succeed()
}
// This marks everything as modified so we can fetch it.
>>> history.onRemovedAccount
// Now check that we have no duplicate visits.
>>> { history.getModifiedHistoryToUpload()
>>== { (places) -> Success in
if let (_, visits) = places.find({$0.0.guid == siteR.guid!}) {
XCTAssertEqual(3, visits.count)
} else {
XCTFail("Couldn't find site R.")
}
return succeed()
}
}
}
XCTAssertTrue(deferred.value.isSuccess)
}
func testUpgrades() {
let sources: [(Int, Schema)] = [
(6, BrowserSchemaV6()),
(7, BrowserSchemaV7()),
(8, BrowserSchemaV8()),
(10, BrowserSchemaV10()),
]
let destination = BrowserSchema()
for (version, schema) in sources {
var db = BrowserDB(filename: "browser-v\(version).db", schema: schema, files: files)
XCTAssertTrue(db.withConnection({ connection -> Int in
connection.version
}).value.successValue == schema.version, "Creating BrowserSchema at version \(version)")
db.forceClose()
db = BrowserDB(filename: "browser-v\(version).db", schema: destination, files: files)
XCTAssertTrue(db.withConnection({ connection -> Int in
connection.version
}).value.successValue == destination.version, "Upgrading BrowserSchema from version \(version) to version \(schema.version)")
db.forceClose()
}
}
func testUpgradesWithData() {
var db = BrowserDB(filename: "browser-v6-data.db", schema: BrowserSchemaV6(), files: files)
// Insert some data.
let queries = [
"INSERT INTO domains (id, domain) VALUES (1, 'example.com')",
"INSERT INTO history (id, guid, url, title, server_modified, local_modified, is_deleted, should_upload, domain_id) VALUES (5, 'guid', 'http://www.example.com', 'title', 5, 10, 0, 1, 1)",
"INSERT INTO visits (siteID, date, type, is_local) VALUES (5, 15, 1, 1)",
"INSERT INTO favicons (url, width, height, type, date) VALUES ('http://www.example.com/favicon.ico', 10, 10, 1, 20)",
"INSERT INTO favicon_sites (siteID, faviconID) VALUES (5, 1)",
"INSERT INTO bookmarks (guid, type, url, parent, faviconID, title) VALUES ('guid', 1, 'http://www.example.com', 0, 1, 'title')"
]
XCTAssertTrue(db.run(queries).value.isSuccess)
// And we can upgrade to the current version.
db = BrowserDB(filename: "browser-v6-data.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let results = history.getSitesByLastVisit(limit: 10, offset: 0).value.successValue
XCTAssertNotNil(results)
XCTAssertEqual(results![0]?.url, "http://www.example.com")
db.forceClose()
}
func testDomainUpgrade() {
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let site = Site(url: "http://www.example.com/test1.1", title: "title one")
// Insert something with an invalid domain ID. We have to manually do this since domains are usually hidden.
let insertDeferred = db.withConnection { connection -> Void in
try connection.executeChange("PRAGMA foreign_keys = OFF")
let insert = "INSERT INTO history (guid, url, title, local_modified, is_deleted, should_upload, domain_id) VALUES (?, ?, ?, ?, ?, ?, ?)"
let args: Args = [Bytes.generateGUID(), site.url, site.title, Date.now(), 0, 0, -1]
try connection.executeChange(insert, withArgs: args)
}
XCTAssertTrue(insertDeferred.value.isSuccess)
// Now insert it again. This should update the domain.
history.addLocalVisit(SiteVisit(site: site, date: Date.nowMicroseconds(), type: VisitType.link)).succeeded()
// domain_id isn't normally exposed, so we manually query to get it.
let resultsDeferred = db.withConnection { connection -> Cursor<Int?> in
let sql = "SELECT domain_id FROM history WHERE url = ?"
let args: Args = [site.url]
return connection.executeQuery(sql, factory: { $0[0] as? Int }, withArgs: args)
}
let results = resultsDeferred.value.successValue!
let domain = results[0]! // Unwrap to get the first item from the cursor.
XCTAssertNil(domain)
}
func testDomains() {
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let initialGuid = Bytes.generateGUID()
let site11 = Site(url: "http://www.example.com/test1.1", title: "title one")
let site12 = Site(url: "http://www.example.com/test1.2", title: "title two")
let site13 = Place(guid: initialGuid, url: "http://www.example.com/test1.3", title: "title three")
let site3 = Site(url: "http://www.example2.com/test1", title: "title three")
let expectation = self.expectation(description: "First.")
let clearTopSites = "DELETE FROM cached_top_sites"
let updateTopSites: [(String, Args?)] = [(clearTopSites, nil), (history.getFrecentHistory().updateTopSitesCacheQuery())]
func countTopSites() -> Deferred<Maybe<Cursor<Int>>> {
return db.runQuery("SELECT count(*) FROM cached_top_sites", args: nil, factory: { sdrow -> Int in
return sdrow[0] as? Int ?? 0
})
}
history.clearHistory().bind({ success in
return all([history.addLocalVisit(SiteVisit(site: site11, date: Date.nowMicroseconds(), type: VisitType.link)),
history.addLocalVisit(SiteVisit(site: site12, date: Date.nowMicroseconds(), type: VisitType.link)),
history.addLocalVisit(SiteVisit(site: site3, date: Date.nowMicroseconds(), type: VisitType.link))])
}).bind({ (results: [Maybe<()>]) in
return history.insertOrUpdatePlace(site13, modified: Date.nowMicroseconds())
}).bind({ guid -> Success in
XCTAssertEqual(guid.successValue!, initialGuid, "Guid is correct")
return db.run(updateTopSites)
}).bind({ success in
XCTAssertTrue(success.isSuccess, "update was successful")
return countTopSites()
}).bind({ (count: Maybe<Cursor<Int>>) -> Success in
XCTAssert(count.successValue![0] == 2, "2 sites returned")
return history.removeSiteFromTopSites(site11)
}).bind({ success -> Success in
XCTAssertTrue(success.isSuccess, "Remove was successful")
return db.run(updateTopSites)
}).bind({ success -> Deferred<Maybe<Cursor<Int>>> in
XCTAssertTrue(success.isSuccess, "update was successful")
return countTopSites()
})
.upon({ (count: Maybe<Cursor<Int>>) in
XCTAssert(count.successValue![0] == 1, "1 site returned")
expectation.fulfill()
})
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testHistoryIsSynced() {
let db = BrowserDB(filename: "historysynced.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let initialGUID = Bytes.generateGUID()
let site = Place(guid: initialGUID, url: "http://www.example.com/test1.3", title: "title")
XCTAssertFalse(history.hasSyncedHistory().value.successValue ?? true)
XCTAssertTrue(history.insertOrUpdatePlace(site, modified: Date.now()).value.isSuccess)
XCTAssertTrue(history.hasSyncedHistory().value.successValue ?? false)
}
// This is a very basic test. Adds an entry, retrieves it, updates it,
// and then clears the database.
func testHistoryTable() {
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let bookmarks = SQLiteBookmarks(db: db)
let site1 = Site(url: "http://url1/", title: "title one")
let site1Changed = Site(url: "http://url1/", title: "title one alt")
let siteVisit1 = SiteVisit(site: site1, date: Date.nowMicroseconds(), type: VisitType.link)
let siteVisit2 = SiteVisit(site: site1Changed, date: Date.nowMicroseconds() + 1000, type: VisitType.bookmark)
let site2 = Site(url: "http://url2/", title: "title two")
let siteVisit3 = SiteVisit(site: site2, date: Date.nowMicroseconds() + 2000, type: VisitType.link)
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func checkSitesByFrecency(_ f: @escaping (Cursor<Site>) -> Success) -> () -> Success {
return {
history.getFrecentHistory().getSites(whereURLContains: nil, historyLimit: 10, bookmarksLimit: 0)
>>== f
}
}
func checkSitesByDate(_ f: @escaping (Cursor<Site>) -> Success) -> () -> Success {
return {
history.getSitesByLastVisit(limit: 10, offset: 0)
>>== f
}
}
func checkSitesWithFilter(_ filter: String, f: @escaping (Cursor<Site>) -> Success) -> () -> Success {
return {
history.getFrecentHistory().getSites(whereURLContains: filter, historyLimit: 10, bookmarksLimit: 0)
>>== f
}
}
func checkDeletedCount(_ expected: Int) -> () -> Success {
return {
history.getDeletedHistoryToUpload()
>>== { guids in
XCTAssertEqual(expected, guids.count)
return succeed()
}
}
}
history.clearHistory()
>>> { history.addLocalVisit(siteVisit1) }
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(1, sites.count)
XCTAssertEqual(site1.title, sites[0]!.title)
XCTAssertEqual(site1.url, sites[0]!.url)
sites.close()
return succeed()
}
>>> { history.addLocalVisit(siteVisit2) }
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(1, sites.count)
XCTAssertEqual(site1Changed.title, sites[0]!.title)
XCTAssertEqual(site1Changed.url, sites[0]!.url)
sites.close()
return succeed()
}
>>> { history.addLocalVisit(siteVisit3) }
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(2, sites.count)
// They're in order of frecency.
XCTAssertEqual(site1Changed.title, sites[0]!.title)
XCTAssertEqual(site2.title, sites[1]!.title)
return succeed()
}
>>> checkSitesByDate { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(2, sites.count)
// They're in order of date last visited.
let first = sites[0]!
let second = sites[1]!
XCTAssertEqual(site2.title, first.title)
XCTAssertEqual(site1Changed.title, second.title)
XCTAssertTrue(siteVisit3.date == first.latestVisit!.date)
return succeed()
}
>>> checkSitesWithFilter("two") { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(1, sites.count)
let first = sites[0]!
XCTAssertEqual(site2.title, first.title)
return succeed()
}
>>>
checkDeletedCount(0)
>>> { history.removeHistoryForURL("http://url2/") }
>>>
checkDeletedCount(1)
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(1, sites.count)
// They're in order of frecency.
XCTAssertEqual(site1Changed.title, sites[0]!.title)
return succeed()
}
>>> { history.clearHistory() }
>>>
checkDeletedCount(0)
>>> checkSitesByDate { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(0, sites.count)
return succeed()
}
>>> checkSitesByFrecency { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(0, sites.count)
return succeed()
}
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testFaviconTable() {
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let bookmarks = SQLiteBookmarks(db: db)
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func updateFavicon() -> Success {
let fav = Favicon(url: "http://url2/", date: Date())
fav.id = 1
let site = Site(url: "http://bookmarkedurl/", title: "My Bookmark")
return history.addFavicon(fav, forSite: site) >>> succeed
}
func checkFaviconForBookmarkIsNil() -> Success {
return bookmarks.bookmarksByURL("http://bookmarkedurl/".asURL!) >>== { results in
XCTAssertEqual(1, results.count)
XCTAssertNil(results[0]?.favicon)
return succeed()
}
}
func checkFaviconWasSetForBookmark() -> Success {
return history.getFaviconsForBookmarkedURL("http://bookmarkedurl/") >>== { results in
XCTAssertEqual(1, results.count)
if let actualFaviconURL = results[0]??.url {
XCTAssertEqual("http://url2/", actualFaviconURL)
}
return succeed()
}
}
func removeBookmark() -> Success {
return bookmarks.testFactory.removeByURL("http://bookmarkedurl/")
}
func checkFaviconWasRemovedForBookmark() -> Success {
return history.getFaviconsForBookmarkedURL("http://bookmarkedurl/") >>== { results in
XCTAssertEqual(0, results.count)
return succeed()
}
}
history.clearAllFavicons()
>>> bookmarks.clearBookmarks
>>> { bookmarks.addToMobileBookmarks("http://bookmarkedurl/".asURL!, title: "Title", favicon: nil) }
>>> checkFaviconForBookmarkIsNil
>>> updateFavicon
>>> checkFaviconWasSetForBookmark
>>> removeBookmark
>>> checkFaviconWasRemovedForBookmark
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testRemoveHistoryForUrl() {
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.setTopSitesCacheSize(20)
history.clearTopSitesCache().succeeded()
history.clearHistory().succeeded()
let url1 = "http://url1/"
let site1 = Site(url: "http://url1/", title: "title one")
let siteVisit1 = SiteVisit(site: site1, date: Date.nowMicroseconds(), type: VisitType.link)
let url2 = "http://url2/"
let site2 = Site(url: "http://url2/", title: "title two")
let siteVisit2 = SiteVisit(site: site2, date: Date.nowMicroseconds() + 2000, type: VisitType.link)
let url3 = "http://url3/"
let site3 = Site(url: url3, title: "title three")
let siteVisit3 = SiteVisit(site: site3, date: Date.nowMicroseconds() + 4000, type: VisitType.link)
history.addLocalVisit(siteVisit1).succeeded()
history.addLocalVisit(siteVisit2).succeeded()
history.addLocalVisit(siteVisit3).succeeded()
history.removeHistoryForURL(url1).succeeded()
history.removeHistoryForURL(url2).succeeded()
history.getDeletedHistoryToUpload()
>>== { guids in
XCTAssertEqual(2, guids.count)
}
}
func testTopSitesFrecencyOrder() {
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.setTopSitesCacheSize(20)
history.clearTopSitesCache().succeeded()
history.clearHistory().succeeded()
// Lets create some history. This will create 100 sites that will have 21 local and 21 remote visits
populateHistoryForFrecencyCalculations(history, siteCount: 100)
// Create a new site thats for an existing domain but a different URL.
let site = Site(url: "http://s\(5)ite\(5).com/foo-different-url", title: "A \(5) different url")
site.guid = "abc\(5)defhi"
history.insertOrUpdatePlace(site.asPlace(), modified: baseInstantInMillis - 20000).succeeded()
// Don't give it any remote visits. But give it 100 local visits. This should be the new Topsite!
for i in 0...100 {
addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i))
}
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func loadCache() -> Success {
return history.repopulate(invalidateTopSites: true, invalidateHighlights: true) >>> succeed
}
func checkTopSitesReturnsResults() -> Success {
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(5)defhi")
return succeed()
}
}
loadCache()
>>> checkTopSitesReturnsResults
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testTopSitesFiltersGoogle() {
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.setTopSitesCacheSize(20)
history.clearTopSitesCache().succeeded()
history.clearHistory().succeeded()
// Lets create some history. This will create 100 sites that will have 21 local and 21 remote visits
populateHistoryForFrecencyCalculations(history, siteCount: 100)
func createTopSite(url: String, guid: String) {
let site = Site(url: url, title: "Hi")
site.guid = guid
history.insertOrUpdatePlace(site.asPlace(), modified: baseInstantInMillis - 20000).succeeded()
// Don't give it any remote visits. But give it 100 local visits. This should be the new Topsite!
for i in 0...100 {
addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i))
}
}
createTopSite(url: "http://google.com", guid: "abcgoogle") // should not be a topsite
createTopSite(url: "http://www.google.com", guid: "abcgoogle1") // should not be a topsite
createTopSite(url: "http://google.co.za", guid: "abcgoogleza") // should not be a topsite
createTopSite(url: "http://docs.google.com", guid: "docsgoogle") // should be a topsite
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func loadCache() -> Success {
return history.repopulate(invalidateTopSites: true, invalidateHighlights: true) >>> succeed
}
func checkTopSitesReturnsResults() -> Success {
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites[0]?.guid, "docsgoogle") // google docs should be the first topsite
// make sure all other google guids are not in the topsites array
topSites.forEach {
let guid: String = $0!.guid! // type checking is hard
XCTAssertNil(["abcgoogle", "abcgoogle1", "abcgoogleza"].index(of: guid))
}
XCTAssertEqual(topSites.count, 20)
return succeed()
}
}
loadCache()
>>> checkTopSitesReturnsResults
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testTopSitesCache() {
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.setTopSitesCacheSize(20)
history.clearTopSitesCache().succeeded()
history.clearHistory().succeeded()
// Make sure that we get back the top sites
populateHistoryForFrecencyCalculations(history, siteCount: 100)
// Add extra visits to the 5th site to bubble it to the top of the top sites cache
let site = Site(url: "http://s\(5)ite\(5).com/foo", title: "A \(5)")
site.guid = "abc\(5)def"
for i in 0...20 {
addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i))
}
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func loadCache() -> Success {
return history.repopulate(invalidateTopSites: true, invalidateHighlights: true) >>> succeed
}
func checkTopSitesReturnsResults() -> Success {
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(5)def")
return succeed()
}
}
func invalidateIfNeededDoesntChangeResults() -> Success {
return history.repopulate(invalidateTopSites: true, invalidateHighlights: true) >>> {
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(5)def")
return succeed()
}
}
}
func addVisitsToZerothSite() -> Success {
let site = Site(url: "http://s\(0)ite\(0).com/foo", title: "A \(0)")
site.guid = "abc\(0)def"
for i in 0...20 {
addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i))
}
return succeed()
}
func markInvalidation() -> Success {
history.setTopSitesNeedsInvalidation()
return succeed()
}
func checkSitesInvalidate() -> Success {
history.repopulate(invalidateTopSites: true, invalidateHighlights: true).succeeded()
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(5)def")
XCTAssertEqual(topSites[1]!.guid, "abc\(0)def")
return succeed()
}
}
loadCache()
>>> checkTopSitesReturnsResults
>>> invalidateIfNeededDoesntChangeResults
>>> markInvalidation
>>> addVisitsToZerothSite
>>> checkSitesInvalidate
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testPinnedTopSites() {
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.setTopSitesCacheSize(20)
history.clearTopSitesCache().succeeded()
history.clearHistory().succeeded()
// add 2 sites to pinned topsite
// get pinned site and make sure it exists in the right order
// remove pinned sites
// make sure pinned sites dont exist
// create pinned sites.
let site1 = Site(url: "http://s\(1)ite\(1).com/foo", title: "A \(1)")
site1.id = 1
site1.guid = "abc\(1)def"
addVisitForSite(site1, intoHistory: history, from: .local, atTime: Date.now())
let site2 = Site(url: "http://s\(2)ite\(2).com/foo", title: "A \(2)")
site2.id = 2
site2.guid = "abc\(2)def"
addVisitForSite(site2, intoHistory: history, from: .local, atTime: Date.now())
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func addPinnedSites() -> Success {
return history.addPinnedTopSite(site1) >>== {
sleep(1) // Sleep to prevent intermittent issue with sorting on the timestamp
return history.addPinnedTopSite(site2)
}
}
func checkPinnedSites() -> Success {
return history.getPinnedTopSites() >>== { pinnedSites in
XCTAssertEqual(pinnedSites.count, 2)
XCTAssertEqual(pinnedSites[0]!.url, site2.url)
XCTAssertEqual(pinnedSites[1]!.url, site1.url, "The older pinned site should be last")
return succeed()
}
}
func removePinnedSites() -> Success {
return history.removeFromPinnedTopSites(site2) >>== {
return history.getPinnedTopSites() >>== { pinnedSites in
XCTAssertEqual(pinnedSites.count, 1, "There should only be one pinned site")
XCTAssertEqual(pinnedSites[0]!.url, site1.url, "Site2 should be the only pin left")
return succeed()
}
}
}
func dupePinnedSite() -> Success {
return history.addPinnedTopSite(site1) >>== {
return history.getPinnedTopSites() >>== { pinnedSites in
XCTAssertEqual(pinnedSites.count, 1, "There should not be a dupe")
XCTAssertEqual(pinnedSites[0]!.url, site1.url, "Site2 should be the only pin left")
return succeed()
}
}
}
func removeHistory() -> Success {
return history.clearHistory() >>== {
return history.getPinnedTopSites() >>== { pinnedSites in
XCTAssertEqual(pinnedSites.count, 1, "Pinned sites should exist after a history clear")
return succeed()
}
}
}
addPinnedSites()
>>> checkPinnedSites
>>> removePinnedSites
>>> dupePinnedSite
>>> removeHistory
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
}
class TestSQLiteHistoryTransactionUpdate: XCTestCase {
func testUpdateInTransaction() {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.clearHistory().succeeded()
let site = Site(url: "http://site/foo", title: "AA")
site.guid = "abcdefghiabc"
history.insertOrUpdatePlace(site.asPlace(), modified: 1234567890).succeeded()
let ts: MicrosecondTimestamp = baseInstantInMicros
let local = SiteVisit(site: site, date: ts, type: VisitType.link)
XCTAssertTrue(history.addLocalVisit(local).value.isSuccess)
}
}
class TestSQLiteHistoryFilterSplitting: XCTestCase {
let history: SQLiteHistory = {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
return SQLiteHistory(db: db, prefs: prefs)
}()
func testWithSingleWord() {
let (fragment, args) = computeWhereFragmentWithFilter("foo", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foo"]))
}
func testWithIdenticalWords() {
let (fragment, args) = computeWhereFragmentWithFilter("foo fo foo", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foo"]))
}
func testWithDistinctWords() {
let (fragment, args) = computeWhereFragmentWithFilter("foo bar", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "? AND ?")
XCTAssert(stringArgsEqual(args, ["foo", "bar"]))
}
func testWithDistinctWordsAndWhitespace() {
let (fragment, args) = computeWhereFragmentWithFilter(" foo bar ", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "? AND ?")
XCTAssert(stringArgsEqual(args, ["foo", "bar"]))
}
func testWithSubstrings() {
let (fragment, args) = computeWhereFragmentWithFilter("foo bar foobar", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foobar"]))
}
func testWithSubstringsAndIdenticalWords() {
let (fragment, args) = computeWhereFragmentWithFilter("foo bar foobar foobar", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foobar"]))
}
fileprivate func stringArgsEqual(_ one: Args, _ other: Args) -> Bool {
return one.elementsEqual(other, by: { (oneElement: Any?, otherElement: Any?) -> Bool in
return (oneElement as! String) == (otherElement as! String)
})
}
}
| mpl-2.0 |
tardieu/swift | test/SILOptimizer/definite_init_diagnostics.swift | 1 | 33253 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-sil %s -parse-stdlib -o /dev/null -verify
import Swift
func markUsed<T>(_ t: T) {}
// These are tests for definite initialization, which is implemented by the
// memory promotion pass.
func test1() -> Int {
// expected-warning @+1 {{variable 'a' was never mutated; consider changing to 'let' constant}} {{3-6=let}}
var a : Int // expected-note {{variable defined here}}
return a // expected-error {{variable 'a' used before being initialized}}
}
func takes_inout(_ a: inout Int) {}
func takes_closure(_ fn: () -> ()) {}
class SomeClass {
var x : Int // expected-note {{'self.x' not initialized}}
var computedProperty : Int { return 42 }
init() { x = 0 }
init(b : Bool) {
if (b) {}
} // expected-error {{return from initializer without initializing all stored properties}}
func baseMethod() {}
}
struct SomeStruct { var x = 1 }
func test2() {
// inout.
var a1 : Int // expected-note {{variable defined here}}
takes_inout(&a1) // expected-error {{variable 'a1' passed by reference before being initialized}}
var a2 = 4
takes_inout(&a2) // ok.
var a3 : Int
a3 = 4
takes_inout(&a3) // ok.
// Address-of with Builtin.addressof.
var a4 : Int // expected-note {{variable defined here}}
Builtin.addressof(&a4) // expected-error {{address of variable 'a4' taken before it is initialized}}
// expected-warning @-1 {{result of call to 'addressof' is unused}}
// Closures.
// expected-warning @+1 {{variable 'b1' was never mutated}} {{3-6=let}}
var b1 : Int // expected-note {{variable defined here}}
takes_closure { // expected-error {{variable 'b1' captured by a closure before being initialized}}
markUsed(b1)
}
var b1a : Int // expected-note {{variable defined here}}
takes_closure { // expected-error {{variable 'b1a' captured by a closure before being initialized}}
b1a += 1
markUsed(b1a)
}
var b2 = 4
takes_closure { // ok.
markUsed(b2)
}
b2 = 1
var b3 : Int
b3 = 4
takes_closure { // ok.
markUsed(b3)
}
var b4 : Int?
takes_closure { // ok.
markUsed(b4!)
}
b4 = 7
// Structs
var s1 : SomeStruct
s1 = SomeStruct() // ok
_ = s1
var s2 : SomeStruct // expected-note {{variable defined here}}
s2.x = 1 // expected-error {{struct 's2' must be completely initialized before a member is stored to}}
// Classes
// expected-warning @+1 {{variable 'c1' was never mutated}} {{3-6=let}}
var c1 : SomeClass // expected-note {{variable defined here}}
markUsed(c1.x) // expected-error {{variable 'c1' used before being initialized}}
let c2 = SomeClass()
markUsed(c2.x) // ok
// Weak
weak var w1 : SomeClass?
_ = w1 // ok: default-initialized
weak var w2 = SomeClass()
_ = w2 // ok
// Unowned. This is immediately crashing code (it causes a retain of a
// released object) so it should be diagnosed with a warning someday.
// expected-warning @+1 {{variable 'u1' was never mutated; consider changing to 'let' constant}} {{11-14=let}}
unowned var u1 : SomeClass // expected-note {{variable defined here}}
_ = u1 // expected-error {{variable 'u1' used before being initialized}}
unowned let u2 = SomeClass()
_ = u2 // ok
}
// Tuple field sensitivity.
func test4() {
// expected-warning @+1 {{variable 't1' was never mutated; consider changing to 'let' constant}} {{3-6=let}}
var t1 = (1, 2, 3)
markUsed(t1.0 + t1.1 + t1.2) // ok
// expected-warning @+1 {{variable 't2' was never mutated; consider changing to 'let' constant}} {{3-6=let}}
var t2 : (Int, Int, Int) // expected-note 3 {{variable defined here}}
markUsed(t2.0) // expected-error {{variable 't2.0' used before being initialized}}
markUsed(t2.1) // expected-error {{variable 't2.1' used before being initialized}}
markUsed(t2.2) // expected-error {{variable 't2.2' used before being initialized}}
var t3 : (Int, Int, Int) // expected-note {{variable defined here}}
t3.0 = 1; t3.2 = 42
markUsed(t3.0)
markUsed(t3.1) // expected-error {{variable 't3.1' used before being initialized}}
markUsed(t3.2)
// Partially set, wholly read.
var t4 : (Int, Int, Int) // expected-note 1 {{variable defined here}}
t4.0 = 1; t4.2 = 42
_ = t4 // expected-error {{variable 't4.1' used before being initialized}}
// Subelement sets.
var t5 : (a : (Int, Int), b : Int) // expected-note {{variable defined here}}
t5.a = (1,2)
markUsed(t5.a.0)
markUsed(t5.a.1)
markUsed(t5.b) // expected-error {{variable 't5.b' used before being initialized}}
var t6 : (a : (Int, Int), b : Int) // expected-note {{variable defined here}}
t6.b = 12; t6.a.1 = 1
markUsed(t6.a.0) // expected-error {{variable 't6.a.0' used before being initialized}}
markUsed(t6.a.1)
markUsed(t6.b)
}
func tupleinout(_ a: inout (lo: Int, hi: Int)) {
markUsed(a.0) // ok
markUsed(a.1) // ok
}
// Address only types
func test5<T>(_ x: T, y: T) {
var a : ((T, T), T) // expected-note {{variable defined here}}
a.0 = (x, y)
_ = a // expected-error {{variable 'a.1' used before being initialized}}
}
struct IntFloatStruct { var a = 1, b = 2.0 }
func test6() -> Int {
var a = IntFloatStruct()
a.a = 1
a.b = 2
return a.a
}
// Control flow.
func test7(_ cond: Bool) {
var a : Int
if cond { a = 42 } else { a = 17 }
markUsed(a) // ok
var b : Int // expected-note {{variable defined here}}
if cond { } else { b = 17 }
markUsed(b) // expected-error {{variable 'b' used before being initialized}}
}
protocol SomeProtocol {
func protoMe()
}
protocol DerivedProtocol : SomeProtocol {}
func existentials(_ i: Int, dp: DerivedProtocol) {
// expected-warning @+1 {{variable 'a' was written to, but never read}}
var a : Any = ()
a = i
// expected-warning @+1 {{variable 'b' was written to, but never read}}
var b : Any
b = ()
// expected-warning @+1 {{variable 'c' was never used}} {{7-8=_}}
var c : Any // no uses.
// expected-warning @+1 {{variable 'd1' was never mutated}} {{3-6=let}}
var d1 : Any // expected-note {{variable defined here}}
_ = d1 // expected-error {{variable 'd1' used before being initialized}}
// expected-warning @+1 {{variable 'e' was never mutated}} {{3-6=let}}
var e : SomeProtocol // expected-note {{variable defined here}}
e.protoMe() // expected-error {{variable 'e' used before being initialized}}
var f : SomeProtocol = dp // ok, init'd by existential upcast.
// expected-warning @+1 {{variable 'g' was never mutated}} {{3-6=let}}
var g : DerivedProtocol // expected-note {{variable defined here}}
f = g // expected-error {{variable 'g' used before being initialized}}
_ = f
}
// Tests for top level code.
var g1 : Int // expected-note {{variable defined here}}
var g2 : Int = 42
func testTopLevelCode() { // expected-error {{variable 'g1' used by function definition before being initialized}}
markUsed(g1)
markUsed(g2)
}
var (g3,g4) : (Int,Int) // expected-note 2 {{variable defined here}}
class DITLC_Class {
init() { // expected-error {{variable 'g3' used by function definition before being initialized}}
markUsed(g3)
}
deinit { // expected-error {{variable 'g4' used by function definition before being initialized}}
markUsed(g4)
}
}
struct EmptyStruct {}
func useEmptyStruct(_ a: EmptyStruct) {}
func emptyStructTest() {
// <rdar://problem/20065892> Diagnostic for an uninitialized constant calls it a variable
let a : EmptyStruct // expected-note {{constant defined here}}
useEmptyStruct(a) // expected-error {{constant 'a' used before being initialized}}
var (b,c,d) : (EmptyStruct,EmptyStruct,EmptyStruct) // expected-note 2 {{variable defined here}}
c = EmptyStruct()
useEmptyStruct(b) // expected-error {{variable 'b' used before being initialized}}
useEmptyStruct(c)
useEmptyStruct(d) // expected-error {{variable 'd' used before being initialized}}
var (e,f) : (EmptyStruct,EmptyStruct)
(e, f) = (EmptyStruct(),EmptyStruct())
useEmptyStruct(e)
useEmptyStruct(f)
var g : (EmptyStruct,EmptyStruct)
g = (EmptyStruct(),EmptyStruct())
useEmptyStruct(g.0)
useEmptyStruct(g.1)
}
func takesTuplePair(_ a : inout (SomeClass, SomeClass)) {}
// This tests cases where a store might be an init or assign based on control
// flow path reaching it.
func conditionalInitOrAssign(_ c : Bool, x : Int) {
var t : Int // Test trivial types.
if c {
t = 0
}
if c {
t = x
}
t = 2
_ = t
// Nontrivial type
var sc : SomeClass
if c {
sc = SomeClass()
}
sc = SomeClass()
_ = sc
// Tuple element types
var tt : (SomeClass, SomeClass)
if c {
tt.0 = SomeClass()
} else {
tt.1 = SomeClass()
}
tt.0 = SomeClass()
tt.1 = tt.0
var t2 : (SomeClass, SomeClass) // expected-note {{variable defined here}}
t2.0 = SomeClass()
takesTuplePair(&t2) // expected-error {{variable 't2.1' passed by reference before being initialized}}
}
enum NotInitializedUnion {
init() {
} // expected-error {{return from enum initializer method without storing to 'self'}}
case X
case Y
}
extension NotInitializedUnion {
init(a : Int) {
} // expected-error {{return from enum initializer method without storing to 'self'}}
}
enum NotInitializedGenericUnion<T> {
init() {
} // expected-error {{return from enum initializer method without storing to 'self'}}
case X
}
class SomeDerivedClass : SomeClass {
var y : Int
override init() {
y = 42 // ok
super.init()
}
init(a : Bool) {
super.init() // expected-error {{property 'self.y' not initialized at super.init call}}
}
init(a : Bool, b : Bool) {
// x is a superclass member. It cannot be used before we are initialized.
x = 17 // expected-error {{use of 'self' in property access 'x' before super.init initializes self}}
y = 42
super.init()
}
init(a : Bool, b : Bool, c : Bool) {
y = 42
super.init()
}
init(a : Bool, b : Bool, c : Bool, d : Bool) {
y = 42
super.init()
super.init() // expected-error {{super.init called multiple times in initializer}}
}
init(a : Bool, b : Bool, c : Bool, d : Bool, e : Bool) {
super.init() // expected-error {{property 'self.y' not initialized at super.init call}}
super.init() // expected-error {{super.init called multiple times in initializer}}
}
init(a : Bool, b : Bool, c : Bool, d : Bool, e : Bool, f : Bool) {
y = 11
if a { super.init() }
x = 42 // expected-error {{use of 'self' in property access 'x' before super.init initializes self}}
} // expected-error {{super.init isn't called on all paths before returning from initializer}}
func someMethod() {}
init(a : Int) {
y = 42
super.init()
}
init(a : Int, b : Bool) {
y = 42
someMethod() // expected-error {{use of 'self' in method call 'someMethod' before super.init initializes self}}
super.init()
}
init(a : Int, b : Int) {
y = 42
baseMethod() // expected-error {{use of 'self' in method call 'baseMethod' before super.init initializes self}}
super.init()
}
init(a : Int, b : Int, c : Int) {
y = computedProperty // expected-error {{use of 'self' in property access 'computedProperty' before super.init initializes self}}
super.init()
}
}
//===----------------------------------------------------------------------===//
// Delegating initializers
//===----------------------------------------------------------------------===//
class DelegatingCtorClass {
var ivar: EmptyStruct
init() { ivar = EmptyStruct() }
convenience init(x: EmptyStruct) {
self.init()
_ = ivar // okay: ivar has been initialized by the delegation above
}
convenience init(x: EmptyStruct, y: EmptyStruct) {
_ = ivar // expected-error {{use of 'self' in property access 'ivar' before self.init initializes self}}
ivar = x // expected-error {{use of 'self' in property access 'ivar' before self.init initializes self}}
self.init()
}
convenience init(x: EmptyStruct, y: EmptyStruct, z: EmptyStruct) {
self.init()
self.init() // expected-error {{self.init called multiple times in initializer}}
}
convenience init(x: (EmptyStruct, EmptyStruct)) {
method() // expected-error {{use of 'self' in method call 'method' before self.init initializes self}}
self.init()
}
convenience init(c : Bool) {
if c {
return
}
self.init()
} // expected-error {{self.init isn't called on all paths before returning from initializer}}
convenience init(bool: Bool) {
doesNotReturn()
}
convenience init(double: Double) {
} // expected-error{{self.init isn't called on all paths before returning from initializer}}
func method() {}
}
struct DelegatingCtorStruct {
var ivar : EmptyStruct
init() { ivar = EmptyStruct() }
init(a : Double) {
self.init()
_ = ivar // okay: ivar has been initialized by the delegation above
}
init(a : Int) {
_ = ivar // expected-error {{'self' used before self.init call}}
self.init()
}
init(a : Float) {
self.init()
self.init() // expected-error {{self.init called multiple times in initializer}}
}
init(c : Bool) {
if c {
return
}
self.init()
} // expected-error {{self.init isn't called on all paths before returning from initializer}}
}
enum DelegatingCtorEnum {
case Dinosaur, Train, Truck
init() { self = .Train }
init(a : Double) {
self.init()
_ = self // okay: self has been initialized by the delegation above
self = .Dinosaur
}
init(a : Int) {
_ = self // expected-error {{'self' used before self.init call}}
self.init()
}
init(a : Float) {
self.init()
self.init() // expected-error {{self.init called multiple times in initializer}}
}
init(c : Bool) {
if c {
return
}
self.init()
} // expected-error {{self.init isn't called on all paths before returning from initializer}}
}
//===----------------------------------------------------------------------===//
// Delegating initializers vs extensions
//===----------------------------------------------------------------------===//
protocol TriviallyConstructible {
init()
func go(_ x: Int)
}
extension TriviallyConstructible {
init(down: Int) {
go(down) // expected-error {{'self' used before self.init call}}
self.init()
}
}
//===----------------------------------------------------------------------===//
// Various bugs
//===----------------------------------------------------------------------===//
// rdar://16119509 - Dataflow problem where we reject valid code.
class rdar16119509_Buffer {
init(x : Int) { }
}
class rdar16119509_Base {}
class rdar16119509_Derived : rdar16119509_Base {
override init() {
var capacity = 2
while capacity < 2 {
capacity <<= 1
}
buffer = rdar16119509_Buffer(x: capacity)
}
var buffer : rdar16119509_Buffer
}
// <rdar://problem/16797372> Bogus error: self.init called multiple times in initializer
extension Foo {
convenience init() {
for _ in 0..<42 {
}
self.init(a: 4)
}
}
class Foo {
init(a : Int) {}
}
func doesNotReturn() -> Never {
while true {}
}
func doesReturn() {}
func testNoReturn1(_ b : Bool) -> Any {
var a : Any
if b {
a = 42
} else {
doesNotReturn()
}
return a // Ok, because the noreturn call path isn't viable.
}
func testNoReturn2(_ b : Bool) -> Any {
var a : Any // expected-note {{variable defined here}}
if b {
a = 42
} else {
doesReturn()
}
// Not ok, since doesReturn() doesn't kill control flow.
return a // expected-error {{variable 'a' used before being initialized}}
}
class PerpetualMotion {
func start() -> Never {
repeat {} while true
}
static func stop() -> Never {
repeat {} while true
}
}
func testNoReturn3(_ b : Bool) -> Any {
let a : Int
switch b {
default:
PerpetualMotion().start()
}
return a
}
func testNoReturn4(_ b : Bool) -> Any {
let a : Int
switch b {
default:
PerpetualMotion.stop()
}
return a
}
// <rdar://problem/16687555> [DI] New convenience initializers cannot call inherited convenience initializers
class BaseWithConvenienceInits {
init(int: Int) {}
convenience init() {
self.init(int: 3)
}
}
class DerivedUsingConvenienceInits : BaseWithConvenienceInits {
convenience init(string: String) {
self.init()
}
}
// <rdar://problem/16660680> QoI: _preconditionFailure() in init method complains about super.init being called multiple times
class ClassWhoseInitDoesntReturn : BaseWithConvenienceInits {
init() {
_preconditionFailure("leave me alone dude");
}
}
// <rdar://problem/17233681> DI: Incorrectly diagnostic in delegating init with generic enum
enum r17233681Lazy<T> {
case Thunk(() -> T)
case Value(T)
init(value: T) {
self = .Value(value)
}
}
extension r17233681Lazy {
init(otherValue: T) {
self.init(value: otherValue)
}
}
// <rdar://problem/17556858> delegating init that delegates to @_transparent init fails
struct FortyTwo { }
extension Double {
init(v : FortyTwo) {
self.init(0.0)
}
}
// <rdar://problem/17686667> If super.init is implicitly inserted, DI diagnostics have no location info
class r17686667Base {}
class r17686667Test : r17686667Base {
var x: Int
override init() { // expected-error {{property 'self.x' not initialized at implicitly generated super.init call}}
}
}
// <rdar://problem/18199087> DI doesn't catch use of super properties lexically inside super.init call
class r18199087BaseClass {
let data: Int
init(val: Int) {
data = val
}
}
class r18199087SubClassA: r18199087BaseClass {
init() {
super.init(val: self.data) // expected-error {{use of 'self' in property access 'data' before super.init initializes self}}
}
}
// <rdar://problem/18414728> QoI: DI should talk about "implicit use of self" instead of individual properties in some cases
class rdar18414728Base {
var prop:String? { return "boo" }
// expected-note @+1 {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
let aaaaa:String // expected-note 3 {{'self.aaaaa' not initialized}}
init() {
if let p1 = prop { // expected-error {{use of 'self' in property access 'prop' before all stored properties are initialized}}
aaaaa = p1
}
aaaaa = "foo" // expected-error {{immutable value 'self.aaaaa' may only be initialized once}}
}
init(a : ()) {
method1(42) // expected-error {{use of 'self' in method call 'method1' before all stored properties are initialized}}
aaaaa = "foo"
}
init(b : ()) {
final_method() // expected-error {{use of 'self' in method call 'final_method' before all stored properties are initialized}}
aaaaa = "foo"
}
init(c : ()) {
aaaaa = "foo"
final_method() // ok
}
func method1(_ a : Int) {}
final func final_method() {}
}
class rdar18414728Derived : rdar18414728Base {
var prop2:String? { return "boo" }
// expected-note @+1 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}}
let aaaaa2:String
override init() {
if let p1 = prop2 { // expected-error {{use of 'self' in property access 'prop2' before super.init initializes self}}
aaaaa2 = p1
}
aaaaa2 = "foo" // expected-error {{immutable value 'self.aaaaa2' may only be initialized once}}
super.init()
}
override init(a : ()) {
method2() // expected-error {{use of 'self' in method call 'method2' before super.init initializes self}}
aaaaa2 = "foo"
super.init()
}
override init(b : ()) {
aaaaa2 = "foo"
method2() // expected-error {{use of 'self' in method call 'method2' before super.init initializes self}}
super.init()
}
override init(c : ()) {
super.init() // expected-error {{property 'self.aaaaa2' not initialized at super.init call}}
aaaaa2 = "foo" // expected-error {{immutable value 'self.aaaaa2' may only be initialized once}}
method2()
}
func method2() {}
}
struct rdar18414728Struct {
var computed:Int? { return 4 }
var i : Int // expected-note 2 {{'self.i' not initialized}}
var j : Int // expected-note {{'self.j' not initialized}}
init() {
j = 42
if let p1 = computed { // expected-error {{'self' used before all stored properties are initialized}}
i = p1
}
i = 1
}
init(a : ()) {
method(42) // expected-error {{'self' used before all stored properties are initialized}}
i = 1
j = 2
}
func method(_ a : Int) {}
}
extension Int {
mutating func mutate() {}
func inspect() {}
}
// <rdar://problem/19035287> let properties should only be initializable, not reassignable
struct LetProperties {
// expected-note @+1 {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
let arr : [Int]
// expected-note @+1 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}}
let (u, v) : (Int, Int)
// expected-note @+1 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}}
let w : (Int, Int)
let x = 42
// expected-note @+1 {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
let y : Int
let z : Int? // expected-note{{'self.z' not initialized}}
// Let properties can be initialized naturally exactly once along any given
// path through an initializer.
init(cond : Bool) {
if cond {
w.0 = 4
(u,v) = (4,2)
y = 71
} else {
y = 13
v = 2
u = v+1
w.0 = 7
}
w.1 = 19
z = nil
arr = []
}
// Multiple initializations are an error.
init(a : Int) {
y = a
y = a // expected-error {{immutable value 'self.y' may only be initialized once}}
u = a
v = a
u = a // expected-error {{immutable value 'self.u' may only be initialized once}}
v = a // expected-error {{immutable value 'self.v' may only be initialized once}}
w.0 = a
w.1 = a
w.0 = a // expected-error {{immutable value 'self.w.0' may only be initialized once}}
w.1 = a // expected-error {{immutable value 'self.w.1' may only be initialized once}}
arr = []
arr = [] // expected-error {{immutable value 'self.arr' may only be initialized once}}
} // expected-error {{return from initializer without initializing all stored properties}}
// inout uses of let properties are an error.
init() {
u = 1; v = 13; w = (1,2); y = 1 ; z = u
var variable = 42
swap(&u, &variable) // expected-error {{immutable value 'self.u' may not be passed inout}}
u.inspect() // ok, non mutating.
u.mutate() // expected-error {{mutating method 'mutate' may not be used on immutable value 'self.u'}}
arr = []
arr += [] // expected-error {{mutating operator '+=' may not be used on immutable value 'self.arr'}}
arr.append(4) // expected-error {{mutating method 'append' may not be used on immutable value 'self.arr'}}
arr[12] = 17 // expected-error {{mutating subscript 'subscript' may not be used on immutable value 'self.arr'}}
}
}
// <rdar://problem/19215313> let properties don't work with protocol method dispatch
protocol TestMutabilityProtocol {
func toIntMax()
mutating func changeToIntMax()
}
class C<T : TestMutabilityProtocol> {
let x : T
let y : T
init(a : T) {
x = a; y = a
x.toIntMax()
y.changeToIntMax() // expected-error {{mutating method 'changeToIntMax' may not be used on immutable value 'self.y'}}
}
}
struct MyMutabilityImplementation : TestMutabilityProtocol {
func toIntMax() {
}
mutating func changeToIntMax() {
}
}
// <rdar://problem/16181314> don't require immediate initialization of 'let' values
func testLocalProperties(_ b : Int) -> Int {
// expected-note @+1 {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
let x : Int
let y : Int // never assigned is ok expected-warning {{immutable value 'y' was never used}} {{7-8=_}}
x = b
x = b // expected-error {{immutable value 'x' may only be initialized once}}
// This is ok, since it is assigned multiple times on different paths.
let z : Int
if true || false {
z = b
} else {
z = b
}
_ = z
return x
}
// Should be rejected as multiple assignment.
func testAddressOnlyProperty<T>(_ b : T) -> T {
// expected-note @+1 {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
let x : T
let y : T
let z : T // never assigned is ok. expected-warning {{immutable value 'z' was never used}} {{7-8=_}}
x = b
y = b
x = b // expected-error {{immutable value 'x' may only be initialized once}}
var tmp = b
swap(&x, &tmp) // expected-error {{immutable value 'x' may not be passed inout}}
return y
}
// <rdar://problem/19254812> DI bug when referencing let member of a class
class r19254812Base {}
class r19254812Derived: r19254812Base{
let pi = 3.14159265359
init(x : ()) {
markUsed(pi) // ok, no diagnostic expected.
}
}
// <rdar://problem/19259730> Using mutating methods in a struct initializer with a let property is rejected
struct StructMutatingMethodTest {
let a, b: String // expected-note 2 {{'self.b' not initialized}}
init(x: String, y: String) {
a = x
b = y
mutate() // ok
}
init(x: String) {
a = x
mutate() // expected-error {{'self' used before all stored properties are initialized}}
b = x
}
init() {
a = ""
nonmutate() // expected-error {{'self' used before all stored properties are initialized}}
b = ""
}
mutating func mutate() {}
func nonmutate() {}
}
// <rdar://problem/19268443> DI should reject this call to transparent function
class TransparentFunction {
let x : Int
let y : Int
init() {
x = 42
x += 1 // expected-error {{mutating operator '+=' may not be used on immutable value 'self.x'}}
y = 12
myTransparentFunction(&y) // expected-error {{immutable value 'self.y' may not be passed inout}}
}
}
@_transparent
func myTransparentFunction(_ x : inout Int) {}
// <rdar://problem/19782264> Immutable, optional class members can't have their subproperties read from during init()
class MyClassWithAnInt {
let channelCount : Int = 42
}
class MyClassTestExample {
let clientFormat : MyClassWithAnInt!
init(){
clientFormat = MyClassWithAnInt()
_ = clientFormat.channelCount
}
}
// <rdar://problem/19746552> QoI: variable "used before being initialized" instead of "returned uninitialized" in address-only enum/struct
struct AddressOnlyStructWithInit<T, U> {
let a : T?
let b : U? // expected-note {{'self.b' not initialized}}
init(a : T) {
self.a = a
} // expected-error {{return from initializer without initializing all stored properties}}
}
enum AddressOnlyEnumWithInit<T> {
case X(T), Y
init() {
} // expected-error {{return from enum initializer method without storing to 'self'}}
}
// <rdar://problem/20135113> QoI: enum failable init that doesn't assign to self produces poor error
enum MyAwesomeEnum {
case One, Two
init?() {
}// expected-error {{return from enum initializer method without storing to 'self'}}
}
// <rdar://problem/20679379> DI crashes on initializers on protocol extensions
extension SomeProtocol {
init?() {
let a = self // expected-error {{variable 'self' used before being initialized}}
self = a
}
init(a : Int) {
} // expected-error {{protocol extension initializer never chained to 'self.init'}}
init(c : Float) {
protoMe() // expected-error {{variable 'self' used before being initialized}}
} // expected-error {{protocol extension initializer never chained to 'self.init'}}
}
// Lvalue check when the archetypes are not the same.
struct LValueCheck<T> {
// expected-note @+1 {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
let x = 0 // expected-note {{initial value already provided in 'let' declaration}}
}
extension LValueCheck {
init(newY: Int) {
x = 42 // expected-error {{immutable value 'self.x' may only be initialized once}}
}
}
// <rdar://problem/20477982> Accessing let-property with default value in init() can throw spurious error
struct DontLoadFullStruct {
let x: Int = 1
let y: Int
init() {
y = x // ok!
}
}
func testReassignment() {
let c : Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}}
c = 12
c = 32 // expected-error {{immutable value 'c' may only be initialized once}}
_ = c
}
// <rdar://problem/21295093> Swift protocol cannot implement default initializer
protocol ProtocolInitTest {
init()
init(a : Int)
var i: Int { get set }
}
extension ProtocolInitTest {
init() {
} // expected-error {{protocol extension initializer never chained to 'self.init'}}
init(b : Float) {
self.init(a: 42) // ok
}
// <rdar://problem/21684596> QoI: Poor DI diagnostic in protocol extension initializer
init(test1 ii: Int) {
i = ii // expected-error {{'self' used before self.init call}}
self.init()
}
init(test2 ii: Int) {
self = unsafeBitCast(0, to: Self.self)
i = ii
}
init(test3 ii: Int) {
i = ii // expected-error {{'self' used before chaining to another self.init requirement}}
self = unsafeBitCast(0, to: Self.self)
}
init(test4 ii: Int) {
i = ii // expected-error {{'self' used before chaining to another self.init requirement}}
} // expected-error {{protocol extension initializer never chained to 'self.init'}}
}
// <rdar://problem/22436880> Function accepting UnsafeMutablePointer is able to change value of immutable value
func bug22436880(_ x: UnsafeMutablePointer<Int>) {}
func test22436880() {
let x: Int
x = 1
bug22436880(&x) // expected-error {{immutable value 'x' may not be passed inout}}
}
// sr-184
let x: String? // expected-note 2 {{constant defined here}}
print(x?.characters.count as Any) // expected-error {{constant 'x' used before being initialized}}
print(x!) // expected-error {{constant 'x' used before being initialized}}
// <rdar://problem/22723281> QoI: [DI] Misleading error from Swift compiler when using an instance method in init()
protocol PMI {
func getg()
}
extension PMI {
func getg() {}
}
class WS: PMI {
final let x: String // expected-note {{'self.x' not initialized}}
init() {
getg() // expected-error {{use of 'self' in method call 'getg' before all stored properties are initialized}}
self.x = "foo"
}
}
// <rdar://problem/23013334> DI QoI: Diagnostic claims that property is being used when it actually isn't
class r23013334 {
var B: Int // expected-note {{'self.B' not initialized}}
var A: String
init(A: String) throws {
self.A = A
self.A.withCString { cString -> () in // expected-error {{'self' captured by a closure before all members were initialized}}
print(self.A)
return ()
}
self.B = 0
}
}
class r23013334Derived : rdar16119509_Base {
var B: Int // expected-note {{'self.B' not initialized}}
var A: String
init(A: String) throws {
self.A = A
self.A.withCString { cString -> () in // expected-error {{'self' captured by a closure before all members were initialized}}
print(self.A)
return ()
}
self.B = 0
}
}
// sr-1469
struct SR1469_Struct1 {
let a: Int
let b: Int // expected-note {{'self.b' not initialized}}
init?(x: Int, y: Int) {
self.a = x
if y == 42 {
return // expected-error {{return from initializer without initializing all stored properties}}
}
// many lines later
self.b = y
}
}
struct SR1469_Struct2 {
let a: Int
let b: Int // expected-note {{'self.b' not initialized}}
init?(x: Int, y: Int) {
self.a = x
return // expected-error {{return from initializer without initializing all stored properties}}
}
}
struct SR1469_Struct3 {
let a: Int
let b: Int // expected-note {{'self.b' not initialized}}
init?(x: Int, y: Int) {
self.a = x
if y == 42 {
self.b = y
return
}
} // expected-error {{return from initializer without initializing all stored properties}}
}
enum SR1469_Enum1 {
case A, B
init?(x: Int) {
if x == 42 {
return // expected-error {{return from enum initializer method without storing to 'self'}}
}
// many lines later
self = .A
}
}
enum SR1469_Enum2 {
case A, B
init?() {
return // expected-error {{return from enum initializer method without storing to 'self'}}
}
}
enum SR1469_Enum3 {
case A, B
init?(x: Int) {
if x == 42 {
self = .A
return
}
} // expected-error {{return from enum initializer method without storing to 'self'}}
}
| apache-2.0 |
thomas-mcdonald/SoundTop | SoundTop/STTrack.swift | 1 | 2813 | // STTrack.swift
//
// Copyright (c) 2015 Thomas McDonald
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer. Redistributions in binary
// form must reproduce the above copyright notice, this list of conditions and
// the following disclaimer in the documentation and/or other materials
// provided with the distribution. Neither the name of the nor the names of
// its contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
import AVFoundation
import Cocoa
class STTrack: NSObject, NSCopying {
var artworkURL : NSString?
var title : NSString?
var artist : NSString?
var streamURL : NSString?
private var clientStreamURL : NSString {
get {
return (self.streamURL! as String) + "?client_id=027aa73b22641da241a74cfdd3c5210b"
}
}
var largeAlbumArt : NSString? {
get {
return self.artworkURL?.stringByReplacingOccurrencesOfString("large", withString: "t500x500")
}
}
var badgeAlbumArt: NSString? {
get {
return self.artworkURL?.stringByReplacingOccurrencesOfString("large", withString: "t300x300")
}
}
init(title : NSString?, artist : NSString?, artworkURL: NSString?, streamURL: NSString?) {
self.artworkURL = artworkURL
self.title = title
self.artist = artist
self.streamURL = streamURL
}
func playerItem() -> AVPlayerItem {
let url = NSURL(string: clientStreamURL as String)!
let asset = AVAsset.init(URL: url)
return AVPlayerItem.init(asset: asset)
}
func copyWithZone(zone: NSZone) -> AnyObject {
return STTrack(title: title, artist: artist, artworkURL: artworkURL, streamURL: streamURL)
}
}
| bsd-3-clause |
Bersaelor/SwiftyHYGDB | Sources/SwiftyHYGDB/Indexer.swift | 1 | 1070 | //
// ValueIndexer.swift
// SwiftyHYGDB
//
// Created by Konrad Feiler on 01.10.17.
//
import Foundation
protocol IndexerValue: Hashable {
func isValid() -> Bool
}
struct Indexer<Value: IndexerValue> {
private var collectedValues = [Value: Int16]()
mutating func index(for value: Value?) -> Int16 {
guard let value = value, value.isValid() else { return Int16(SwiftyHYGDB.missingValueIndex) }
if let existingValueNr = collectedValues[value] {
return existingValueNr
} else {
let spectralTypeNr = Int16(collectedValues.count)
collectedValues[value] = spectralTypeNr
return spectralTypeNr
}
}
func indexedValues() -> [Value] {
return collectedValues.sorted(by: { (a, b) -> Bool in
return a.value < b.value
}).map { $0.key }
}
}
extension Indexer {
init(existingValues: [Value]) {
for (key, value) in existingValues.enumerated().map({ ($1, Int16($0)) }) {
collectedValues[key] = value
}
}
}
| mit |
Lasithih/LIHAlert | Pod/Classes/LIHAlertManager.swift | 1 | 7020 | //
// LIHAlertManager.swift
// LIHAlert
//
// Created by Lasith Hettiarachchi on 10/15/15.
// Copyright © 2015 Lasith Hettiarachchi. All rights reserved.
//
import Foundation
import UIKit
@objc open class LIHAlertManager: NSObject {
open class func getTextAlert(message: String) -> LIHAlert {
let alertTextAlert: LIHAlert = LIHAlert()
alertTextAlert.alertType = LIHAlertType.text
alertTextAlert.contentText = message
alertTextAlert.alertColor = UIColor(red: 102.0/255.0, green: 197.0/255.0, blue: 241.0/255.0, alpha: 1.0)
alertTextAlert.alertHeight = 50.0
alertTextAlert.alertAlpha = 1.0
alertTextAlert.autoCloseEnabled=true
alertTextAlert.contentTextColor = UIColor.white
alertTextAlert.hasNavigationBar = true
alertTextAlert.paddingTop = 0.0
alertTextAlert.animationDuration = 0.35
alertTextAlert.autoCloseTimeInterval = 1.5
return alertTextAlert
}
open class func getTextWithTitleAlert(title: String, message:String) -> LIHAlert {
let alertTextAlert: LIHAlert = LIHAlert()
alertTextAlert.alertType = LIHAlertType.textWithTitle
alertTextAlert.contentText = message
alertTextAlert.titleText = title
alertTextAlert.contentTextFont = UIFont.systemFont(ofSize: 15)
alertTextAlert.alertColor = UIColor.orange
alertTextAlert.alertHeight = 85.0
alertTextAlert.alertAlpha = 1.0
alertTextAlert.autoCloseEnabled=true
alertTextAlert.contentTextColor = UIColor.white
alertTextAlert.titleTextColor = UIColor.white
alertTextAlert.hasNavigationBar = true
alertTextAlert.paddingTop = 0.0
alertTextAlert.animationDuration = 0.35
alertTextAlert.autoCloseTimeInterval = 2.5
return alertTextAlert
}
open class func getProcessingAlert(message: String) -> LIHAlert {
let processingAlert: LIHAlert = LIHAlert()
processingAlert.alertType = LIHAlertType.textWithLoading
processingAlert.contentText = message
processingAlert.alertColor = UIColor.gray
processingAlert.alertHeight = 50.0
processingAlert.alertAlpha = 1.0
processingAlert.autoCloseEnabled=false
processingAlert.contentTextColor = UIColor.white
processingAlert.hasNavigationBar = true
processingAlert.paddingTop = 0.0
processingAlert.animationDuration = 0.35
processingAlert.autoCloseTimeInterval = 2.5
return processingAlert
}
open class func getCustomViewAlert(customView: UIView) -> LIHAlert {
let customViewAlert: LIHAlert = LIHAlert()
customViewAlert.alertType = LIHAlertType.custom
customViewAlert.alertView = customView
customViewAlert.autoCloseEnabled=true
customViewAlert.hasNavigationBar = true
customViewAlert.animationDuration = 0.35
customViewAlert.autoCloseTimeInterval = 2.5
return customViewAlert
}
open class func getSuccessAlert(message: String) -> LIHAlert {
let successAlert: LIHAlert = LIHAlert()
successAlert.alertType = LIHAlertType.textWithIcon
successAlert.icon = UIImage(named: "SuccessIcon")
successAlert.contentText = message
successAlert.alertColor = UIColor(red: 17.0/255.0, green: 201.0/255.0, blue: 3.0/255.0, alpha: 1.0)
successAlert.alertHeight = 70.0
successAlert.alertAlpha = 1.0
successAlert.autoCloseEnabled=true
successAlert.contentTextColor = UIColor.white
successAlert.hasNavigationBar = true
successAlert.paddingTop = 0.0
successAlert.animationDuration = 0.35
successAlert.autoCloseTimeInterval = 2.5
return successAlert
}
open class func getErrorAlert(message: String) -> LIHAlert {
let errorAlert: LIHAlert = LIHAlert()
errorAlert.alertType = LIHAlertType.textWithIcon
errorAlert.icon = UIImage(named: "ErrorIcon")
errorAlert.contentText = message
errorAlert.alertColor = UIColor(red: 201.0/255.0, green: 3.0/255.0, blue: 3.0/255.0, alpha: 1.0)
errorAlert.alertHeight = 70.0
errorAlert.alertAlpha = 1.0
errorAlert.autoCloseEnabled=true
errorAlert.contentTextColor = UIColor.white
errorAlert.hasNavigationBar = true
errorAlert.paddingTop = 0.0
errorAlert.animationDuration = 0.35
errorAlert.autoCloseTimeInterval = 2.5
return errorAlert
}
open class func getTextWithButtonAlert(message: String, buttonText: String) -> LIHAlert {
let textWithButtonAlert: LIHAlert = LIHAlert()
textWithButtonAlert.alertType = LIHAlertType.textWithButton
textWithButtonAlert.contentText = message
textWithButtonAlert.buttonText = buttonText
textWithButtonAlert.buttonColor = UIColor(red: 22.0/255.0, green: 40.0/255.0, blue: 114.0/255.0, alpha: 1.0)
textWithButtonAlert.buttonWidth = 620.0
textWithButtonAlert.alertColor = UIColor(red: 22.0/255.0, green: 40.0/255.0, blue: 114.0/255.0, alpha: 1.0)
textWithButtonAlert.alertHeight = 130.0
textWithButtonAlert.alertAlpha = 1.0
textWithButtonAlert.autoCloseEnabled=false
textWithButtonAlert.contentTextColor = UIColor.white
textWithButtonAlert.hasNavigationBar = true
textWithButtonAlert.paddingTop = 0.0
textWithButtonAlert.animationDuration = 0.35
textWithButtonAlert.autoCloseTimeInterval = 2.5
return textWithButtonAlert
}
open class func getTextWithTwoButtonsAlert(message: String, buttonOneText: String, buttonTwoText: String) -> LIHAlert {
let textWithButtonsAlert: LIHAlert = LIHAlert()
textWithButtonsAlert.alertType = LIHAlertType.textWithTwoButtons
textWithButtonsAlert.contentText = message
textWithButtonsAlert.alertColor = UIColor(red: 22.0/255.0, green: 40.0/255.0, blue: 114.0/255.0, alpha: 1.0)
textWithButtonsAlert.buttonOneText = buttonOneText
textWithButtonsAlert.buttonOneColor = UIColor(red: 22.0/255.0, green: 40.0/255.0, blue: 114.0/255.0, alpha: 1.0)
textWithButtonsAlert.buttonTwoText = buttonTwoText
textWithButtonsAlert.buttonTwoColor = UIColor(red: 22.0/255.0, green: 40.0/255.0, blue: 114.0/255.0, alpha: 1.0)
textWithButtonsAlert.alertHeight = 130.0
textWithButtonsAlert.alertAlpha = 1.0
textWithButtonsAlert.autoCloseEnabled=false
textWithButtonsAlert.contentTextColor = UIColor.white
textWithButtonsAlert.hasNavigationBar = true
textWithButtonsAlert.paddingTop = 0.0
textWithButtonsAlert.animationDuration = 0.35
textWithButtonsAlert.autoCloseTimeInterval = 2.5
return textWithButtonsAlert
}
}
| mit |
mafmoff/RxRSSFeed | RxRSSFeed/Const/Const.swift | 2 | 446 | //
// Const.swift
// MAF-SwiftCompe
//
// Created by SaikaYamamoto on 2015/09/23.
// Copyright (c) 2015年 SaikaYamamoto. All rights reserved.
//
import UIKit
/*
* Const
*/
/// googleajaxfeed Path
let GOOGLE_FEED_PATH = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q="
/// Theme Color
let THEME_COLOR = UIColor.colorWithHex("FB5363", alpha: 1.0)
/// Point Color
let POINT_COLOR = UIColor.colorWithHex("929292", alpha: 1.0)
| mit |
fiveagency/ios-five-utils | Sources/Lerpable.swift | 1 | 885 | //
// Lerpable.swift
// FiveUtils
//
// Created by Miran Brajsa on 16/09/16.
// Copyright © 2016 Five Agency. All rights reserved.
//
import CoreGraphics
import Foundation
public protocol Lerpable {
static func +(lhs: Self, rhs: Self) -> Self
static func -(lhs: Self, rhs: Self) -> Self
func scale(by value: CGFloat) -> Self
}
extension CGFloat: Lerpable {
public func scale(by value: CGFloat) -> CGFloat {
return self * value
}
}
extension Double: Lerpable {
public func scale(by value: CGFloat) -> Double {
return Double(CGFloat(self) * value)
}
}
extension Float: Lerpable {
public func scale(by value: CGFloat) -> Float {
return Float(CGFloat(self) * value)
}
}
extension Int: Lerpable {
public func scale(by value: CGFloat) -> Int {
return Int(CGFloat(self) * value)
}
}
| mit |
midoks/Swift-Learning | GitHubStar/GitHubStar/GitHubStar/Controllers/common/base/GsHomeViewController.swift | 1 | 7804 | //
// GsHomeViewController.swift
// GitHubStar
//
// Created by midoks on 16/4/5.
// Copyright © 2016年 midoks. All rights reserved.
//
import UIKit
class GsHomeViewController: UIViewController {
var _tableView: UITableView?
var _refresh = UIRefreshControl()
var _headView = GsHomeHeadView()
var _backView = UIView()
var _tabBarH:CGFloat = 0
deinit {
print("deinit GsHomeViewController")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = false
self.resetView()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
self.navigationController?.navigationBar.shadowImage = nil
self.navigationController?.navigationBar.isTranslucent = true
}
override func viewDidLoad() {
super.viewDidLoad()
initTableView()
initTableHeadView()
initRefreshView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
private func initTableView(){
_tableView = UITableView(frame: self.view.frame, style: UITableViewStyle.grouped)
_tableView?.frame.size.height -= 64
_tableView?.dataSource = self
_tableView?.delegate = self
self.view.addSubview(_tableView!)
}
private func initRefreshView(){
_refresh.addTarget(self, action: #selector(self.refreshUrl), for: .valueChanged)
_refresh.tintColor = UIColor.white
_tableView!.addSubview(_refresh)
_tableView?.contentOffset.y -= 64
_refresh.beginRefreshing()
refreshUrl()
}
func startRefresh(){
_tableView?.contentOffset.y -= 64
_refresh.beginRefreshing()
}
func endRefresh(){
_refresh.endRefreshing()
}
private func initTableHeadView(){
_backView = UIView(frame: CGRect(x: 0, y: -self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height))
_backView.backgroundColor = UIColor.primaryColor()
_tableView?.addSubview(_backView)
_headView = GsHomeHeadView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 90))
_headView.backgroundColor = UIColor.primaryColor()
_headView.icon.backgroundColor = UIColor.white
_tableView?.tableHeaderView = _headView
}
func refreshUrl(){
_refresh.endRefreshing()
}
}
extension GsHomeViewController {
func getNavBarHeight() -> CGFloat {
return UIApplication.shared.statusBarFrame.height + (navigationController?.navigationBar.frame.height)!
}
func resetView(){
let root = self.getRootVC()
_tabBarH = self.getNavBarHeight()
let w = root.view.frame.width < root.view.frame.height
? root.view.frame.width : root.view.frame.height
let h = root.view.frame.height > root.view.frame.width
? root.view.frame.height : root.view.frame.width
if UIDevice.current.orientation.isPortrait {
_tableView?.frame = CGRect(x: 0, y: 0, width: w, height: h - _tabBarH)
} else if UIDevice.current.orientation.isLandscape {
_tableView?.frame = CGRect(x: 0, y: 0, width: h, height: w - _tabBarH)
}
_backView.frame = CGRect(x: 0, y: -root.view.frame.height, width: root.view.frame.width, height: root.view.frame.height)
}
}
extension GsHomeViewController {
func setAvatar(url:String){
self.asynTask {
self._headView.icon.MDCacheImage(url: url, defaultImage: "avatar_default")
}
}
func setName(name:String){
self.asynTask {
self._headView.name.text = name
let size = self._headView.getLabelSize(label: self._headView.name)
self._headView.name.frame.size.height = size.height
self._headView.frame.size.height = 90 + size.height + 5
self._tableView?.tableHeaderView = self._headView
}
}
func setDesc(desc:String){
self.asynTask {
self._headView.desc.text = desc
self._headView.desc.frame.origin.y = self._headView.frame.size.height
let size = self._headView.getLabelSize(label: self._headView.desc)
self._headView.frame.size.height = self._headView.frame.size.height + size.height + 5
self._tableView?.tableHeaderView = self._headView
}
}
func setStarStatus(status:Bool){
self.asynTask {
self._headView.addIconStar()
}
}
func removeStarStatus(){
self.asynTask {
self._headView.removeIconStar()
}
}
func setIconView(icon:[GsIconView]){
self.asynTask {
for i in self._headView.listIcon {
i.removeFromSuperview()
}
for i in self._headView.listLine {
i.removeFromSuperview()
}
self._headView.listIcon.removeAll()
self._headView.listLine.removeAll()
for i in icon {
self._headView.addIcon(icon: i)
}
self._headView.frame.size.height = self._headView.frame.size.height + 70
self._tableView?.tableHeaderView = self._headView
}
}
}
extension GsHomeViewController {
func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollView.contentOffset.y > 0 {
self.navigationController?.navigationBar.shadowImage = nil
} else {
self.navigationController?.navigationBar.shadowImage = UIImage()
}
}
}
extension GsHomeViewController{
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
_backView.frame = CGRect(x: 0, y: -size.height, width: size.width, height: size.height)
_tabBarH = self.getNavBarHeight()
if _tabBarH > 32 { //print("竖屏")
_tableView?.frame.size = CGSize(width: size.width, height: size.height + _tabBarH / 2)
} else { //print("横屏")
_tableView?.frame.size = CGSize(width: size.width, height: size.height - _tabBarH)
}
}
}
//Mark: - UITableViewDataSource && UITableViewDelegate -
extension GsHomeViewController:UITableViewDataSource, UITableViewDelegate {
private func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 0
}
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
cell.textLabel?.text = "home"
return cell
}
}
| apache-2.0 |
chashmeetsingh/Youtube-iOS | YouTube Demo/HomeController.swift | 1 | 6074 | //
// ViewController.swift
// YouTube Demo
//
// Created by Chashmeet Singh on 06/01/17.
// Copyright © 2017 Chashmeet Singh. All rights reserved.
//
import UIKit
class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let cellId = "cellId"
let trendingCellId = "trendingCellId"
let subscriptionCellId = "subscriptionCellId"
let titles = ["Home", "Trending", "Subscriptions", "Account"]
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.isTranslucent = false
let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.width - 32, height: view.frame.height))
titleLabel.text = " Home"
titleLabel.textColor = .white
titleLabel.font = UIFont.systemFont(ofSize: 20)
navigationItem.titleView = titleLabel
setupCollectionView()
setupMenuBar()
setupNavBarButtons()
}
func setupCollectionView() {
if let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.scrollDirection = .horizontal
flowLayout.minimumLineSpacing = 0
}
collectionView?.backgroundColor = .white
collectionView?.register(FeedCell.self, forCellWithReuseIdentifier: cellId)
collectionView?.register(TrendingCell.self, forCellWithReuseIdentifier: trendingCellId)
collectionView?.register(SubscriptionCell.self, forCellWithReuseIdentifier: subscriptionCellId)
collectionView?.contentInset = UIEdgeInsets(top: 50, left: 0, bottom: 0, right: 0)
collectionView?.scrollIndicatorInsets = UIEdgeInsets(top: 50, left: 0, bottom: 0, right: 0)
collectionView?.isPagingEnabled = true
}
lazy var menuBar: MenuBar = {
let menuBar = MenuBar()
menuBar.homeController = self
return menuBar
}()
private func setupMenuBar() {
navigationController?.hidesBarsOnSwipe = true
let redView = UIView()
redView.backgroundColor = UIColor.rgb(red: 230, green: 32, blue: 31)
view.addSubview(redView)
view.addConstraintsWithFormat(format: "H:|[v0]|", view: redView)
view.addConstraintsWithFormat(format: "V:[v0(50)]", view: redView)
view.addSubview(menuBar)
view.addConstraintsWithFormat(format: "H:|[v0]|", view: menuBar)
view.addConstraintsWithFormat(format: "V:[v0(50)]", view: menuBar)
menuBar.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
menuBar.horizontalbarLeftAnchorConstraint?.constant = scrollView.contentOffset.x / 4
}
private func setupNavBarButtons() {
let searchImage = UIImage(named: "search")?.withRenderingMode(.alwaysOriginal)
let searchBarButton = UIBarButtonItem(image: searchImage, style: .plain, target: self, action: #selector(handleSearch))
let settingsImage = UIImage(named: "settings")?.withRenderingMode(.alwaysOriginal)
let settingsBarButton = UIBarButtonItem(image: settingsImage, style: .plain, target: self, action: #selector(handleMore))
navigationItem.rightBarButtonItems = [settingsBarButton, searchBarButton]
}
func handleSearch() {
scrollToMenuIndex(menuIndex: 2)
}
func scrollToMenuIndex(menuIndex: Int) {
let indexPath = IndexPath(item: menuIndex, section: 0)
collectionView?.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
setTitleForIndex(index: menuIndex)
}
private func setTitleForIndex(index: Int) {
if let titleLabel = navigationItem.titleView as? UILabel {
titleLabel.text = " \(titles[index])"
}
}
lazy var settingsLauncher: SettingsLauncher = {
let vc = SettingsLauncher()
vc.homeController = self
return vc
}()
func handleMore() {
settingsLauncher.showSettings()
}
func showControllerForSetting(_ setting: Setting) {
let vc = UIViewController()
vc.navigationItem.title = setting.name.rawValue
vc.view.backgroundColor = .white
navigationController?.navigationBar.tintColor = .white
navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white]
self.navigationController?.pushViewController(vc, animated: true)
}
override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let index: Int = Int(targetContentOffset.pointee.x / view.frame.width)
let indexPath = IndexPath(item: index, section: 0)
menuBar.collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally)
setTitleForIndex(index: index)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let identifier: String
if indexPath.item == 1 {
identifier = trendingCellId
} else if indexPath.item == 2 {
identifier = subscriptionCellId
} else {
identifier = cellId
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! FeedCell
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: view.frame.height - 50)
}
}
| mit |
fernandomarins/food-drivr-pt | hackathon-for-hunger/MetaData.swift | 1 | 1134 | //
// MetaData.swift
// hackathon-for-hunger
//
// Created by Ian Gristock on 4/1/16.
// Copyright © 2016 Hacksmiths. All rights reserved.
//
import Foundation
import RealmSwift
import ObjectMapper
class MetaData: Object, Mappable {
typealias JsonDict = [String: AnyObject]
var images = List<Image>()
var donationDescription: String? = nil
convenience init(dict: JsonDict) {
self.init()
addImages(dict["images"] as? [JsonDict])
if let description = dict["description"] as? String {
donationDescription = description
}
}
func addImages(images: [JsonDict]?) {
if let newImages = images{
for newImage in newImages {
if let imageUrl = newImage["url"] {
self.images.append(Image(value: ["url": imageUrl]))
}
}
}
}
required convenience init?(_ map: Map) {
self.init()
}
func mapping(map: Map) {
donationDescription <- map["description"]
images <- (map["images"], ListTransform<Image>())
}
} | mit |
tomomura/TimeSheet | Classes/Controllers/Intros/FTIntrosCompleteViewController.swift | 1 | 2595 | //
// FTIntrosCompleteViewController.swift
// TimeSheet
//
// Created by TomomuraRyota on 2015/05/03.
// Copyright (c) 2015年 TomomuraRyota. All rights reserved.
//
import UIKit
class FTIntrosCompleteViewController: FTIntrosPageDataViewController {
@IBOutlet weak var completeButton: UIButton!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var statusImage: UIImageView!
// MARK: - View Life Cycles
override func viewDidLoad() {
super.viewDidLoad()
self.pageIndex = 2
self.descriptionLabel.text = "使う準備が整いました"
self.completeButton.setAttributedTitle(NSAttributedString(string: "時間の管理をはじめる"), forState: UIControlState.Normal)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if self.user!.name != nil && !self.user!.name!.isEmpty {
self.showCompleteMessages()
} else {
self.showNameEmptyMessages()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Helper Methods
/**
エラーメッセージを表示する
*/
func showNameEmptyMessages() {
self.statusImage.image = UIImage(named: "x-mark")
self.descriptionLabel.text = "名前が未入力です"
self.descriptionLabel.textColor = .redColor()
self.completeButton.hidden = true
}
/**
完了メッセージを表示する
*/
func showCompleteMessages() {
self.statusImage.image = UIImage(named: "complete")
self.descriptionLabel.text = "ようこそ「\(self.user!.name!)」さん\n使う準備が整いました"
self.descriptionLabel.textColor = .whiteColor()
self.completeButton.hidden = false
}
// MARK: - IBActions
/**
完了ボタンを押下した際に呼び出される
データを保存して、ダッシュボード画面へ遷移する
:param: sender <#sender description#>
*/
@IBAction func onClickComplete(sender: AnyObject) {
NSManagedObjectContext.MR_defaultContext().MR_saveToPersistentStoreWithCompletion { (result, error) -> Void in
let storyboard : UIStoryboard! = UIStoryboard(name: "Dashboards", bundle: nil)
let initialViewCtl = storyboard.instantiateInitialViewController() as! UIViewController
self.presentViewController(initialViewCtl, animated: true, completion: nil)
}
}
} | mit |
sora0077/APIKit | Sources/SessionAdapterType/NSURLSessionAdapter.swift | 1 | 3514 | import Foundation
extension URLSessionTask: SessionTaskType {
}
private var dataTaskResponseBufferKey = 0
private var taskAssociatedObjectCompletionHandlerKey = 0
/// `NSURLSessionAdapter` connects `URLSession` with `Session`.
///
/// If you want to add custom behavior of `URLSession` by implementing delegate methods defined in
/// `URLSessionDelegate` and related protocols, define a subclass of `NSURLSessionAdapter` and implment
/// delegate methods that you want to implement. Since `NSURLSessionAdapter` also implements delegate methods
/// `URLSession(_:task: didCompleteWithError:)` and `URLSession(_:dataTask:didReceiveData:)`, you have to call
/// `super` in these methods if you implement them.
public class NSURLSessionAdapter: NSObject, SessionAdapterType, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate {
/// The undelying `URLSession` instance.
public var URLSession: Foundation.URLSession!
/// Returns `NSURLSessionAdapter` initialized with `NSURLSessionConfiguration`.
public init(configuration: URLSessionConfiguration) {
super.init()
self.URLSession = Foundation.URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
}
/// Creates `URLSessionDataTask` instance using `dataTaskWithRequest(_:completionHandler:)`.
public func createTaskWithURLRequest(_ URLRequest: Foundation.URLRequest, handler: (Data?, URLResponse?, ErrorProtocol?) -> Void) -> SessionTaskType {
let task = URLSession.dataTask(with: URLRequest)
setBuffer(NSMutableData(), forTask: task)
setHandler(handler, forTask: task)
task.resume()
return task
}
/// Aggregates `URLSessionTask` instances in `URLSession` using `getTasksWithCompletionHandler(_:)`.
public func getTasksWithHandler(_ handler: ([SessionTaskType]) -> Void) {
URLSession.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in
let allTasks = dataTasks as [URLSessionTask]
+ uploadTasks as [URLSessionTask]
+ downloadTasks as [URLSessionTask]
handler(allTasks.map { $0 })
}
}
private func setBuffer(_ buffer: NSMutableData, forTask task: URLSessionTask) {
objc_setAssociatedObject(task, &dataTaskResponseBufferKey, buffer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
private func bufferForTask(_ task: URLSessionTask) -> NSMutableData? {
return objc_getAssociatedObject(task, &dataTaskResponseBufferKey) as? NSMutableData
}
private func setHandler(_ handler: (Data?, URLResponse?, NSError?) -> Void, forTask task: URLSessionTask) {
objc_setAssociatedObject(task, &taskAssociatedObjectCompletionHandlerKey, Box(handler), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
private func handlerForTask(_ task: URLSessionTask) -> ((Data?, URLResponse?, NSError?) -> Void)? {
return (objc_getAssociatedObject(task, &taskAssociatedObjectCompletionHandlerKey) as? Box<(Data?, URLResponse?, NSError?) -> Void>)?.value
}
// MARK: URLSessionTaskDelegate
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError connectionError: NSError?) {
handlerForTask(task)?(bufferForTask(task).map(Data.init), task.response, connectionError)
}
// MARK: URLSessionDataDelegate
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
bufferForTask(dataTask)?.append(data)
}
}
| mit |
andrewBatutin/tripmemories | TravelMemories/TravelMemories/AppDelegate.swift | 1 | 2157 | //
// AppDelegate.swift
// TravelMemories
//
// Created by Batutin, Andriy on 1/5/15.
// Copyright (c) 2015 Batutin, Andriy. All rights reserved.
//
import UIKit
@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:.
}
}
| mit |
whiteshadow-gr/HatForIOS | HAT/Objects/File Upload Object/HATFileUploadPermissions.swift | 1 | 1987 | /**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
import SwiftyJSON
// MARK: Struct
public struct HATFileUploadPermissions {
// MARK: - Coding Keys
/**
The JSON fields used by the hat
The Fields are the following:
* `userID` in JSON is `userID`
* `contentReadable` in JSON is `contentReadable`
*/
private enum CodingKeys: String, CodingKey {
case userID
case contentReadable
}
// MARK: - Variables
/// The user id that uploaded the file
public var userID: String = ""
/// Is the content readable
public var contentReadable: String = ""
// MARK: - Initialisers
/**
The default initialiser. Initialises everything to default values.
*/
public init() {
userID = ""
}
/**
It initialises everything from the received JSON file from the HAT
- dict: The JSON file received
*/
public init(from dict: Dictionary<String, JSON>) {
self.init()
if let tempUserID: String = dict["userID"]?.stringValue {
userID = tempUserID
}
if let tempContentReadable: String = dict["contentReadable"]?.stringValue {
contentReadable = tempContentReadable
}
}
// MARK: - JSON Mapper
/**
Returns the object as Dictionary, JSON
- returns: Dictionary<String, String>
*/
public func toJSON() -> Dictionary<String, Any> {
return [
"userID": self.userID,
"contentReadable": self.contentReadable,
"unixTimeStamp": Int(HATFormatterHelper.formatDateToEpoch(date: Date())!)!
]
}
}
| mpl-2.0 |
rene-dohan/CS-IOS | Renetik/Example/Renetik/ExampleAppDelegate.swift | 1 | 2208 | //
// AppDelegate.swift
// Renetik
//
// Created by rene-dohan on 02/19/2019.
// Copyright (c) 2019 rene-dohan. All rights reserved.
//
import RenetikObjc
import Renetik
@UIApplicationMain
class ExampleAppDelegate: CSAppDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
DDLog.add(DDTTYLogger.sharedInstance)
DDLog.add(DDASLLogger.sharedInstance)
setup(CocoaLumberjackCSLogger(), CSNavigationController())
window = UIWindow()
window!.rootViewController = navigation
window!.makeKeyAndVisible()
Style.didFinishLaunchingWithOptions(self)
ExampleListController().push()
logInfo("ExampleAppDelegate didFinishLaunchingWithOptions")
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// 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:.
}
}
| mit |
azadibogolubov/InterestDestroyer | iOS Version/Interest Destroyer/Charts/Classes/Charts/RadarChartView.swift | 12 | 9293 | //
// RadarChartView.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
/// Implementation of the RadarChart, a "spidernet"-like chart. It works best
/// when displaying 5-10 entries per DataSet.
public class RadarChartView: PieRadarChartViewBase
{
/// width of the web lines that come from the center.
public var webLineWidth = CGFloat(1.5)
/// width of the web lines that are in between the lines coming from the center
public var innerWebLineWidth = CGFloat(0.75)
/// color for the web lines that come from the center
public var webColor = UIColor(red: 122/255.0, green: 122/255.0, blue: 122.0/255.0, alpha: 1.0)
/// color for the web lines in between the lines that come from the center.
public var innerWebColor = UIColor(red: 122/255.0, green: 122/255.0, blue: 122.0/255.0, alpha: 1.0)
/// transparency the grid is drawn with (0.0 - 1.0)
public var webAlpha: CGFloat = 150.0 / 255.0
/// flag indicating if the web lines should be drawn or not
public var drawWeb = true
/// modulus that determines how many labels and web-lines are skipped before the next is drawn
private var _webModulus = 1
/// the object reprsenting the y-axis labels
private var _yAxis: ChartYAxis!
/// the object representing the x-axis labels
private var _xAxis: ChartXAxis!
internal var _yAxisRenderer: ChartYAxisRendererRadarChart!
internal var _xAxisRenderer: ChartXAxisRendererRadarChart!
public override init(frame: CGRect)
{
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
internal override func initialize()
{
super.initialize()
_yAxis = ChartYAxis(position: .Left)
_xAxis = ChartXAxis()
_xAxis.spaceBetweenLabels = 0
renderer = RadarChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler)
_yAxisRenderer = ChartYAxisRendererRadarChart(viewPortHandler: _viewPortHandler, yAxis: _yAxis, chart: self)
_xAxisRenderer = ChartXAxisRendererRadarChart(viewPortHandler: _viewPortHandler, xAxis: _xAxis, chart: self)
}
internal override func calcMinMax()
{
super.calcMinMax()
let minLeft = _data.getYMin(.Left)
let maxLeft = _data.getYMax(.Left)
_chartXMax = Double(_data.xVals.count) - 1.0
_deltaX = CGFloat(abs(_chartXMax - _chartXMin))
let leftRange = CGFloat(abs(maxLeft - (_yAxis.isStartAtZeroEnabled ? 0.0 : minLeft)))
let topSpaceLeft = Double(leftRange * _yAxis.spaceTop)
let bottomSpaceLeft = Double(leftRange * _yAxis.spaceBottom)
// Consider sticking one of the edges of the axis to zero (0.0)
if _yAxis.isStartAtZeroEnabled
{
if minLeft < 0.0 && maxLeft < 0.0
{
// If the values are all negative, let's stay in the negative zone
_yAxis.axisMinimum = min(0.0, !isnan(_yAxis.customAxisMin) ? _yAxis.customAxisMin : (minLeft - bottomSpaceLeft))
_yAxis.axisMaximum = 0.0
}
else if minLeft >= 0.0
{
// We have positive values only, stay in the positive zone
_yAxis.axisMinimum = 0.0
_yAxis.axisMaximum = max(0.0, !isnan(_yAxis.customAxisMax) ? _yAxis.customAxisMax : (maxLeft + topSpaceLeft))
}
else
{
// Stick the minimum to 0.0 or less, and maximum to 0.0 or more (startAtZero for negative/positive at the same time)
_yAxis.axisMinimum = min(0.0, !isnan(_yAxis.customAxisMin) ? _yAxis.customAxisMin : (minLeft - bottomSpaceLeft))
_yAxis.axisMaximum = max(0.0, !isnan(_yAxis.customAxisMax) ? _yAxis.customAxisMax : (maxLeft + topSpaceLeft))
}
}
else
{
// Use the values as they are
_yAxis.axisMinimum = !isnan(_yAxis.customAxisMin) ? _yAxis.customAxisMin : (minLeft - bottomSpaceLeft)
_yAxis.axisMaximum = !isnan(_yAxis.customAxisMax) ? _yAxis.customAxisMax : (maxLeft + topSpaceLeft)
}
_chartXMax = Double(_data.xVals.count) - 1.0
_deltaX = CGFloat(abs(_chartXMax - _chartXMin))
_yAxis.axisRange = abs(_yAxis.axisMaximum - _yAxis.axisMinimum)
}
public override func getMarkerPosition(entry entry: ChartDataEntry, highlight: ChartHighlight) -> CGPoint
{
let angle = self.sliceAngle * CGFloat(entry.xIndex) + self.rotationAngle
let val = CGFloat(entry.value) * self.factor
let c = self.centerOffsets
let p = CGPoint(x: c.x + val * cos(angle * ChartUtils.Math.FDEG2RAD),
y: c.y + val * sin(angle * ChartUtils.Math.FDEG2RAD))
return p
}
public override func notifyDataSetChanged()
{
if (_dataNotSet)
{
return
}
calcMinMax()
_yAxis?._defaultValueFormatter = _defaultValueFormatter
_yAxisRenderer?.computeAxis(yMin: _yAxis.axisMinimum, yMax: _yAxis.axisMaximum)
_xAxisRenderer?.computeAxis(xValAverageLength: _data.xValAverageLength, xValues: _data.xVals)
if (_legend !== nil && !_legend.isLegendCustom)
{
_legendRenderer?.computeLegend(_data)
}
calculateOffsets()
setNeedsDisplay()
}
public override func drawRect(rect: CGRect)
{
super.drawRect(rect)
if (_dataNotSet)
{
return
}
let context = UIGraphicsGetCurrentContext()
_xAxisRenderer?.renderAxisLabels(context: context)
if (drawWeb)
{
renderer!.drawExtras(context: context)
}
_yAxisRenderer.renderLimitLines(context: context)
renderer!.drawData(context: context)
if (valuesToHighlight())
{
renderer!.drawHighlighted(context: context, indices: _indicesToHightlight)
}
_yAxisRenderer.renderAxisLabels(context: context)
renderer!.drawValues(context: context)
_legendRenderer.renderLegend(context: context)
drawDescription(context: context)
drawMarkers(context: context)
}
/// - returns: the factor that is needed to transform values into pixels.
public var factor: CGFloat
{
let content = _viewPortHandler.contentRect
return min(content.width / 2.0, content.height / 2.0)
/ CGFloat(_yAxis.axisRange)
}
/// - returns: the angle that each slice in the radar chart occupies.
public var sliceAngle: CGFloat
{
return 360.0 / CGFloat(_data.xValCount)
}
public override func indexForAngle(angle: CGFloat) -> Int
{
// take the current angle of the chart into consideration
let a = ChartUtils.normalizedAngleFromAngle(angle - self.rotationAngle)
let sliceAngle = self.sliceAngle
for (var i = 0; i < _data.xValCount; i++)
{
if (sliceAngle * CGFloat(i + 1) - sliceAngle / 2.0 > a)
{
return i
}
}
return 0
}
/// - returns: the object that represents all y-labels of the RadarChart.
public var yAxis: ChartYAxis
{
return _yAxis
}
/// - returns: the object that represents all x-labels that are placed around the RadarChart.
public var xAxis: ChartXAxis
{
return _xAxis
}
/// Sets the number of web-lines that should be skipped on chart web before the next one is drawn. This targets the lines that come from the center of the RadarChart.
/// if count = 1 -> 1 line is skipped in between
public var skipWebLineCount: Int
{
get
{
return _webModulus - 1
}
set
{
_webModulus = max(0, newValue) + 1
}
}
internal override var requiredBottomOffset: CGFloat
{
return _legend.font.pointSize * 4.0
}
internal override var requiredBaseOffset: CGFloat
{
return _xAxis.isEnabled && _xAxis.isDrawLabelsEnabled ? _xAxis.labelWidth : 10.0
}
public override var radius: CGFloat
{
let content = _viewPortHandler.contentRect
return min(content.width / 2.0, content.height / 2.0)
}
/// - returns: the maximum value this chart can display on it's y-axis.
public override var chartYMax: Double { return _yAxis.axisMaximum; }
/// - returns: the minimum value this chart can display on it's y-axis.
public override var chartYMin: Double { return _yAxis.axisMinimum; }
/// - returns: the range of y-values this chart can display.
public var yRange: Double { return _yAxis.axisRange}
} | apache-2.0 |
carabina/Lantern | LanternModel/PageInfo.swift | 1 | 10715 | //
// PageInfo.swift
// Hoverlytics
//
// Created by Patrick Smith on 28/04/2015.
// Copyright (c) 2015 Burnt Caramel. All rights reserved.
//
import Foundation
import Alamofire
import Ono
public enum BaseContentType {
case Unknown
case LocalHTMLPage
case Text
case Image
case Feed
case Redirect
case Essential
}
extension BaseContentType: DebugPrintable {
public var debugDescription: String {
switch self {
case .Unknown:
return "Unknown"
case .LocalHTMLPage:
return "LocalHTMLPage"
case .Text:
return "Text"
case .Image:
return "Image"
case .Feed:
return "Feed"
case .Redirect:
return "Redirect"
case .Essential:
return "Essential"
}
}
}
private typealias ONOXMLElementFilter = (element: ONOXMLElement) -> Bool
extension ONOXMLDocument {
private func allElementsWithCSS(selector: String, filter: ONOXMLElementFilter? = nil) -> [ONOXMLElement] {
var elements = [ONOXMLElement]()
self.enumerateElementsWithCSS(selector) { (element, index, stop) in
if filter?(element: element) == false {
return
}
elements.append(element)
}
return elements
}
}
public enum PageResponseType: Int {
case Successful = 2
case Redirects = 3
case RequestErrors = 4
case ResponseErrors = 5
case Unknown = 0
}
extension PageResponseType {
public init(statusCode: Int) {
switch statusCode {
case 200..<300:
self = .Successful
case 300..<400:
self = .Redirects
case 400..<500:
self = .RequestErrors
case 500..<600:
self = .ResponseErrors
default:
self = .Unknown
}
}
}
internal func URLIsExternal(URLToTest: NSURL, #localHost: String) -> Bool {
if let host = URLToTest.host {
if host.caseInsensitiveCompare(localHost) != .OrderedSame {
return true
}
}
return false
}
private let fileDownloadFileExtensions = Set<String>(["zip", "dmg", "exe", "pdf", "gz", "tar", "doc", "docx", "xls", "wav", "aiff", "mp3", "mp4", "mov", "avi", "wmv"])
func linkedURLLooksLikeFileDownload(URL: NSURL) -> Bool {
if let path = URL.path {
let pathExtension = path.pathExtension
if fileDownloadFileExtensions.contains(pathExtension) {
return true
}
}
return false
}
public struct MIMETypeString {
public let stringValue: String
}
extension MIMETypeString {
init?(_ stringValue: String?) {
if let stringValue = stringValue {
self.stringValue = stringValue
}
else {
return nil
}
}
var isHTML: Bool {
return stringValue == "text/html"
}
var isText: Bool {
return stringValue.hasPrefix("text/")
}
var isImage: Bool {
return stringValue.hasPrefix("image/")
}
private static let feedTypes = Set<String>(["application/rss+xml", "application/rdf+xml", "application/atom+xml", "application/xml", "text/xml"])
var isFeed: Bool {
let feedTypes = MIMETypeString.feedTypes
return feedTypes.contains(stringValue)
}
var baseContentType: BaseContentType {
if isHTML {
return .LocalHTMLPage
}
else if isText {
return .Text
}
else if isImage {
return .Image
}
else if isFeed {
return .Feed
}
else {
return .Unknown
}
}
}
extension MIMETypeString: Printable {
public var description: String {
return stringValue
}
}
struct PageContentInfoOptions {
var separateLinksToImageTypes = true
}
public struct PageContentInfo {
public let data: NSData
private let document: ONOXMLDocument!
let stringEncoding: NSStringEncoding!
public let preBodyByteCount: Int?
public let pageTitleElements: [ONOXMLElement]
public let metaDescriptionElements: [ONOXMLElement]
public let openGraphElements: [ONOXMLElement]
private let uniqueFeedURLs: UniqueURLArray
public var feedURLs: [NSURL] {
return uniqueFeedURLs.orderedURLs
}
public let feedLinkElements: [ONOXMLElement]
private let uniqueExternalPageURLs: UniqueURLArray
public var externalPageURLs: [NSURL] {
return uniqueExternalPageURLs.orderedURLs
}
public let aExternalLinkElements: [ONOXMLElement]
private let uniqueLocalPageURLs: UniqueURLArray
public var localPageURLs: [NSURL] {
return uniqueLocalPageURLs.orderedURLs
}
public func containsLocalPageURL(URL: NSURL) -> Bool {
return uniqueLocalPageURLs.contains(URL)
}
public let aLocalLinkElements: [ONOXMLElement]
public let imageURLs: Set<NSURL>
public func containsImageURL(URL: NSURL) -> Bool {
return imageURLs.contains(URL)
}
public let imageElements: [ONOXMLElement]
//public let stylesheetURLs: Set<NSURL>
//public let stylesheetElements: [ONOXMLElement]
public let h1Elements: [ONOXMLElement]
public let richSnippetElements: [ONOXMLElement]
init(data: NSData, localURL: NSURL, options: PageContentInfoOptions = PageContentInfoOptions()) {
self.data = data
var error: NSError?
if let document = ONOXMLDocument.HTMLDocumentWithData(data, error: &error) {
self.stringEncoding = document.stringEncodingWithFallback()
// Must store document to also save references to all found elements.
self.document = document
let stringEncoding = document.stringEncodingWithFallback()
if let bodyTagData = "<body".dataUsingEncoding(stringEncoding, allowLossyConversion: false) {
let bodyTagRange = data.rangeOfData(bodyTagData, options: .allZeros, range: NSMakeRange(0, data.length))
if bodyTagRange.location != NSNotFound {
preBodyByteCount = bodyTagRange.location
}
else {
preBodyByteCount = nil
}
}
else {
preBodyByteCount = nil
}
pageTitleElements = document.allElementsWithCSS("head title")
metaDescriptionElements = document.allElementsWithCSS("head meta[name][content]") { element in
if let name = element["name"] as? String {
return name.caseInsensitiveCompare("description") == .OrderedSame
}
return false
}
openGraphElements = document.allElementsWithCSS("head meta[property]") { element in
if let name = element["property"] as? String {
return name.rangeOfString("og:", options: .AnchoredSearch | .CaseInsensitiveSearch) != nil
}
return false
}
var uniqueFeedURLs = UniqueURLArray()
feedLinkElements = document.allElementsWithCSS("head link[type][href]") { element in
if
let typeRaw = element["type"] as? String,
let MIMEType = MIMETypeString(typeRaw.lowercaseString),
let linkURLString = element["href"] as? String,
let linkURL = NSURL(string: linkURLString, relativeToURL: localURL)
{
if MIMEType.isFeed {
uniqueFeedURLs.insertReturningConformedURLIfNew(linkURL)
return true
}
}
return false
}
self.uniqueFeedURLs = uniqueFeedURLs
let localHost = localURL.host!
let separateLinksToImageTypes = options.separateLinksToImageTypes
var aLocalLinkElements = [ONOXMLElement]()
var aExternalLinkElements = [ONOXMLElement]()
var uniqueLocalPageURLs = UniqueURLArray()
var uniqueExternalPageURLs = UniqueURLArray()
var imageElements = [ONOXMLElement]()
var imageURLs = Set<NSURL>()
document.enumerateElementsWithCSS("a[href]") { (aLinkElement, index, stop) in
if
let linkURLString = aLinkElement["href"] as? String,
let linkURL = NSURL(string: linkURLString, relativeToURL: localURL)
{
if separateLinksToImageTypes {
let hasImageType = [".jpg", ".jpeg", ".png", ".gif"].reduce(false, combine: { (hasSoFar, suffix) -> Bool in
return hasSoFar || linkURLString.hasSuffix(suffix)
})
if hasImageType {
imageElements.append(aLinkElement)
imageURLs.insert(linkURL)
return
}
}
let isExternal = URLIsExternal(linkURL, localHost: localHost)
if isExternal {
aExternalLinkElements.append(aLinkElement)
uniqueExternalPageURLs.insertReturningConformedURLIfNew(linkURL)
}
else {
aLocalLinkElements.append(aLinkElement)
uniqueLocalPageURLs.insertReturningConformedURLIfNew(linkURL)
}
}
}
self.aLocalLinkElements = aLocalLinkElements
self.aExternalLinkElements = aExternalLinkElements
self.uniqueLocalPageURLs = uniqueLocalPageURLs
self.uniqueExternalPageURLs = uniqueExternalPageURLs
document.enumerateElementsWithCSS("img[src]") { (imgElement, index, stop) in
if
let imageURLString = imgElement["src"] as? String,
let imageURL = NSURL(string: imageURLString, relativeToURL: localURL)
{
//let isExternal = URLIsExternal(linkURL, localHost: localHost)
imageElements.append(imgElement)
imageURLs.insert(imageURL)
}
}
self.imageElements = imageElements
self.imageURLs = imageURLs
h1Elements = document.allElementsWithCSS("h1")
richSnippetElements = [] //TODO:
}
else {
document = nil
stringEncoding = nil
pageTitleElements = []
metaDescriptionElements = []
openGraphElements = []
uniqueFeedURLs = UniqueURLArray()
feedLinkElements = []
uniqueExternalPageURLs = UniqueURLArray()
aExternalLinkElements = []
uniqueLocalPageURLs = UniqueURLArray()
aLocalLinkElements = []
imageURLs = Set<NSURL>()
imageElements = []
h1Elements = []
richSnippetElements = []
preBodyByteCount = nil
}
}
public var HTMLHeadData: NSData? {
if let preBodyByteCount = preBodyByteCount {
return data.subdataWithRange(NSMakeRange(0, preBodyByteCount))
}
return nil
}
public var HTMLBodyData: NSData? {
if let preBodyByteCount = preBodyByteCount {
return data.subdataWithRange(NSMakeRange(preBodyByteCount, data.length - preBodyByteCount))
}
return nil
}
public var stringContent: String? {
return NSString(data: data, encoding: stringEncoding) as? String
//return data.stringRepresentationUsingONOXMLDocumentHints(document)
}
public var HTMLHeadStringContent: String? {
if let data = HTMLHeadData {
return NSString(data: data, encoding: stringEncoding) as? String
}
else {
return nil
}
//return HTMLHeadData?.stringRepresentationUsingONOXMLDocumentHints(document)
}
public var HTMLBodyStringContent: String? {
if let data = HTMLBodyData {
return NSString(data: data, encoding: stringEncoding) as? String
}
else {
return nil
}
//return HTMLBodyData?.stringRepresentationUsingONOXMLDocumentHints(document)
}
}
public struct PageInfo {
public let requestedURL: NSURL
public let finalURL: NSURL?
public let statusCode: Int
public let baseContentType: BaseContentType
public let MIMEType: MIMETypeString?
public let byteCount: Int?
public let contentInfo: PageContentInfo?
}
public struct RequestRedirectionInfo {
let sourceRequest: NSURLRequest
let nextRequest: NSURLRequest
public let statusCode: Int
public let MIMEType: MIMETypeString?
}
| apache-2.0 |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Conversation/InputBar/CameraKeyboard/PhotoPermissionsControllerStrategy.swift | 1 | 1561 | //
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import Photos
final class PhotoPermissionsControllerStrategy: PhotoPermissionsController {
// `unauthorized` state happens the first time before opening the keyboard,
// so we don't need to check it for our purposes.
var isCameraAuthorized: Bool {
switch AVCaptureDevice.authorizationStatus(for: AVMediaType.video) {
case .authorized: return true
default: return false
}
}
var isPhotoLibraryAuthorized: Bool {
switch PHPhotoLibrary.authorizationStatus() {
case .authorized: return true
default: return false
}
}
var areCameraOrPhotoLibraryAuthorized: Bool {
return isCameraAuthorized || isPhotoLibraryAuthorized
}
var areCameraAndPhotoLibraryAuthorized: Bool {
return isCameraAuthorized && isPhotoLibraryAuthorized
}
}
| gpl-3.0 |
eoger/firefox-ios | Client/Frontend/AuthenticationManager/RequirePasscodeIntervalViewController.swift | 4 | 3168 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import SwiftKeychainWrapper
/// Screen presented to the user when selecting the time interval before requiring a passcode
class RequirePasscodeIntervalViewController: UITableViewController {
let intervalOptions: [PasscodeInterval] = [
.immediately,
.oneMinute,
.fiveMinutes,
.tenMinutes,
.fifteenMinutes,
.oneHour
]
fileprivate let BasicCheckmarkCell = "BasicCheckmarkCell"
fileprivate var authenticationInfo: AuthenticationKeychainInfo?
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = AuthenticationStrings.requirePasscode
tableView.accessibilityIdentifier = "AuthenticationManager.passcodeIntervalTableView"
tableView.register(UITableViewCell.self, forCellReuseIdentifier: BasicCheckmarkCell)
tableView.backgroundColor = UIColor.theme.tableView.headerBackground
let headerFooterFrame = CGRect(width: self.view.frame.width, height: SettingsUX.TableViewHeaderFooterHeight)
let headerView = ThemedTableSectionHeaderFooterView(frame: headerFooterFrame)
headerView.showTopBorder = false
headerView.showBottomBorder = true
let footerView = ThemedTableSectionHeaderFooterView(frame: headerFooterFrame)
footerView.showTopBorder = true
footerView.showBottomBorder = false
tableView.tableHeaderView = headerView
tableView.tableFooterView = footerView
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.authenticationInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo()
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: BasicCheckmarkCell, for: indexPath)
let option = intervalOptions[indexPath.row]
let intervalTitle = NSAttributedString.tableRowTitle(option.settingTitle, enabled: true)
cell.textLabel?.attributedText = intervalTitle
cell.accessoryType = authenticationInfo?.requiredPasscodeInterval == option ? .checkmark : .none
cell.backgroundColor = UIColor.theme.tableView.rowBackground
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return intervalOptions.count
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
authenticationInfo?.updateRequiredPasscodeInterval(intervalOptions[indexPath.row])
KeychainWrapper.sharedAppContainerKeychain.setAuthenticationInfo(authenticationInfo)
tableView.reloadData()
}
}
| mpl-2.0 |
mozilla-mobile/firefox-ios | Shared/AppConstants.swift | 2 | 3565 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import UIKit
public enum AppName: String, CustomStringConvertible {
case shortName = "Firefox"
public var description: String {
return self.rawValue
}
}
public enum AppBuildChannel: String {
case release = "release"
case beta = "beta"
case developer = "developer"
// Used for unknown cases
case other = "other"
}
public enum KVOConstants: String {
case loading = "loading"
case estimatedProgress = "estimatedProgress"
case URL = "URL"
case title = "title"
case canGoBack = "canGoBack"
case canGoForward = "canGoForward"
case contentSize = "contentSize"
}
public struct KeychainKey {
public static let fxaPushRegistration = "account.push-registration"
public static let apnsToken = "apnsToken"
}
public struct AppConstants {
// Any type of tests (UI and Unit)
public static let isRunningTest = NSClassFromString("XCTestCase") != nil
|| AppConstants.isRunningUITests
|| AppConstants.isRunningPerfTests
// Unit tests only
public static let isRunningUnitTest = NSClassFromString("XCTestCase") != nil
&& !AppConstants.isRunningUITests
&& !AppConstants.isRunningPerfTests
// Only UI tests
public static let isRunningUITests = ProcessInfo.processInfo.arguments.contains(LaunchArguments.Test)
// Only performance tests
public static let isRunningPerfTests = ProcessInfo.processInfo.arguments.contains(LaunchArguments.PerformanceTest)
public static let FxAiOSClientId = "1b1a3e44c54fbb58"
/// Build Channel.
public static let BuildChannel: AppBuildChannel = {
#if MOZ_CHANNEL_RELEASE
return AppBuildChannel.release
#elseif MOZ_CHANNEL_BETA
return AppBuildChannel.beta
#elseif MOZ_CHANNEL_FENNEC
return AppBuildChannel.developer
#else
return AppBuildChannel.other
#endif
}()
public static let scheme: String = {
guard let identifier = Bundle.main.bundleIdentifier else {
return "unknown"
}
let scheme = identifier.replacingOccurrences(of: "org.mozilla.ios.", with: "")
if scheme == "FirefoxNightly.enterprise" {
return "FirefoxNightly"
}
return scheme
}()
public static let PrefSendUsageData = "settings.sendUsageData"
public static let PrefStudiesToggle = "settings.studiesToggle"
/// Enables support for International Domain Names (IDN)
/// Disabled because of https://bugzilla.mozilla.org/show_bug.cgi?id=1312294
public static let MOZ_PUNYCODE: Bool = {
#if MOZ_CHANNEL_RELEASE
return false
#elseif MOZ_CHANNEL_BETA
return false
#elseif MOZ_CHANNEL_FENNEC
return true
#else
return true
#endif
}()
/// The maximum length of a URL stored by Firefox. Shared with Places on desktop.
public static let DB_URL_LENGTH_MAX = 65536
/// The maximum length of a page title stored by Firefox. Shared with Places on desktop.
public static let DB_TITLE_LENGTH_MAX = 4096
/// The maximum length of a bookmark description stored by Firefox. Shared with Places on desktop.
public static let DB_DESCRIPTION_LENGTH_MAX = 1024
/// Fixed short version for nightly builds
public static let NIGHTLY_APP_VERSION = "9000"
}
| mpl-2.0 |
simalexan/concrete-math-algorithms | lines-in-plane.swift | 1 | 295 | func getRegionsInPlaneByLinesRecurrently(numLines: UInt) -> UInt{
if numLines == UInt.min { return 1 }
return getRegionsInPlaneByLinesRecurrently(numLines-1) + numLines
} //O(n)
func getRegionsInPlaneByLinesClosed(numLines: UInt) -> UInt {
return (numLines*(numLines+1)) / 2 + 1
} //O(1)
| mit |
hoobaa/nkbd | Keyboard/cForwardingView.swift | 6 | 7709 | //
// ForwardingView.swift
// TransliteratingKeyboard
//
// Created by Alexei Baboulevitch on 7/19/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
import UIKit
class ForwardingView: UIView {
var touchToView: [UITouch:UIView]
override init(frame: CGRect) {
self.touchToView = [:]
super.init(frame: frame)
self.contentMode = UIViewContentMode.Redraw
self.multipleTouchEnabled = true
self.userInteractionEnabled = true
self.opaque = false
}
required init(coder: NSCoder) {
fatalError("NSCoding not supported")
}
// Why have this useless drawRect? Well, if we just set the backgroundColor to clearColor,
// then some weird optimization happens on UIKit's side where tapping down on a transparent pixel will
// not actually recognize the touch. Having a manual drawRect fixes this behavior, even though it doesn't
// actually do anything.
override func drawRect(rect: CGRect) {}
override func hitTest(point: CGPoint, withEvent event: UIEvent!) -> UIView? {
if self.hidden || self.alpha == 0 || !self.userInteractionEnabled {
return nil
}
else {
return (CGRectContainsPoint(self.bounds, point) ? self : nil)
}
}
func handleControl(view: UIView?, controlEvent: UIControlEvents) {
if let control = view as? UIControl {
let targets = control.allTargets()
for target in targets {
if var actions = control.actionsForTarget(target, forControlEvent: controlEvent) {
for action in actions {
if let selectorString = action as? String {
let selector = Selector(selectorString)
control.sendAction(selector, to: target, forEvent: nil)
}
}
}
}
}
}
// TODO: there's a bit of "stickiness" to Apple's implementation
func findNearestView(position: CGPoint) -> UIView? {
if !self.bounds.contains(position) {
return nil
}
var closest: (UIView, CGFloat)? = nil
for anyView in self.subviews {
if let view = anyView as? UIView {
if view.hidden {
continue
}
view.alpha = 1
let distance = distanceBetween(view.frame, point: position)
if closest != nil {
if distance < closest!.1 {
closest = (view, distance)
}
}
else {
closest = (view, distance)
}
}
}
if closest != nil {
return closest!.0
}
else {
return nil
}
}
// http://stackoverflow.com/questions/3552108/finding-closest-object-to-cgpoint b/c I'm lazy
func distanceBetween(rect: CGRect, point: CGPoint) -> CGFloat {
if CGRectContainsPoint(rect, point) {
return 0
}
var closest = rect.origin
if (rect.origin.x + rect.size.width < point.x) {
closest.x += rect.size.width
}
else if (point.x > rect.origin.x) {
closest.x = point.x
}
if (rect.origin.y + rect.size.height < point.y) {
closest.y += rect.size.height
}
else if (point.y > rect.origin.y) {
closest.y = point.y
}
let a = pow(Double(closest.y - point.y), 2)
let b = pow(Double(closest.x - point.x), 2)
return CGFloat(sqrt(a + b));
}
// reset tracked views without cancelling current touch
func resetTrackedViews() {
for view in self.touchToView.values {
self.handleControl(view, controlEvent: .TouchCancel)
}
self.touchToView.removeAll(keepCapacity: true)
}
func ownView(newTouch: UITouch, viewToOwn: UIView?) -> Bool {
var foundView = false
if viewToOwn != nil {
for (touch, view) in self.touchToView {
if viewToOwn == view {
if touch == newTouch {
break
}
else {
self.touchToView[touch] = nil
foundView = true
}
break
}
}
}
self.touchToView[newTouch] = viewToOwn
return foundView
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
for obj in touches {
if let touch = obj as? UITouch {
let position = touch.locationInView(self)
var view = findNearestView(position)
var viewChangedOwnership = self.ownView(touch, viewToOwn: view)
if !viewChangedOwnership {
self.handleControl(view, controlEvent: .TouchDown)
if touch.tapCount > 1 {
// two events, I think this is the correct behavior but I have not tested with an actual UIControl
self.handleControl(view, controlEvent: .TouchDownRepeat)
}
}
}
}
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
for obj in touches {
if let touch = obj as? UITouch {
let position = touch.locationInView(self)
var oldView = self.touchToView[touch]
var newView = findNearestView(position)
if oldView != newView {
self.handleControl(oldView, controlEvent: .TouchDragExit)
var viewChangedOwnership = self.ownView(touch, viewToOwn: newView)
if !viewChangedOwnership {
self.handleControl(newView, controlEvent: .TouchDragEnter)
}
else {
self.handleControl(newView, controlEvent: .TouchDragInside)
}
}
else {
self.handleControl(oldView, controlEvent: .TouchDragInside)
}
}
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
for obj in touches {
if let touch = obj as? UITouch {
var view = self.touchToView[touch]
let touchPosition = touch.locationInView(self)
if self.bounds.contains(touchPosition) {
self.handleControl(view, controlEvent: .TouchUpInside)
}
else {
self.handleControl(view, controlEvent: .TouchCancel)
}
self.touchToView[touch] = nil
}
}
}
override func touchesCancelled(touches: Set<NSObject>, withEvent event: UIEvent!) {
for obj in touches {
if let touch = obj as? UITouch {
var view = self.touchToView[touch]
self.handleControl(view, controlEvent: .TouchCancel)
self.touchToView[touch] = nil
}
}
}
}
| bsd-3-clause |
fizx/jane | ruby/lib/vendor/grpc-swift/Sources/SwiftGRPC/Runtime/ClientCallServerStreaming.swift | 4 | 2334 | /*
* Copyright 2018, gRPC 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 Dispatch
import Foundation
import SwiftProtobuf
public protocol ClientCallServerStreaming: ClientCall {
// TODO: Move the other, message type-dependent, methods into this protocol. At the moment, this is not possible,
// as the protocol would then have an associated type requirement (and become pretty much unusable in the process).
}
open class ClientCallServerStreamingBase<InputType: Message, OutputType: Message>: ClientCallBase, ClientCallServerStreaming, StreamReceiving {
public typealias ReceivedType = OutputType
/// Call this once with the message to send. Nonblocking.
public func start(request: InputType, metadata: Metadata, completion: ((CallResult) -> Void)?) throws -> Self {
let requestData = try request.serializedData()
try call.start(.serverStreaming,
metadata: metadata,
message: requestData,
completion: completion)
return self
}
}
/// Simple fake implementation of ClientCallServerStreamingBase that returns a previously-defined set of results.
open class ClientCallServerStreamingTestStub<OutputType: Message>: ClientCallServerStreaming {
open class var method: String { fatalError("needs to be overridden") }
open var lock = Mutex()
open var outputs: [OutputType] = []
public init() {}
open func _receive(timeout: DispatchTime) throws -> OutputType? {
return lock.synchronize {
defer { if !outputs.isEmpty { outputs.removeFirst() } }
return outputs.first
}
}
open func receive(completion: @escaping (ResultOrRPCError<OutputType?>) -> Void) throws {
completion(.result(try self._receive(timeout: .distantFuture)))
}
open func cancel() {}
}
| mit |
google/GTMAppAuth | GTMAppAuthSwift/Sources/GTMKeychain.swift | 1 | 13732 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import Security
/// An internal utility for saving and loading data to the keychain.
final class GTMKeychain {
private var keychainHelper: KeychainHelper
/// An initializer for testing to create an instance of this keychain wrapper with a given helper.
///
/// - Parameter keychainHelper: An instance conforming to `KeychainHelper`.
init(keychainHelper: KeychainHelper? = nil) {
if let helper = keychainHelper {
self.keychainHelper = helper
} else {
self.keychainHelper = KeychainWrapper()
}
}
/// Saves the password `String` to the keychain with the given identifier.
///
/// - Parameters:
/// - password: The `String` password.
/// - itemName: The name for the Keychain item.
/// - Throws: An instance of `KeychainWrapper.Error`.
func save(password: String, forItemName itemName: String) throws {
try savePasswordToKeychain(password, forItemName: itemName)
}
/// Saves the password `String` to the keychain with the given identifier.
///
/// - Parameters:
/// - password: The `String` password.
/// - itemName: The name for the Keychain item.
/// - usingDataProtectionKeychain: A `Bool` indicating whether to use the data
/// protection keychain on macOS 10.15.
/// - Throws: An instance of `KeychainWrapper.Error`.
@available(macOS 10.15, *)
func save(
password: String,
forItemName itemName: String,
usingDataProtectionKeychain: Bool
) throws {
try savePasswordToKeychain(
password,
forItemName: itemName,
usingDataProtectionKeychain: usingDataProtectionKeychain
)
}
private func savePasswordToKeychain(
_ password: String,
forItemName name: String,
usingDataProtectionKeychain: Bool = false
) throws {
keychainHelper.useDataProtectionKeychain = usingDataProtectionKeychain
try keychainHelper.setPassword(
password,
forService: name,
accessibility: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
)
}
/// Retrieves the `String` password for the given `String` identifier.
///
/// - Parameter itemName: A `String` identifier for the Keychain item.
/// - Returns: A `String` password if found.
/// - Throws: An instance of `KeychainWrapper.Error`.
func password(forItemName itemName: String) throws -> String {
try passwordFromKeychain(withKeychainItemName: itemName)
}
/// Retrieves the `String` password for the given `String` identifier.
///
/// - Parameters:
/// - itemName: A `String` identifier for the Keychain item.
/// - usingDataProtectionKeychain: A `Bool` indicating whether to use the data protection
/// keychain on macOS 10.15.
/// - Returns: A `String` password if found.
/// - Throws: An instance of `KeychainWrapper.Error`.
@available(macOS 10.15, *)
func password(forItemName itemName: String, usingDataProtectionKeychain: Bool) throws -> String {
try passwordFromKeychain(
withKeychainItemName: itemName,
usingDataProtectionKeychain: usingDataProtectionKeychain
)
}
private func passwordFromKeychain(
withKeychainItemName itemName: String,
usingDataProtectionKeychain: Bool = false
) throws -> String {
keychainHelper.useDataProtectionKeychain = usingDataProtectionKeychain
return try keychainHelper.password(forService: itemName)
}
/// Saves the password `Data` to the keychain with the given identifier.
///
/// - Parameters:
/// - passwordData: The password `Data`.
/// - itemName: The name for the Keychain item.
/// - Throws: An instance of `KeychainWrapper.Error`.
func save(passwordData: Data, forItemName itemName: String) throws {
try savePasswordDataToKeychain(passwordData, forItemName: itemName)
}
/// Saves the password `Data` to the keychain with the given identifier.
///
/// - Parameters:
/// - password: The password `Data`.
/// - itemName: The name for the Keychain item.
/// - usingDataProtectionKeychain: A `Bool` indicating whether to use the data protection
/// keychain on macOS 10.15.
/// - Throws: An instance of `KeychainWrapper.Error`.
@available(macOS 10.15, *)
func save(
passwordData: Data,
forItemName itemName: String,
usingDataProtectionKeychain: Bool
) throws {
try savePasswordDataToKeychain(
passwordData,
forItemName: itemName,
usingDataProtectionKeychain: usingDataProtectionKeychain
)
}
private func savePasswordDataToKeychain(
_ passwordData: Data,
forItemName itemName: String,
usingDataProtectionKeychain: Bool = false
) throws {
keychainHelper.useDataProtectionKeychain = usingDataProtectionKeychain
try keychainHelper.setPassword(
data: passwordData,
forService: itemName,
accessibility: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
)
}
/// Retrieves the password `Data` for the given `String` identifier.
///
/// - Parameter itemName: A `String` identifier for the Keychain item.
/// - Returns: The password `Data` if found.
/// - Throws: An instance of `KeychainWrapper.Error`.
func passwordData(forItemName itemName: String) throws -> Data {
try passwordDataFromKeychain(withItemName: itemName)
}
/// Retrieves the password `Data` for the given `String` identifier.
///
/// - Parameters:
/// - itemName: A `String` identifier for the Keychain item.
/// - usingDataProtectionKeychain: A `Bool` indicating whether to use the data protection
/// keychain on macOS 10.15.
/// - Returns: The password `Data` if found.
/// - Throws: An instance of `KeychainWrapper.Error`.
@available(macOS 10.15, *)
func passwordData(
forItemName itemName: String,
usingDataProtectionKeychain: Bool
) throws -> Data {
try passwordDataFromKeychain(
withItemName: itemName,
usingDataProtectionKeychain: usingDataProtectionKeychain
)
}
private func passwordDataFromKeychain(
withItemName itemName: String,
usingDataProtectionKeychain: Bool = false
) throws -> Data {
keychainHelper.useDataProtectionKeychain = usingDataProtectionKeychain
return try keychainHelper.passwordData(forService: itemName)
}
/// Removes stored password string, such as when the user signs out.
///
/// - Parameter itemName: The Keychain name for the item.
/// - Throws: An instance of `KeychainWrapper.Error`.
func removePasswordFromKeychain(withItemName itemName: String) throws {
try removePasswordFromKeychain(keychainItemName: itemName)
}
/// Removes stored password string, such as when the user signs out. Note that if you choose to
/// start using the data protection keychain on macOS, any items previously created will not be
/// accessible without migration.
///
/// - Parameters:
/// - itemName: The Keychain name for the item.
/// - usingDataProtectionKeychain: A Boolean value that indicates whether to use the data
/// protection keychain on macOS 10.15+.
/// - Throws: An instance of `KeychainWrapper.Error`.
@available(macOS 10.15, *)
func removePasswordFromKeychain(forName name: String, usingDataProtectionKeychain: Bool) throws {
try removePasswordFromKeychain(
keychainItemName: name,
usingDataProtectionKeychain: usingDataProtectionKeychain
)
}
private func removePasswordFromKeychain(
keychainItemName: String,
usingDataProtectionKeychain: Bool = false
) throws {
keychainHelper.useDataProtectionKeychain = usingDataProtectionKeychain
try keychainHelper.removePassword(forService: keychainItemName)
}
}
// MARK: - Keychain helper
/// A protocol defining the helper API for interacting with the Keychain.
protocol KeychainHelper {
var accountName: String { get }
var useDataProtectionKeychain: Bool { get set }
func password(forService service: String) throws -> String
func passwordData(forService service: String) throws -> Data
func removePassword(forService service: String) throws
func setPassword(_ password: String, forService service: String, accessibility: CFTypeRef) throws
func setPassword(data: Data, forService service: String, accessibility: CFTypeRef?) throws
}
/// An internally scoped keychain helper.
private struct KeychainWrapper: KeychainHelper {
let accountName = "OAuth"
var useDataProtectionKeychain = false
@available(macOS 10.15, *)
private var isMaxMacOSVersionGreaterThanTenOneFive: Bool {
let tenOneFive = OperatingSystemVersion(majorVersion: 10, minorVersion: 15, patchVersion: 0)
return ProcessInfo().isOperatingSystemAtLeast(tenOneFive)
}
func keychainQuery(forService service: String) -> [String: Any] {
var query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String : accountName,
kSecAttrService as String: service,
]
#if os(macOS) && isMaxMacOSVersionGreaterThanTenOneFive
if #available(macOS 10.15, *), useDataProtectionKeychain {
query[kSecUseDataProtectionKeychain as String] = kCFBooleanTrue
}
#endif
return query
}
func password(forService service: String) throws -> String {
let passwordData = try passwordData(forService: service)
guard let result = String(data: passwordData, encoding: .utf8) else {
throw GTMKeychainError.unexpectedPasswordData(forItemName: service)
}
return result
}
func passwordData(forService service: String) throws -> Data {
guard !service.isEmpty else { throw GTMKeychainError.noService }
var passwordItem: AnyObject?
var keychainQuery = keychainQuery(forService: service)
keychainQuery[kSecReturnData as String] = true
keychainQuery[kSecMatchLimit as String] = kSecMatchLimitOne
let status = SecItemCopyMatching(keychainQuery as CFDictionary, &passwordItem)
guard status != errSecItemNotFound else {
throw GTMKeychainError.passwordNotFound(forItemName: service)
}
guard status == errSecSuccess else { throw GTMKeychainError.unhandled(status: status) }
guard let result = passwordItem as? Data else {
throw GTMKeychainError.unexpectedPasswordData(forItemName: service)
}
return result
}
func removePassword(forService service: String) throws {
guard !service.isEmpty else { throw GTMKeychainError.noService }
let keychainQuery = keychainQuery(forService: service)
let status = SecItemDelete(keychainQuery as CFDictionary)
guard status != errSecItemNotFound else {
throw GTMKeychainError.failedToDeletePasswordBecauseItemNotFound(itemName: service)
}
guard status == noErr else { throw GTMKeychainError.failedToDeletePassword(forItemName: service) }
}
func setPassword(
_ password: String,
forService service: String,
accessibility: CFTypeRef
) throws {
let passwordData = Data(password.utf8)
try setPassword(data: passwordData, forService: service, accessibility: accessibility)
}
func setPassword(data: Data, forService service: String, accessibility: CFTypeRef?) throws {
guard !service.isEmpty else { throw GTMKeychainError.noService }
do {
try removePassword(forService: service)
} catch GTMKeychainError.failedToDeletePasswordBecauseItemNotFound {
// Don't throw; password doesn't exist since the password is being saved for the first time
} catch {
// throw here since this is some other error
throw error
}
guard !data.isEmpty else { return }
var keychainQuery = keychainQuery(forService: service)
keychainQuery[kSecValueData as String] = data
if let accessibility = accessibility {
keychainQuery[kSecAttrAccessible as String] = accessibility
}
let status = SecItemAdd(keychainQuery as CFDictionary, nil)
guard status == noErr else { throw GTMKeychainError.failedToSetPassword(forItemName: service) }
}
}
// MARK: - Keychain Errors
/// Errors that may arise while saving, reading, and removing passwords from the Keychain.
public enum GTMKeychainError: Error, Equatable, CustomNSError {
case unhandled(status: OSStatus)
case passwordNotFound(forItemName: String)
/// Error thrown when there is no name for the item in the keychain.
case noService
case unexpectedPasswordData(forItemName: String)
case failedToDeletePassword(forItemName: String)
case failedToDeletePasswordBecauseItemNotFound(itemName: String)
case failedToSetPassword(forItemName: String)
public static var errorDomain: String {
"GTMAppAuthKeychainErrorDomain"
}
public var errorUserInfo: [String : Any] {
switch self {
case .unhandled(status: let status):
return ["status": status]
case .passwordNotFound(let itemName):
return ["itemName": itemName]
case .noService:
return [:]
case .unexpectedPasswordData(let itemName):
return ["itemName": itemName]
case .failedToDeletePassword(let itemName):
return ["itemName": itemName]
case .failedToDeletePasswordBecauseItemNotFound(itemName: let itemName):
return ["itemName": itemName]
case .failedToSetPassword(forItemName: let itemName):
return ["itemName": itemName]
}
}
}
| apache-2.0 |
BenYeh16/SoundMapiOS | SoundMap/RecordInfoViewController.swift | 1 | 12335 | //
// RecordInfoViewController.swift
// SoundMap
//
// Created by 胡采思 on 12/06/2017.
// Copyright © 2017 cnl4. All rights reserved.
//
import UIKit
import AVFoundation
import CoreLocation
class RecordInfoViewController: UIViewController, UITextViewDelegate, UITextFieldDelegate {
@IBOutlet weak var recordInfoView: UIView!
@IBOutlet weak var closeButton: UIButton!
@IBOutlet weak var saveButton: UIButton!
@IBOutlet weak var soundInfoLabel: UILabel!
@IBOutlet weak var descriptionText: UITextView!
@IBOutlet weak var titleText: UITextField!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var audioCurrent: UILabel!
@IBOutlet weak var audioTime: UILabel!
@IBOutlet weak var audioSlider: UISlider!
@IBOutlet weak var playButton: UIButton!
var player:AVAudioPlayer = AVAudioPlayer();
var remotePlayer:AVPlayer = AVPlayer();
var isPaused:BooleanLiteralType = false;
var timer: Timer!
var soundFileURL: URL?
override func viewDidLoad() {
super.viewDidLoad()
// Set design attributes
recordInfoView.layer.cornerRadius = 10
recordInfoView.layer.masksToBounds = true
soundInfoLabel.font = UIFont.boldSystemFont(ofSize: 20.0)
titleText.layer.borderColor = UIColor.init(red: 203/255, green: 203/255, blue: 203/255, alpha: 1).cgColor
descriptionText.layer.borderColor = UIColor.init(red: 204/255, green: 204/255, blue: 204/255, alpha: 1).cgColor
saveButton.layer.borderColor = UIColor.init(red: 7/255, green: 55/255, blue: 99/255, alpha: 1).cgColor
// Keyboard
//NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
//NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
// Text delegate
descriptionText.delegate = self
titleText.delegate = self
// Initialize audio
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
soundFileURL = documentsDirectory.appendingPathComponent("recording-123.m4a")
self.isPaused = false;
do {
//let audioPath = Bundle.main.path(forResource: "audiofile", ofType: "mp3")
//try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
try player = AVAudioPlayer(contentsOf: soundFileURL!)
player.volume = 1.0
audioSlider.maximumValue = Float(player.duration)
audioSlider.value = 0.0
audioTime.text = stringFromTimeInterval(interval: player.duration)
audioCurrent.text = stringFromTimeInterval(interval: player.currentTime)
//try player = AVAudioPlayer(contentsOf: url)
//let playerItem = AVPlayerItem(url: self.url)
//try self.remotePlayer = AVPlayer(playerItem: playerItem)
//self.remotePlayer.volume = 1.0
} catch {
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/****** TextView related ******/
/*func keyboardWillShow(notification: NSNotification) {
/*let keyboardSize: CGSize = ((notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size)!
let offset: CGSize = ((notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size)!
if keyboardSize.height == offset.height {
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.view.frame.origin.y -= keyboardSize.height
})
} else {
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.view.frame.origin.y += keyboardSize.height - offset.height
})
}*/
if let keyboardFrame = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue) {
let rect = keyboardFrame.cgRectValue
UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseInOut, animations: {
self.descriptionText.contentInset = UIEdgeInsetsMake(0, 0, rect.size.height, 0)
}, completion: nil)
}
}
func keyboardWillHide(notification: NSNotification) {
/*if let keyboardFrame = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue) {
let rect = keyboardFrame.cgRectValue
self.view.frame.origin.y += rect.size.height
}*/
UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseInOut, animations: {
self.descriptionText.contentInset = UIEdgeInsets.zero
}, completion: nil)
}*/
func textViewDidBeginEditing(_ textView: UITextView) {
animateViewMoving(up: true, moveValue: 50)
}
func textViewDidEndEditing(_ textView: UITextView) {
animateViewMoving(up: true, moveValue: -50)
}
func animateViewMoving (up: Bool, moveValue: CGFloat){
let movementDuration:TimeInterval = 0.3
let movement:CGFloat = ( up ? -moveValue : moveValue)
UIView.beginAnimations( "animateView", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(movementDuration )
self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)
UIView.commitAnimations()
}
// Allow RETURN to hide keyboard for textField
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// Allow RETURN to hide keyboard for textView
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if (text == "\n")
{
textView.resignFirstResponder()
return false
}
return true
}
/****** Button action ******/
@IBAction func saveSound(_ sender: Any) {
let data = SharedData()
//let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
//let soundFileURL: URL = documentsDirectory.appendingPathComponent("recording-123.m4a")
//self.parentView.pinFromOutside()
print("soundfile url: '\(soundFileURL)'")
print("title: " + titleText.text!)
print ("descripText: " + descriptionText.text)
if ( titleText.text != "" && descriptionText.text != ""){
print("ready to upload")
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "stopSoundNotification"), object: nil)
let locationManager = CLLocationManager()
var currentLocation = locationManager.location!
/*upload with
user id
titleText.text
descriptionText.text
\(currentLocation.coordinate.latitude)
\(currentLocation.coordinate.longitude)
\(soundFileURL)
*/
var storeUrl = data.storeSound(latitude: "25.033331",
longitude: "121.534831",
id: data.getUserId(),
title: titleText.text!,
descript: descriptionText.text
)
print("!@#!@#!# storeUrl" + storeUrl)
var request = URLRequest(url: URL(string: storeUrl)!) // link removed
//var request = URLRequest(url : URL(string: "http://140.112.90.203:4000/setUserVoice/1")!)
request.httpMethod = "POST"
/* create body*/
let body = NSMutableData()
//let file = "\(soundFileURL)" // :String
let bundlefile = Bundle.main.path(forResource: "audiofile", ofType: "mp3")
print("!!!!!! " + bundlefile!)
let url = URL(string: bundlefile!) // :URL
let data = try! Data(contentsOf: url!)
body.append(data)
request.httpBody = body as Data
/* body create complete*/
let atask = URLSession.shared.dataTask(with: request) { data, response, error in
if error != nil{
print("error in dataTask")
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
let resultValue:String = parseJSON["success"] as! String;
print("result: \(resultValue)")
print(parseJSON)
}
} catch let error as NSError {
print(error)
}
}
atask.resume()
// Close modal
dismiss(animated: true, completion: nil)
}else {
let alertController = UIAlertController(
title: "Don't leave Blank",
message: "Title or description missing",
preferredStyle: .alert)
// 建立[確認]按鈕
let okAction = UIAlertAction(
title: "確認",
style: .default,
handler: {
(action: UIAlertAction!) -> Void in
print("按下確認後,閉包裡的動作")
})
alertController.addAction(okAction)
// 顯示提示框
self.present(
alertController,
animated: true,
completion: nil)
}
//
}
@IBAction func closePopup(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
/****** Audio ******/
@IBAction func playAudioPressed(_ sender: Any) {
if ( self.isPaused == false ) {
player.play()
playButton.setImage(UIImage(named: "music-pause"), for: .normal)
self.isPaused = true
//audioSlider.value = Float(player.currentTime)
timer = Timer(timeInterval: 1.0, target: self, selector: #selector(self.updateSlider), userInfo: nil, repeats: true)
RunLoop.main.add(timer, forMode: .commonModes)
} else {
player.pause()
playButton.setImage(UIImage(named: "music-play"), for: .normal)
self.isPaused = false
timer.invalidate()
}
}
@IBAction func slide(_ sender: Any) {
player.currentTime = TimeInterval(audioSlider.value)
}
func stringFromTimeInterval(interval: TimeInterval) -> String {
let interval = Int(interval)
let seconds = interval % 60
let minutes = (interval / 60) % 60
return String(format: "%02d:%02d", minutes, seconds)
}
func updateSlider(_ timer: Timer) {
audioSlider.value = Float(player.currentTime)
audioCurrent.text = stringFromTimeInterval(interval: player.currentTime)
audioTime.text = stringFromTimeInterval(interval: player.duration - player.currentTime)
if audioTime.text == "00:00" { // done
playButton.setImage(UIImage(named: "music-play"), for: .normal)
}
}
func stringFromFloatCMTime(time: Double) -> String {
let intTime = Int(time)
let seconds = intTime % 60
let minutes = ( intTime / 60 ) % 60
return String(format: "%02d:%02d", minutes, seconds)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| gpl-3.0 |
wordpress-mobile/WordPress-iOS | WordPress/WordPressTest/MediaHostTests.swift | 2 | 4086 | import XCTest
@testable import WordPress
class MediaHostTests: XCTestCase {
func testInitializationWithPublicSite() {
let host = MediaHost(
isAccessibleThroughWPCom: false,
isPrivate: false,
isAtomic: false,
siteID: nil,
username: nil,
authToken: nil) { error in
XCTFail("This should not be called.")
}
XCTAssertEqual(host, .publicSite)
}
func testInitializationWithPublicWPComSite() {
let host = MediaHost(
isAccessibleThroughWPCom: true,
isPrivate: false,
isAtomic: false,
siteID: nil,
username: nil,
authToken: nil) { error in
XCTFail("This should not be called.")
}
XCTAssertEqual(host, .publicWPComSite)
}
func testInitializationWithPrivateSelfHostedSite() {
let host = MediaHost(
isAccessibleThroughWPCom: false,
isPrivate: true,
isAtomic: false,
siteID: nil,
username: nil,
authToken: nil) { error in
XCTFail("This should not be called.")
}
XCTAssertEqual(host, .privateSelfHostedSite)
}
func testInitializationWithPrivateWPComSite() {
let authToken = "letMeIn!"
let host = MediaHost(
isAccessibleThroughWPCom: true,
isPrivate: true,
isAtomic: false,
siteID: nil,
username: nil,
authToken: authToken) { error in
XCTFail("This should not be called.")
}
XCTAssertEqual(host, .privateWPComSite(authToken: authToken))
}
func testInitializationWithPrivateAtomicWPComSite() {
let siteID = 16557
let username = "demouser"
let authToken = "letMeIn!"
let host = MediaHost(
isAccessibleThroughWPCom: true,
isPrivate: true,
isAtomic: true,
siteID: siteID,
username: username,
authToken: authToken) { error in
XCTFail("This should not be called.")
}
XCTAssertEqual(host, .privateAtomicWPComSite(siteID: siteID, username: username, authToken: authToken))
}
func testInitializationWithPrivateAtomicWPComSiteWithoutAuthTokenFails() {
let siteID = 16557
let username = "demouser"
let expectation = self.expectation(description: "We're expecting an error to be triggered.")
let _ = MediaHost(
isAccessibleThroughWPCom: true,
isPrivate: true,
isAtomic: true,
siteID: siteID,
username: username,
authToken: nil) { error in
if error == .wpComPrivateSiteWithoutAuthToken {
expectation.fulfill()
}
}
waitForExpectations(timeout: 0.05)
}
func testInitializationWithPrivateAtomicWPComSiteWithoutUsernameFails() {
let siteID = 16557
let authToken = "letMeIn!"
let expectation = self.expectation(description: "We're expecting an error to be triggered.")
let _ = MediaHost(
isAccessibleThroughWPCom: true,
isPrivate: true,
isAtomic: true,
siteID: siteID,
username: nil,
authToken: authToken) { error in
if error == .wpComPrivateSiteWithoutUsername {
expectation.fulfill()
}
}
waitForExpectations(timeout: 0.05)
}
func testInitializationWithPrivateAtomicWPComSiteWithoutSiteIDFails() {
let expectation = self.expectation(description: "The error closure will be called")
let _ = MediaHost(
isAccessibleThroughWPCom: true,
isPrivate: true,
isAtomic: true,
siteID: nil,
username: nil,
authToken: nil) { error in
expectation.fulfill()
}
waitForExpectations(timeout: 0.05)
}
}
| gpl-2.0 |
fawadsuhail/weather-app | WeatherAppTests/RealmDataProviderTests.swift | 1 | 1677 | //
// RealmDataProviderTests.swift
// WeatherApp
//
// Created by Fawad Suhail on 4/3/17.
// Copyright © 2017 Fawad Suhail. All rights reserved.
//
import XCTest
@testable import WeatherApp
@testable import RealmSwift
class RealmDataProviderTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// setup in memory Identifier
RealmDataProvider.shared.setupWithMemoryIdentifier(identifier: "testRealm1")
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class
super.tearDown()
}
func testInsertion() {
let city = City(name: "singapore")
RealmDataProvider.shared.addCity(city: city)
let cities: [City] = RealmDataProvider.shared.getCities()
XCTAssert(cities.count == 1, "")
}
func testDuplicates() {
// all the following insertions should result in only
// one result in the database "singapore"
let city1 = City(name: "Singapore")
let city2 = City(name: " singapore")
let city3 = City(name: "SiNgApOrE")
// insert 1
RealmDataProvider.shared.addCity(city: city1)
// insert 2
RealmDataProvider.shared.addCity(city: city2)
// insert 3
RealmDataProvider.shared.addCity(city: city3)
guard let realm = try? Realm() else {
XCTFail("Failed to initialize realm")
return
}
let cities = realm.objects(CityRealmObject.self).filter("name = 'singapore'")
XCTAssert(cities.count == 1, "Cities are not one")
}
}
| mit |
avito-tech/Paparazzo | Paparazzo/Core/VIPER/InfoMessage/InfoMessageAnimator.swift | 1 | 5198 | import UIKit
public enum InfoMessageViewDismissType {
case interactive
case timeout
case force
}
struct InfoMessageAnimatorData {
let animation: InfoMessageAnimatorBehavior
let timeout: TimeInterval
let onDismiss: ((InfoMessageViewDismissType) -> ())?
init(
animation: InfoMessageAnimatorBehavior,
timeout: TimeInterval = 0.0,
onDismiss: ((InfoMessageViewDismissType) -> ())?)
{
self.animation = animation
self.timeout = timeout
self.onDismiss = onDismiss
}
}
private enum AnimatorState {
case initial
case appearing
case appeared
case dismissingByTimer
case dismissingByDismissFunction
case dismissed
}
final class InfoMessageAnimator: InfoMessageViewInput {
private weak var container: UIView?
private weak var messageView: InfoMessageView?
private var dismissingByTimerDebouncer: Debouncer
// Constant settings
private let behavior: InfoMessageAnimatorBehavior
private let onDismiss: ((InfoMessageViewDismissType) -> ())?
// Updatable settings
private var timeout: TimeInterval
// Other state
private var state = AnimatorState.initial
init(_ data: InfoMessageAnimatorData)
{
behavior = data.animation
onDismiss = data.onDismiss
timeout = data.timeout
dismissingByTimerDebouncer = Debouncer(delay: timeout)
}
// MARK: - Interface
func appear(messageView: InfoMessageView, in container: UIView) {
self.container = container
self.messageView = messageView
messageView.size = messageView.sizeThatFits(container.size)
behavior.configure(messageView: messageView, in: container)
container.addSubview(messageView)
container.bringSubviewToFront(messageView)
changeState(to: .appearing)
}
func dismiss() {
changeState(to: .dismissingByDismissFunction)
}
func update(timeout: TimeInterval) {
self.timeout = timeout
dismissingByTimerDebouncer.cancel()
dismissingByTimerDebouncer = Debouncer(delay: timeout)
switch state {
case .initial, .appearing:
// dismissing is not scheduled
break
case .appeared:
scheduleDismissing()
case .dismissingByTimer, .dismissingByDismissFunction, .dismissed:
// scheduling is not needed
break
}
}
// MARK: - States
private func changeState(to newState: AnimatorState) {
guard allowedTransitions().contains(newState) else { return }
state = newState
switch newState {
case .initial:
break
case .appearing:
animateAppearing()
case .appeared:
scheduleDismissing()
case .dismissingByTimer:
animateDismissing(dismissType: .timeout)
case .dismissingByDismissFunction:
animateDismissing(dismissType: .force)
case .dismissed:
messageView?.removeFromSuperview()
}
}
private func allowedTransitions() -> [AnimatorState] {
switch state {
case .initial:
return [.appearing, .dismissingByDismissFunction]
case .appearing:
return [.appeared, .dismissingByDismissFunction]
case .appeared:
return [.dismissingByTimer, .dismissingByDismissFunction]
case .dismissingByTimer, .dismissingByDismissFunction:
return [.dismissed]
case .dismissed:
return []
}
}
private func scheduleDismissing() {
if timeout.isZero {
dismissingByTimerDebouncer.cancel()
} else {
dismissingByTimerDebouncer.debounce { [weak self] in
self?.changeState(to: .dismissingByTimer)
}
}
}
// MARK: - Animations
private func animateAppearing() {
guard
let messageView = self.messageView,
let container = self.container
else { return }
UIView.animate(
withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 0.75,
initialSpringVelocity: 0.1,
options: .curveEaseIn,
animations: {
self.behavior.present(messageView: messageView, in: container)
},
completion: {_ in
self.changeState(to: .appeared)
}
)
}
private func animateDismissing(dismissType: InfoMessageViewDismissType) {
guard
let messageView = self.messageView,
let container = self.container
else { return }
UIView.animate(
withDuration: 0.3,
delay: 0,
options: .curveEaseOut,
animations: {
self.behavior.dismiss(messageView: messageView, in: container)
},
completion: {_ in
self.changeState(to: .dismissed)
self.onDismiss?(dismissType)
}
)
}
}
| mit |
khizkhiz/swift | test/SILGen/generic_closures.swift | 2 | 6087 | // RUN: %target-swift-frontend -parse-stdlib -emit-silgen %s | FileCheck %s
import Swift
var zero: Int
// CHECK-LABEL: sil hidden @_TF16generic_closures28generic_nondependent_context{{.*}}
func generic_nondependent_context<T>(x: T, y: Int) -> Int {
func foo() -> Int { return y }
// CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures28generic_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]
return foo()
}
// CHECK-LABEL: sil hidden @_TF16generic_closures15generic_capture{{.*}}
func generic_capture<T>(x: T) -> Any.Type {
func foo() -> Any.Type { return T.self }
// CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures15generic_capture{{.*}} : $@convention(thin) <τ_0_0> () -> @thick protocol<>.Type
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]
return foo()
}
// CHECK-LABEL: sil hidden @_TF16generic_closures20generic_capture_cast{{.*}}
func generic_capture_cast<T>(x: T, y: Any) -> Bool {
func foo(a: Any) -> Bool { return a is T }
// CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures20generic_capture_cast{{.*}} : $@convention(thin) <τ_0_0> (@in protocol<>) -> Bool
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]
return foo(y)
}
protocol Concept {
var sensical: Bool { get }
}
// CHECK-LABEL: sil hidden @_TF16generic_closures29generic_nocapture_existential{{.*}}
func generic_nocapture_existential<T>(x: T, y: Concept) -> Bool {
func foo(a: Concept) -> Bool { return a.sensical }
// CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures29generic_nocapture_existential{{.*}} : $@convention(thin) (@in Concept) -> Bool
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]
return foo(y)
}
// CHECK-LABEL: sil hidden @_TF16generic_closures25generic_dependent_context{{.*}}
func generic_dependent_context<T>(x: T, y: Int) -> T {
func foo() -> T { return x }
// CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures25generic_dependent_context{{.*}} : $@convention(thin) <τ_0_0> (@owned @box τ_0_0) -> @out τ_0_0
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T>
return foo()
}
enum Optionable<Wrapped> {
case none
case some(Wrapped)
}
class NestedGeneric<U> {
class func generic_nondependent_context<T>(x: T, y: Int, z: U) -> Int {
func foo() -> Int { return y }
return foo()
}
class func generic_dependent_inner_context<T>(x: T, y: Int, z: U) -> T {
func foo() -> T { return x }
return foo()
}
class func generic_dependent_outer_context<T>(x: T, y: Int, z: U) -> U {
func foo() -> U { return z }
return foo()
}
class func generic_dependent_both_contexts<T>(x: T, y: Int, z: U) -> (T, U) {
func foo() -> (T, U) { return (x, z) }
return foo()
}
// CHECK-LABEL: sil hidden @_TFC16generic_closures13NestedGeneric20nested_reabstraction{{.*}}
// CHECK: [[REABSTRACT:%.*]] = function_ref @_TTRG__rXFo___XFo_iT__iT__
// CHECK: partial_apply [[REABSTRACT]]<U, T>
func nested_reabstraction<T>(x: T) -> Optionable<() -> ()> {
return .some({})
}
}
// <rdar://problem/15417773>
// Ensure that nested closures capture the generic parameters of their nested
// context.
// CHECK: sil hidden @_TF16generic_closures25nested_closure_in_generic{{.*}} : $@convention(thin) <T> (@in T) -> @out T
// CHECK: function_ref [[OUTER_CLOSURE:@_TFF16generic_closures25nested_closure_in_genericurFxxU_FT_Q_]]
// CHECK: sil shared [[OUTER_CLOSURE]] : $@convention(thin) <T> (@inout_aliasable T) -> @out T
// CHECK: function_ref [[INNER_CLOSURE:@_TFFF16generic_closures25nested_closure_in_genericurFxxU_FT_Q_U_FT_Q_]]
// CHECK: sil shared [[INNER_CLOSURE]] : $@convention(thin) <T> (@inout_aliasable T) -> @out T {
func nested_closure_in_generic<T>(x:T) -> T {
return { { x }() }()
}
// CHECK-LABEL: sil hidden @_TF16generic_closures16local_properties
func local_properties<T>(t: inout T) {
// CHECK: [[TBOX:%[0-9]+]] = alloc_box $T
var prop: T {
get {
return t
}
set {
t = newValue
}
}
// CHECK: [[GETTER_REF:%[0-9]+]] = function_ref [[GETTER_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@owned @box τ_0_0) -> @out τ_0_0
// CHECK: apply [[GETTER_REF]]
t = prop
// CHECK: [[SETTER_REF:%[0-9]+]] = function_ref [[SETTER_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@in τ_0_0, @owned @box τ_0_0) -> ()
// CHECK: apply [[SETTER_REF]]
prop = t
var prop2: T {
get {
return t
}
set {
// doesn't capture anything
}
}
// CHECK: [[GETTER2_REF:%[0-9]+]] = function_ref [[GETTER2_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@owned @box τ_0_0) -> @out τ_0_0
// CHECK: apply [[GETTER2_REF]]
t = prop2
// CHECK: [[SETTER2_REF:%[0-9]+]] = function_ref [[SETTER2_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@in τ_0_0) -> ()
// CHECK: apply [[SETTER2_REF]]
prop2 = t
}
protocol Fooable {
static func foo() -> Bool
}
// <rdar://problem/16399018>
func shmassert(@autoclosure f: () -> Bool) {}
// CHECK-LABEL: sil hidden @_TF16generic_closures21capture_generic_param
func capture_generic_param<A: Fooable>(x: A) {
shmassert(A.foo())
}
// Make sure we use the correct convention when capturing class-constrained
// member types: <rdar://problem/24470533>
class Class {}
protocol HasClassAssoc { associatedtype Assoc : Class }
// CHECK-LABEL: sil hidden @_TF16generic_closures34captures_class_constrained_genericuRxS_13HasClassAssocrFTx1fFwx5AssocwxS1__T_
// CHECK: bb0(%0 : $*T, %1 : $@callee_owned (@owned T.Assoc) -> @owned T.Assoc):
// CHECK: [[GENERIC_FN:%.*]] = function_ref @_TFF16generic_closures34captures_class_constrained_genericuRxS_13HasClassAssocrFTx1fFwx5AssocwxS1__T_U_FT_FQQ_5AssocS2_
// CHECK: [[CONCRETE_FN:%.*]] = partial_apply [[GENERIC_FN]]<T, T.Assoc>(%1)
func captures_class_constrained_generic<T : HasClassAssoc>(x: T, f: T.Assoc -> T.Assoc) {
let _: () -> T.Assoc -> T.Assoc = { f }
}
| apache-2.0 |
siegesmund/SwiftDDP | Package.swift | 1 | 1391 | // swift-tools-version:4.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "SwiftDDP",
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "SwiftDDP",
targets: ["SwiftDDP"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
.package(url: "https://github.com/DaveWoodCom/XCGLogger.git", from: "6.0.0"),
.package(url: "https://github.com/krzyzanowskim/CryptoSwift.git", from: "0.12.0"),
.package(url: "https://github.com/tidwall/SwiftWebSocket.git", from: "2.7.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "SwiftDDP",
dependencies: ["XCGLogger", "CryptoSwift", "SwiftWebSocket"],
path: "Sources"),
.testTarget(
name: "SwiftDDPTests",
dependencies: ["SwiftDDP"],
path: "SwiftDDPTests"),
]
)
| mit |
slavapestov/swift | test/decl/subscript/subscripting.swift | 1 | 7538 | // RUN: %target-parse-verify-swift
struct X { }
// Simple examples
struct X1 {
var stored : Int
subscript (i : Int) -> Int {
get {
return stored
}
mutating
set {
stored = newValue
}
}
}
struct X2 {
var stored : Int
subscript (i : Int) -> Int {
get {
return stored + i
}
set(v) {
stored = v - i
}
}
}
struct X3 {
var stored : Int
subscript (_ : Int) -> Int {
get {
return stored
}
set(v) {
stored = v
}
}
}
struct X4 {
var stored : Int
subscript (i : Int, j : Int) -> Int {
get {
return stored + i + j
}
set(v) {
stored = v + i - j
}
}
}
// Semantic errors
struct Y1 {
var x : X
subscript(i: Int) -> Int {
get {
return x // expected-error{{cannot convert return expression of type 'X' to return type 'Int'}}
}
set {
x = newValue // expected-error{{cannot assign value of type 'Int' to type 'X'}}
}
}
}
struct Y2 {
subscript(idx: Int) -> TypoType { // expected-error 3{{use of undeclared type 'TypoType'}}
get { repeat {} while true }
set {}
}
}
class Y3 {
subscript(idx: Int) -> TypoType { // expected-error 3{{use of undeclared type 'TypoType'}}
get { repeat {} while true }
set {}
}
}
protocol ProtocolGetSet0 {
subscript(i: Int) -> Int {} // expected-error {{subscript declarations must have a getter}}
}
protocol ProtocolGetSet1 {
subscript(i: Int) -> Int { get }
}
protocol ProtocolGetSet2 {
subscript(i: Int) -> Int { set } // expected-error {{subscript declarations must have a getter}}
}
protocol ProtocolGetSet3 {
subscript(i: Int) -> Int { get set }
}
protocol ProtocolGetSet4 {
subscript(i: Int) -> Int { set get }
}
protocol ProtocolWillSetDidSet1 {
subscript(i: Int) -> Int { willSet } // expected-error {{expected get or set in a protocol property}}
}
protocol ProtocolWillSetDidSet2 {
subscript(i: Int) -> Int { didSet } // expected-error {{expected get or set in a protocol property}}
}
protocol ProtocolWillSetDidSet3 {
subscript(i: Int) -> Int { willSet didSet } // expected-error {{expected get or set in a protocol property}}
}
protocol ProtocolWillSetDidSet4 {
subscript(i: Int) -> Int { didSet willSet } // expected-error {{expected get or set in a protocol property}}
}
class DidSetInSubscript {
subscript(_: Int) -> Int {
didSet { // expected-error {{didSet is not allowed in subscripts}}
print("eek")
}
get {}
}
}
class WillSetInSubscript {
subscript(_: Int) -> Int {
willSet { // expected-error {{willSet is not allowed in subscripts}}
print("eek")
}
get {}
}
}
subscript(i: Int) -> Int { // expected-error{{'subscript' functions may only be declared within a type}}
get {}
}
func f() {
subscript (i: Int) -> Int { // expected-error{{'subscript' functions may only be declared within a type}}
get {}
}
}
struct NoSubscript { }
struct OverloadedSubscript {
subscript(i: Int) -> Int {
get {
return i
}
set {}
}
subscript(i: Int, j: Int) -> Int {
get { return i }
set {}
}
}
struct RetOverloadedSubscript {
subscript(i: Int) -> Int { // expected-note {{found this candidate}}
get { return i }
set {}
}
subscript(i: Int) -> Float { // expected-note {{found this candidate}}
get { return Float(i) }
set {}
}
}
struct MissingGetterSubscript1 {
subscript (i : Int) -> Int {
} // expected-error {{computed property must have accessors specified}}
}
struct MissingGetterSubscript2 {
subscript (i : Int, j : Int) -> Int { // expected-error{{subscript declarations must have a getter}}
set {}
}
}
func test_subscript(inout x2: X2, i: Int, j: Int, inout value: Int, no: NoSubscript,
inout ovl: OverloadedSubscript, inout ret: RetOverloadedSubscript) {
no[i] = value // expected-error{{type 'NoSubscript' has no subscript members}}
value = x2[i]
x2[i] = value
value = ovl[i]
ovl[i] = value
value = ovl[(i, j)]
ovl[(i, j)] = value
value = ovl[(i, j, i)] // expected-error{{cannot subscript a value of type 'OverloadedSubscript' with an index of type '(Int, Int, Int)'}}
// expected-note @-1 {{expected an argument list of type '(Int)'}}
ret[i] // expected-error{{ambiguous use of 'subscript'}}
value = ret[i]
ret[i] = value
}
func subscript_rvalue_materialize(inout i: Int) {
i = X1(stored: 0)[i]
}
func subscript_coerce(fn: ([UnicodeScalar], [UnicodeScalar]) -> Bool) {}
func test_subscript_coerce() {
subscript_coerce({ $0[$0.count-1] < $1[$1.count-1] })
}
struct no_index {
subscript () -> Int { return 42 }
func test() -> Int {
return self[]
}
}
struct tuple_index {
subscript (x : Int, y : Int) -> (Int, Int) { return (x, y) }
func test() -> (Int, Int) {
return self[123, 456]
}
}
struct SubscriptTest1 {
subscript(keyword:String) -> Bool { return true } // expected-note 2 {{found this candidate}}
subscript(keyword:String) -> String? {return nil } // expected-note 2 {{found this candidate}}
}
func testSubscript1(s1 : SubscriptTest1) {
let _ : Int = s1["hello"] // expected-error {{ambiguous subscript with base type 'SubscriptTest1' and index type 'String'}}
if s1["hello"] {}
let _ = s1["hello"] // expected-error {{ambiguous use of 'subscript'}}
}
struct SubscriptTest2 {
subscript(a : String, b : Int) -> Int { return 0 }
subscript(a : String, b : String) -> Int { return 0 }
}
func testSubscript1(s2 : SubscriptTest2) {
_ = s2["foo"] // expected-error {{cannot subscript a value of type 'SubscriptTest2' with an index of type 'String'}}
// expected-note @-1 {{overloads for 'subscript' exist with these partially matching parameter lists: (String, Int), (String, String)}}
let a = s2["foo", 1.0] // expected-error {{cannot subscript a value of type 'SubscriptTest2' with an index of type '(String, Double)'}}
// expected-note @-1 {{overloads for 'subscript' exist with these partially matching parameter lists: (String, Int), (String, String)}}
let b = s2[1, "foo"] // expected-error {{cannot subscript a value of type 'SubscriptTest2' with an index of type '(Int, String)'}}
// expected-note @-1 {{expected an argument list of type '(String, String)'}}
}
// sr-114 & rdar://22007370
class Foo {
subscript(key: String) -> String { // expected-note {{'subscript' previously declared here}}
get { a } // expected-error {{use of unresolved identifier 'a'}}
set { b } // expected-error {{use of unresolved identifier 'b'}}
}
subscript(key: String) -> String { // expected-error {{invalid redeclaration of 'subscript'}}
get { a } // expected-error {{use of unresolved identifier 'a'}}
set { b } // expected-error {{use of unresolved identifier 'b'}}
}
}
// <rdar://problem/23952125> QoI: Subscript in protocol with missing {}, better diagnostic please
protocol r23952125 {
associatedtype ItemType
var count: Int { get }
subscript(index: Int) -> ItemType // expected-error {{subscript in protocol must have explicit { get } or { get set } specifier}} {{36-36= { get set \}}}
var c : Int // expected-error {{property in protocol must have explicit { get } or { get set } specifier}}
}
// <rdar://problem/16812341> QoI: Poor error message when providing a default value for a subscript parameter
struct S4 {
subscript(subs: Int = 0) -> Int { // expected-error {{default arguments are not allowed in subscripts}}
get {
return 1
}
}
}
| apache-2.0 |
ioscreator/ioscreator | IOSDynamicTypesTutorial/IOSDynamicTypesTutorial/AppDelegate.swift | 1 | 2197 | //
// AppDelegate.swift
// IOSDynamicTypesTutorial
//
// Created by Arthur Knopper on 13/03/2019.
// Copyright © 2019 Arthur Knopper. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
CrazyZhangSanFeng/BanTang | BanTang/BanTang/Classes/Home/Model/BTHomeTopic.swift | 1 | 768 | //
// BTHomeTopic.swift
// BanTang
//
// Created by 张灿 on 16/6/6.
// Copyright © 2016年 张灿. All rights reserved.
//
import UIKit
import MJExtension
class BTHomeTopic: NSObject {
/** id */
var ID: String = ""
/** 标题 */
var title: String = ""
/** 类型 */
var type: String = ""
/** 图片 */
var pic: String = ""
/** 是否显示喜欢 */
var is_show_like: Bool = false
/** 是否喜欢 */
var islike:Bool = false
/** 喜欢的人数 */
var likes: String = ""
/** 用户模型 */
var user : BTTopicUserItem?
override static func mj_replacedKeyFromPropertyName() -> [NSObject : AnyObject]! {
return ["ID": "id"]
}
}
| apache-2.0 |
Mindera/Alicerce | Tests/AlicerceTests/TestUtils.swift | 1 | 2831 | import UIKit
import XCTest
final class TestDummy {}
func dataFromFile(withName name: String, type: String, bundleClass: AnyClass = TestDummy.self) -> Data {
let filePath = Bundle(for: bundleClass).path(forResource: name, ofType: type)
guard
let path = filePath,
let data = try? Data(contentsOf: URL(fileURLWithPath: path))
else {
fatalError("🔥 File not found or invalid data!")
}
return data
}
func stringFromFile(withName name: String, type: String, bundleClass: AnyClass = TestDummy.self) -> String {
let filePath = Bundle(for: bundleClass).path(forResource: name, ofType: type)
guard
let path = filePath,
let string = try? String(contentsOf: URL(fileURLWithPath: path))
else {
fatalError("🔥 File not found or invalid data!")
}
return string
}
func jsonFromFile(withName name: String,
options: JSONSerialization.ReadingOptions = .mutableContainers,
bundleClass: AnyClass = TestDummy.self) -> Any {
let jsonData = dataFromFile(withName: name, type: "json", bundleClass: bundleClass)
return try! JSONSerialization.jsonObject(with: jsonData, options: options)
}
func imageFromFile(withName name: String, type: String, bundleClass: AnyClass = TestDummy.self) -> UIImage {
let imageData = dataFromFile(withName: name, type: type, bundleClass: bundleClass)
return UIImage(data: imageData)!
}
func dataFromImage(_ image: UIImage) -> Data {
guard let data = image.pngData() else {
assertionFailure("💥 Could not convert image into data 😱")
return Data()
}
return data
}
extension UIView {
static func instantiateFromNib<T: UIView>(withOwner owner: Any?,
nibName: String = "Views",
bundle: Bundle = Bundle(for: T.self)) -> T? {
let nib = UINib(nibName: nibName, bundle: bundle)
return nib.instantiate(withOwner: owner, options: nil).compactMap { $0 as? T }.first
}
}
public func XCTAssertDumpsEqual<T>(_ lhs: @autoclosure () -> T,
_ rhs: @autoclosure () -> T,
message: @autoclosure () -> String = "Expected dumps to be equal.",
file: StaticString = #file,
line: UInt = #line) {
XCTAssertEqual(String(dumping: lhs()), String(dumping: rhs()), message(), file: file, line: line)
}
extension String {
func url(file: StaticString = #file, line: UInt = #line) -> URL {
guard let url = URL(string: self) else {
XCTFail("🔥 failed to create URL from '\(self)!'", file: file, line: line)
return URL(string: "/")!
}
return url
}
}
| mit |
kwakuoowusu/tipApp | tipsTests/tipsTests.swift | 1 | 962 | //
// tipsTests.swift
// tipsTests
//
// Created by Kwaku Owusu on 12/1/15.
// Copyright © 2015 Kwaku Owusu. All rights reserved.
//
import XCTest
@testable import tips
class tipsTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| gpl-2.0 |
themonki/onebusaway-iphone | Carthage/Checkouts/swift-protobuf/Sources/SwiftProtobuf/TextFormatScanner.swift | 1 | 35871 | // Sources/SwiftProtobuf/TextFormatScanner.swift - Text format decoding
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Test format decoding engine.
///
// -----------------------------------------------------------------------------
import Foundation
private let asciiBell = UInt8(7)
private let asciiBackspace = UInt8(8)
private let asciiTab = UInt8(9)
private let asciiNewLine = UInt8(10)
private let asciiVerticalTab = UInt8(11)
private let asciiFormFeed = UInt8(12)
private let asciiCarriageReturn = UInt8(13)
private let asciiZero = UInt8(ascii: "0")
private let asciiOne = UInt8(ascii: "1")
private let asciiThree = UInt8(ascii: "3")
private let asciiSeven = UInt8(ascii: "7")
private let asciiNine = UInt8(ascii: "9")
private let asciiColon = UInt8(ascii: ":")
private let asciiPeriod = UInt8(ascii: ".")
private let asciiPlus = UInt8(ascii: "+")
private let asciiComma = UInt8(ascii: ",")
private let asciiSemicolon = UInt8(ascii: ";")
private let asciiDoubleQuote = UInt8(ascii: "\"")
private let asciiSingleQuote = UInt8(ascii: "\'")
private let asciiBackslash = UInt8(ascii: "\\")
private let asciiForwardSlash = UInt8(ascii: "/")
private let asciiHash = UInt8(ascii: "#")
private let asciiUnderscore = UInt8(ascii: "_")
private let asciiQuestionMark = UInt8(ascii: "?")
private let asciiSpace = UInt8(ascii: " ")
private let asciiOpenSquareBracket = UInt8(ascii: "[")
private let asciiCloseSquareBracket = UInt8(ascii: "]")
private let asciiOpenCurlyBracket = UInt8(ascii: "{")
private let asciiCloseCurlyBracket = UInt8(ascii: "}")
private let asciiOpenAngleBracket = UInt8(ascii: "<")
private let asciiCloseAngleBracket = UInt8(ascii: ">")
private let asciiMinus = UInt8(ascii: "-")
private let asciiLowerA = UInt8(ascii: "a")
private let asciiUpperA = UInt8(ascii: "A")
private let asciiLowerB = UInt8(ascii: "b")
private let asciiLowerE = UInt8(ascii: "e")
private let asciiUpperE = UInt8(ascii: "E")
private let asciiLowerF = UInt8(ascii: "f")
private let asciiUpperF = UInt8(ascii: "F")
private let asciiLowerI = UInt8(ascii: "i")
private let asciiLowerL = UInt8(ascii: "l")
private let asciiLowerN = UInt8(ascii: "n")
private let asciiLowerR = UInt8(ascii: "r")
private let asciiLowerS = UInt8(ascii: "s")
private let asciiLowerT = UInt8(ascii: "t")
private let asciiUpperT = UInt8(ascii: "T")
private let asciiLowerU = UInt8(ascii: "u")
private let asciiLowerV = UInt8(ascii: "v")
private let asciiLowerX = UInt8(ascii: "x")
private let asciiLowerY = UInt8(ascii: "y")
private let asciiLowerZ = UInt8(ascii: "z")
private let asciiUpperZ = UInt8(ascii: "Z")
private func fromHexDigit(_ c: UInt8) -> UInt8? {
if c >= asciiZero && c <= asciiNine {
return c - asciiZero
}
if c >= asciiUpperA && c <= asciiUpperF {
return c - asciiUpperA + UInt8(10)
}
if c >= asciiLowerA && c <= asciiLowerF {
return c - asciiLowerA + UInt8(10)
}
return nil
}
// Protobuf Text encoding assumes that you're working directly
// in UTF-8. So this implementation converts the string to UTF8,
// then decodes it into a sequence of bytes, then converts
// it back into a string.
private func decodeString(_ s: String) -> String? {
var out = [UInt8]()
var bytes = s.utf8.makeIterator()
while let byte = bytes.next() {
switch byte {
case asciiBackslash: // backslash
if let escaped = bytes.next() {
switch escaped {
case asciiZero...asciiSeven: // 0...7
// C standard allows 1, 2, or 3 octal digits.
let savedPosition = bytes
let digit1 = escaped
let digit1Value = digit1 - asciiZero
if let digit2 = bytes.next(),
digit2 >= asciiZero && digit2 <= asciiSeven {
let digit2Value = digit2 - asciiZero
let innerSavedPosition = bytes
if let digit3 = bytes.next(),
digit3 >= asciiZero && digit3 <= asciiSeven {
let digit3Value = digit3 - asciiZero
let n = digit1Value * 64 + digit2Value * 8 + digit3Value
out.append(n)
} else {
let n = digit1Value * 8 + digit2Value
out.append(n)
bytes = innerSavedPosition
}
} else {
let n = digit1Value
out.append(n)
bytes = savedPosition
}
case asciiLowerX: // "x"
// Unlike C/C++, protobuf only allows 1 or 2 digits here:
if let byte = bytes.next(), let digit = fromHexDigit(byte) {
var n = digit
let savedPosition = bytes
if let byte = bytes.next(), let digit = fromHexDigit(byte) {
n = n &* 16 + digit
} else {
// No second digit; reset the iterator
bytes = savedPosition
}
out.append(n)
} else {
return nil // Hex escape must have at least 1 digit
}
case asciiLowerA: // \a
out.append(asciiBell)
case asciiLowerB: // \b
out.append(asciiBackspace)
case asciiLowerF: // \f
out.append(asciiFormFeed)
case asciiLowerN: // \n
out.append(asciiNewLine)
case asciiLowerR: // \r
out.append(asciiCarriageReturn)
case asciiLowerT: // \t
out.append(asciiTab)
case asciiLowerV: // \v
out.append(asciiVerticalTab)
case asciiDoubleQuote,
asciiSingleQuote,
asciiQuestionMark,
asciiBackslash: // " ' ? \
out.append(escaped)
default:
return nil // Unrecognized escape
}
} else {
return nil // Input ends with backslash
}
default:
out.append(byte)
}
}
// There has got to be an easier way to convert a [UInt8] into a String.
return out.withUnsafeBufferPointer { ptr in
if let addr = ptr.baseAddress {
return utf8ToString(bytes: addr, count: ptr.count)
} else {
return String()
}
}
}
///
/// TextFormatScanner has no public members.
///
internal struct TextFormatScanner {
internal var extensions: ExtensionMap?
private var p: UnsafePointer<UInt8>
private var end: UnsafePointer<UInt8>
private var doubleFormatter = DoubleFormatter()
internal var complete: Bool {
mutating get {
return p == end
}
}
internal init(utf8Pointer: UnsafePointer<UInt8>, count: Int, extensions: ExtensionMap? = nil) {
p = utf8Pointer
end = p + count
self.extensions = extensions
skipWhitespace()
}
/// Skip whitespace
private mutating func skipWhitespace() {
while p != end {
let u = p[0]
switch u {
case asciiSpace,
asciiTab,
asciiNewLine,
asciiCarriageReturn: // space, tab, NL, CR
p += 1
case asciiHash: // # comment
p += 1
while p != end {
// Skip until end of line
let c = p[0]
p += 1
if c == asciiNewLine || c == asciiCarriageReturn {
break
}
}
default:
return
}
}
}
/// Return a buffer containing the raw UTF8 for an identifier.
/// Assumes that you already know the current byte is a valid
/// start of identifier.
private mutating func parseUTF8Identifier() -> UnsafeBufferPointer<UInt8> {
let start = p
loop: while p != end {
let c = p[0]
switch c {
case asciiLowerA...asciiLowerZ,
asciiUpperA...asciiUpperZ,
asciiZero...asciiNine,
asciiUnderscore:
p += 1
default:
break loop
}
}
let s = UnsafeBufferPointer(start: start, count: p - start)
skipWhitespace()
return s
}
/// Return a String containing the next identifier.
private mutating func parseIdentifier() -> String {
let buff = parseUTF8Identifier()
let s = utf8ToString(bytes: buff.baseAddress!, count: buff.count)
// Force-unwrap is OK: we never have invalid UTF8 at this point.
return s!
}
/// Parse the rest of an [extension_field_name] in the input, assuming the
/// initial "[" character has already been read (and is in the prefix)
/// This is also used for AnyURL, so we include "/", "."
private mutating func parseExtensionKey() -> String? {
let start = p
if p == end {
return nil
}
let c = p[0]
switch c {
case asciiLowerA...asciiLowerZ, asciiUpperA...asciiUpperZ:
p += 1
default:
return nil
}
while p != end {
let c = p[0]
switch c {
case asciiLowerA...asciiLowerZ,
asciiUpperA...asciiUpperZ,
asciiZero...asciiNine,
asciiUnderscore,
asciiPeriod,
asciiForwardSlash:
p += 1
case asciiCloseSquareBracket: // ]
return utf8ToString(bytes: start, count: p - start)
default:
return nil
}
}
return nil
}
/// Scan a string that encodes a byte field, return a count of
/// the number of bytes that should be decoded from it
private mutating func validateAndCountBytesFromString(terminator: UInt8, sawBackslash: inout Bool) throws -> Int {
var count = 0
let start = p
sawBackslash = false
while p != end {
let byte = p[0]
p += 1
if byte == terminator {
p = start
return count
}
switch byte {
case asciiBackslash: // "\\"
sawBackslash = true
if p != end {
let escaped = p[0]
p += 1
switch escaped {
case asciiZero...asciiSeven: // '0'...'7'
// C standard allows 1, 2, or 3 octal digits.
if p != end, p[0] >= asciiZero, p[0] <= asciiSeven {
p += 1
if p != end, p[0] >= asciiZero, p[0] <= asciiSeven {
if escaped > asciiThree {
// Out of range octal: three digits and first digit is greater than 3
throw TextFormatDecodingError.malformedText
}
p += 1
}
}
count += 1
case asciiLowerX: // 'x' hexadecimal escape
if p != end && fromHexDigit(p[0]) != nil {
p += 1
if p != end && fromHexDigit(p[0]) != nil {
p += 1
}
} else {
throw TextFormatDecodingError.malformedText // Hex escape must have at least 1 digit
}
count += 1
case asciiLowerA, // \a ("alert")
asciiLowerB, // \b
asciiLowerF, // \f
asciiLowerN, // \n
asciiLowerR, // \r
asciiLowerT, // \t
asciiLowerV, // \v
asciiSingleQuote, // \'
asciiDoubleQuote, // \"
asciiQuestionMark, // \?
asciiBackslash: // \\
count += 1
default:
throw TextFormatDecodingError.malformedText // Unrecognized escape
}
}
default:
count += 1
}
}
throw TextFormatDecodingError.malformedText
}
/// Protobuf Text format uses C ASCII conventions for
/// encoding byte sequences, including the use of octal
/// and hexadecimal escapes.
///
/// Assumes that validateAndCountBytesFromString() has already
/// verified the correctness. So we get to avoid error checks here.
private mutating func parseBytesFromString(terminator: UInt8, into data: inout Data) {
data.withUnsafeMutableBytes {
(dataPointer: UnsafeMutablePointer<UInt8>) in
var out = dataPointer
while p[0] != terminator {
let byte = p[0]
p += 1
switch byte {
case asciiBackslash: // "\\"
let escaped = p[0]
p += 1
switch escaped {
case asciiZero...asciiSeven: // '0'...'7'
// C standard allows 1, 2, or 3 octal digits.
let digit1Value = escaped - asciiZero
let digit2 = p[0]
if digit2 >= asciiZero, digit2 <= asciiSeven {
p += 1
let digit2Value = digit2 - asciiZero
let digit3 = p[0]
if digit3 >= asciiZero, digit3 <= asciiSeven {
p += 1
let digit3Value = digit3 - asciiZero
out[0] = digit1Value &* 64 + digit2Value * 8 + digit3Value
out += 1
} else {
out[0] = digit1Value * 8 + digit2Value
out += 1
}
} else {
out[0] = digit1Value
out += 1
}
case asciiLowerX: // 'x' hexadecimal escape
// We already validated, so we know there's at least one digit:
var n = fromHexDigit(p[0])!
p += 1
if let digit = fromHexDigit(p[0]) {
n = n &* 16 &+ digit
p += 1
}
out[0] = n
out += 1
case asciiLowerA: // \a ("alert")
out[0] = asciiBell
out += 1
case asciiLowerB: // \b
out[0] = asciiBackspace
out += 1
case asciiLowerF: // \f
out[0] = asciiFormFeed
out += 1
case asciiLowerN: // \n
out[0] = asciiNewLine
out += 1
case asciiLowerR: // \r
out[0] = asciiCarriageReturn
out += 1
case asciiLowerT: // \t
out[0] = asciiTab
out += 1
case asciiLowerV: // \v
out[0] = asciiVerticalTab
out += 1
default:
out[0] = escaped
out += 1
}
default:
out[0] = byte
out += 1
}
}
p += 1 // Consume terminator
}
}
/// Assumes the leading quote has already been consumed
private mutating func parseStringSegment(terminator: UInt8) -> String? {
let start = p
var sawBackslash = false
while p != end {
let c = p[0]
if c == terminator {
let s = utf8ToString(bytes: start, count: p - start)
p += 1
skipWhitespace()
if let s = s, sawBackslash {
return decodeString(s)
} else {
return s
}
}
p += 1
if c == asciiBackslash { // \
if p == end {
return nil
}
sawBackslash = true
p += 1
}
}
return nil // Unterminated quoted string
}
internal mutating func nextUInt() throws -> UInt64 {
if p == end {
throw TextFormatDecodingError.malformedNumber
}
let c = p[0]
p += 1
if c == asciiZero { // leading '0' precedes octal or hex
if p[0] == asciiLowerX { // 'x' => hex
p += 1
var n: UInt64 = 0
while p != end {
let digit = p[0]
let val: UInt64
switch digit {
case asciiZero...asciiNine: // 0...9
val = UInt64(digit - asciiZero)
case asciiLowerA...asciiLowerF: // a...f
val = UInt64(digit - asciiLowerA + 10)
case asciiUpperA...asciiUpperF:
val = UInt64(digit - asciiUpperA + 10)
case asciiLowerU: // trailing 'u'
p += 1
skipWhitespace()
return n
default:
skipWhitespace()
return n
}
if n > UInt64.max / 16 {
throw TextFormatDecodingError.malformedNumber
}
p += 1
n = n * 16 + val
}
skipWhitespace()
return n
} else { // octal
var n: UInt64 = 0
while p != end {
let digit = p[0]
if digit == asciiLowerU { // trailing 'u'
p += 1
skipWhitespace()
return n
}
if digit < asciiZero || digit > asciiSeven {
skipWhitespace()
return n // not octal digit
}
let val = UInt64(digit - asciiZero)
if n > UInt64.max / 8 {
throw TextFormatDecodingError.malformedNumber
}
p += 1
n = n * 8 + val
}
skipWhitespace()
return n
}
} else if c > asciiZero && c <= asciiNine { // 1...9
var n = UInt64(c - asciiZero)
while p != end {
let digit = p[0]
if digit == asciiLowerU { // trailing 'u'
p += 1
skipWhitespace()
return n
}
if digit < asciiZero || digit > asciiNine {
skipWhitespace()
return n // not a digit
}
let val = UInt64(digit - asciiZero)
if n > UInt64.max / 10 || n * 10 > UInt64.max - val {
throw TextFormatDecodingError.malformedNumber
}
p += 1
n = n * 10 + val
}
skipWhitespace()
return n
}
throw TextFormatDecodingError.malformedNumber
}
internal mutating func nextSInt() throws -> Int64 {
if p == end {
throw TextFormatDecodingError.malformedNumber
}
let c = p[0]
if c == asciiMinus { // -
p += 1
// character after '-' must be digit
let digit = p[0]
if digit < asciiZero || digit > asciiNine {
throw TextFormatDecodingError.malformedNumber
}
let n = try nextUInt()
let limit: UInt64 = 0x8000000000000000 // -Int64.min
if n >= limit {
if n > limit {
// Too large negative number
throw TextFormatDecodingError.malformedNumber
} else {
return Int64.min // Special case for Int64.min
}
}
return -Int64(bitPattern: n)
} else {
let n = try nextUInt()
if n > UInt64(bitPattern: Int64.max) {
throw TextFormatDecodingError.malformedNumber
}
return Int64(bitPattern: n)
}
}
internal mutating func nextStringValue() throws -> String {
var result: String
skipWhitespace()
if p == end {
throw TextFormatDecodingError.malformedText
}
let c = p[0]
if c != asciiSingleQuote && c != asciiDoubleQuote {
throw TextFormatDecodingError.malformedText
}
p += 1
if let s = parseStringSegment(terminator: c) {
result = s
} else {
throw TextFormatDecodingError.malformedText
}
while true {
if p == end {
return result
}
let c = p[0]
if c != asciiSingleQuote && c != asciiDoubleQuote {
return result
}
p += 1
if let s = parseStringSegment(terminator: c) {
result.append(s)
} else {
throw TextFormatDecodingError.malformedText
}
}
}
/// Protobuf Text Format allows a single bytes field to
/// contain multiple quoted strings. The values
/// are separately decoded and then concatenated:
/// field1: "bytes" 'more bytes'
/// "and even more bytes"
internal mutating func nextBytesValue() throws -> Data {
// Get the first string's contents
var result: Data
skipWhitespace()
if p == end {
throw TextFormatDecodingError.malformedText
}
let c = p[0]
if c != asciiSingleQuote && c != asciiDoubleQuote {
throw TextFormatDecodingError.malformedText
}
p += 1
var sawBackslash = false
let n = try validateAndCountBytesFromString(terminator: c, sawBackslash: &sawBackslash)
if sawBackslash {
result = Data(count: n)
parseBytesFromString(terminator: c, into: &result)
} else {
result = Data(bytes: p, count: n)
p += n + 1 // Skip string body + close quote
}
// If there are more strings, decode them
// and append to the result:
while true {
skipWhitespace()
if p == end {
return result
}
let c = p[0]
if c != asciiSingleQuote && c != asciiDoubleQuote {
return result
}
p += 1
var sawBackslash = false
let n = try validateAndCountBytesFromString(terminator: c, sawBackslash: &sawBackslash)
if sawBackslash {
var b = Data(count: n)
parseBytesFromString(terminator: c, into: &b)
result.append(b)
} else {
result.append(p, count: n)
p += n + 1 // Skip string body + close quote
}
}
}
// Tries to identify a sequence of UTF8 characters
// that represent a numeric floating-point value.
private mutating func tryParseFloatString() -> Double? {
guard p != end else {return nil}
let start = p
var c = p[0]
if c == asciiMinus {
p += 1
guard p != end else {p = start; return nil}
c = p[0]
}
switch c {
case asciiZero: // '0' as first character is not allowed followed by digit
p += 1
guard p != end else {break}
c = p[0]
if c >= asciiZero && c <= asciiNine {
p = start
return nil
}
case asciiPeriod: // '.' as first char only if followed by digit
p += 1
guard p != end else {p = start; return nil}
c = p[0]
if c < asciiZero || c > asciiNine {
p = start
return nil
}
case asciiOne...asciiNine:
break
default:
p = start
return nil
}
loop: while p != end {
let c = p[0]
switch c {
case asciiZero...asciiNine,
asciiPeriod,
asciiPlus,
asciiMinus,
asciiLowerE,
asciiUpperE: // 0...9, ., +, -, e, E
p += 1
case asciiLowerF: // f
// proto1 allowed floats to be suffixed with 'f'
let d = doubleFormatter.utf8ToDouble(bytes: start, count: p - start)
// Just skip the 'f'
p += 1
skipWhitespace()
return d
default:
break loop
}
}
let d = doubleFormatter.utf8ToDouble(bytes: start, count: p - start)
skipWhitespace()
return d
}
// Skip specified characters if they all match
private mutating func skipOptionalCharacters(bytes: [UInt8]) {
let start = p
for b in bytes {
if p == end || p[0] != b {
p = start
return
}
p += 1
}
}
// Skip following keyword if it matches (case-insensitively)
// the given keyword (specified as a series of bytes).
private mutating func skipOptionalKeyword(bytes: [UInt8]) -> Bool {
let start = p
for b in bytes {
if p == end {
p = start
return false
}
var c = p[0]
if c >= asciiUpperA && c <= asciiUpperZ {
// Convert to lower case
// (Protobuf text keywords are case insensitive)
c += asciiLowerA - asciiUpperA
}
if c != b {
p = start
return false
}
p += 1
}
if p == end {
return true
}
let c = p[0]
if ((c >= asciiUpperA && c <= asciiUpperZ)
|| (c >= asciiLowerA && c <= asciiLowerZ)) {
p = start
return false
}
skipWhitespace()
return true
}
// If the next token is the identifier "nan", return true.
private mutating func skipOptionalNaN() -> Bool {
return skipOptionalKeyword(bytes:
[asciiLowerN, asciiLowerA, asciiLowerN])
}
// If the next token is a recognized spelling of "infinity",
// return Float.infinity or -Float.infinity
private mutating func skipOptionalInfinity() -> Float? {
if p == end {
return nil
}
let c = p[0]
let negated: Bool
if c == asciiMinus {
negated = true
p += 1
} else {
negated = false
}
let inf = [asciiLowerI, asciiLowerN, asciiLowerF]
let infinity = [asciiLowerI, asciiLowerN, asciiLowerF, asciiLowerI,
asciiLowerN, asciiLowerI, asciiLowerT, asciiLowerY]
if (skipOptionalKeyword(bytes: inf)
|| skipOptionalKeyword(bytes: infinity)) {
return negated ? -Float.infinity : Float.infinity
}
return nil
}
internal mutating func nextFloat() throws -> Float {
if let d = tryParseFloatString() {
return Float(d)
}
if skipOptionalNaN() {
return Float.nan
}
if let inf = skipOptionalInfinity() {
return inf
}
throw TextFormatDecodingError.malformedNumber
}
internal mutating func nextDouble() throws -> Double {
if let d = tryParseFloatString() {
return d
}
if skipOptionalNaN() {
return Double.nan
}
if let inf = skipOptionalInfinity() {
return Double(inf)
}
throw TextFormatDecodingError.malformedNumber
}
internal mutating func nextBool() throws -> Bool {
skipWhitespace()
if p == end {
throw TextFormatDecodingError.malformedText
}
let c = p[0]
p += 1
let result: Bool
switch c {
case asciiZero:
result = false
case asciiOne:
result = true
case asciiLowerF, asciiUpperF:
if p != end {
let alse = [asciiLowerA, asciiLowerL, asciiLowerS, asciiLowerE]
skipOptionalCharacters(bytes: alse)
}
result = false
case asciiLowerT, asciiUpperT:
if p != end {
let rue = [asciiLowerR, asciiLowerU, asciiLowerE]
skipOptionalCharacters(bytes: rue)
}
result = true
default:
throw TextFormatDecodingError.malformedText
}
if p == end {
return result
}
switch p[0] {
case asciiSpace,
asciiTab,
asciiNewLine,
asciiCarriageReturn,
asciiHash,
asciiComma,
asciiSemicolon,
asciiCloseSquareBracket,
asciiCloseCurlyBracket,
asciiCloseAngleBracket:
skipWhitespace()
return result
default:
throw TextFormatDecodingError.malformedText
}
}
internal mutating func nextOptionalEnumName() throws -> UnsafeBufferPointer<UInt8>? {
skipWhitespace()
if p == end {
throw TextFormatDecodingError.malformedText
}
switch p[0] {
case asciiLowerA...asciiLowerZ, asciiUpperA...asciiUpperZ:
return parseUTF8Identifier()
default:
return nil
}
}
/// Any URLs are syntactically (almost) identical to extension
/// keys, so we share the code for those.
internal mutating func nextOptionalAnyURL() throws -> String? {
return try nextOptionalExtensionKey()
}
/// Returns next extension key or nil if end-of-input or
/// if next token is not an extension key.
///
/// Throws an error if the next token starts with '[' but
/// cannot be parsed as an extension key.
///
/// Note: This accepts / characters to support Any URL parsing.
/// Technically, Any URLs can contain / characters and extension
/// key names cannot. But in practice, accepting / chracters for
/// extension keys works fine, since the result just gets rejected
/// when the key is looked up.
internal mutating func nextOptionalExtensionKey() throws -> String? {
skipWhitespace()
if p == end {
return nil
}
if p[0] == asciiOpenSquareBracket { // [
p += 1
if let s = parseExtensionKey() {
if p == end || p[0] != asciiCloseSquareBracket {
throw TextFormatDecodingError.malformedText
}
// Skip ]
p += 1
skipWhitespace()
return s
} else {
throw TextFormatDecodingError.malformedText
}
}
return nil
}
/// Returns text of next regular key or nil if end-of-input.
/// This considers an extension key [keyname] to be an
/// error, so call nextOptionalExtensionKey first if you
/// want to handle extension keys.
///
/// This is only used by map parsing; we should be able to
/// rework that to use nextFieldNumber instead.
internal mutating func nextKey() throws -> String? {
skipWhitespace()
if p == end {
return nil
}
let c = p[0]
switch c {
case asciiOpenSquareBracket: // [
throw TextFormatDecodingError.malformedText
case asciiLowerA...asciiLowerZ,
asciiUpperA...asciiUpperZ,
asciiOne...asciiNine: // a...z, A...Z, 1...9
return parseIdentifier()
default:
throw TextFormatDecodingError.malformedText
}
}
/// Parse a field name, look it up, and return the corresponding
/// field number.
///
/// returns nil at end-of-input
///
/// Throws if field name cannot be parsed or if field name is
/// unknown.
///
/// This function accounts for as much as 2/3 of the total run
/// time of the entire parse.
internal mutating func nextFieldNumber(names: _NameMap) throws -> Int? {
if p == end {
return nil
}
let c = p[0]
switch c {
case asciiLowerA...asciiLowerZ,
asciiUpperA...asciiUpperZ: // a...z, A...Z
let key = parseUTF8Identifier()
if let fieldNumber = names.number(forProtoName: key) {
return fieldNumber
} else {
throw TextFormatDecodingError.unknownField
}
case asciiOne...asciiNine: // 1-9 (field numbers are 123, not 0123)
var fieldNum = Int(c) - Int(asciiZero)
p += 1
while p != end {
let c = p[0]
if c >= asciiZero && c <= asciiNine {
fieldNum = fieldNum &* 10 &+ (Int(c) - Int(asciiZero))
} else {
break
}
p += 1
}
skipWhitespace()
if names.names(for: fieldNum) != nil {
return fieldNum
} else {
// It was a number that isn't a known field.
// The C++ version (TextFormat::Parser::ParserImpl::ConsumeField()),
// supports an option to file or skip the field's value (this is true
// of unknown names or numbers).
throw TextFormatDecodingError.unknownField
}
default:
break
}
throw TextFormatDecodingError.malformedText
}
private mutating func skipRequiredCharacter(_ c: UInt8) throws {
skipWhitespace()
if p != end && p[0] == c {
p += 1
skipWhitespace()
} else {
throw TextFormatDecodingError.malformedText
}
}
internal mutating func skipRequiredComma() throws {
try skipRequiredCharacter(asciiComma)
}
internal mutating func skipRequiredColon() throws {
try skipRequiredCharacter(asciiColon)
}
private mutating func skipOptionalCharacter(_ c: UInt8) -> Bool {
if p != end && p[0] == c {
p += 1
skipWhitespace()
return true
}
return false
}
internal mutating func skipOptionalColon() -> Bool {
return skipOptionalCharacter(asciiColon)
}
internal mutating func skipOptionalEndArray() -> Bool {
return skipOptionalCharacter(asciiCloseSquareBracket)
}
internal mutating func skipOptionalBeginArray() -> Bool {
return skipOptionalCharacter(asciiOpenSquareBracket)
}
internal mutating func skipOptionalObjectEnd(_ c: UInt8) -> Bool {
return skipOptionalCharacter(c)
}
internal mutating func skipOptionalSeparator() {
if p != end {
let c = p[0]
if c == asciiComma || c == asciiSemicolon { // comma or semicolon
p += 1
skipWhitespace()
}
}
}
/// Returns the character that should end this field.
/// E.g., if object starts with "{", returns "}"
internal mutating func skipObjectStart() throws -> UInt8 {
if p != end {
let c = p[0]
p += 1
skipWhitespace()
switch c {
case asciiOpenCurlyBracket: // {
return asciiCloseCurlyBracket // }
case asciiOpenAngleBracket: // <
return asciiCloseAngleBracket // >
default:
break
}
}
throw TextFormatDecodingError.malformedText
}
}
| apache-2.0 |
anirudh24seven/wikipedia-ios | Pods/SWStepSlider/Pod/Classes/SWStepSlider.swift | 1 | 9625 | //
// SWStepSlider.swift
// Pods
//
// Created by Sarun Wongpatcharapakorn on 2/4/16.
//
//
import UIKit
public class SWStepSliderAccessibilityElement: UIAccessibilityElement {
var minimumValue: Int = 0
var maximumValue: Int = 4
var value: Int = 2
weak var slider: SWStepSlider?
public init(accessibilityContainer container: AnyObject, slider: SWStepSlider) {
self.slider = slider
super.init(accessibilityContainer: container)
}
override public func accessibilityActivate() -> Bool {
return true
}
override public func accessibilityIncrement() {
let new = value + 1
self.slider?.setValueAndUpdateView(new)
}
override public func accessibilityDecrement() {
let new = value - 1
self.slider?.setValueAndUpdateView(new)
}
}
@IBDesignable
public class SWStepSlider: UIControl {
@IBInspectable public var minimumValue: Int = 0 {
didSet {
if self.minimumValue != oldValue {
if let e = self.thumbAccessabilityElement {
e.minimumValue = self.minimumValue
self.accessibilityElements = [e]
}
}
}
}
@IBInspectable public var maximumValue: Int = 4 {
didSet {
if self.maximumValue != oldValue {
if let e = self.thumbAccessabilityElement {
e.minimumValue = self.maximumValue
self.accessibilityElements = [e]
}
}
}
}
@IBInspectable public var value: Int = 2 {
didSet {
if self.value != oldValue {
if let e = self.thumbAccessabilityElement {
e.accessibilityValue = String(self.value)
e.value = self.value
self.accessibilityElements = [e]
}
if self.continuous {
self.sendActionsForControlEvents(.ValueChanged)
}
}
}
}
@IBInspectable public var continuous: Bool = true // if set, value change events are generated any time the value changes due to dragging. default = YES
let trackLayer = CALayer()
public var trackHeight: CGFloat = 2
public var trackColor = UIColor(red: 152.0/255.0, green: 152.0/255.0, blue: 152.0/255.0, alpha: 1)
public var tickHeight: CGFloat = 8
public var tickWidth: CGFloat = 2
public var tickColor = UIColor(red: 152.0/255.0, green: 152.0/255.0, blue: 152.0/255.0, alpha: 1)
let thumbLayer = CAShapeLayer()
var thumbFillColor = UIColor.whiteColor()
var thumbStrokeColor = UIColor(red: 222.0/255.0, green: 222.0/255.0, blue: 222.0/255.0, alpha: 1)
var thumbDimension: CGFloat = 28
private var thumbAccessabilityElement: SWStepSliderAccessibilityElement?
var stepWidth: CGFloat {
return self.trackWidth / CGFloat(self.maximumValue)
}
var trackWidth: CGFloat {
return self.bounds.size.width - self.thumbDimension
}
var trackOffset: CGFloat {
return (self.bounds.size.width - self.trackWidth) / 2
}
var numberOfSteps: Int {
return self.maximumValue - self.minimumValue + 1
}
required public init?(coder: NSCoder) {
super.init(coder: coder)
self.commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
private func commonInit() {
self.trackLayer.backgroundColor = self.trackColor.CGColor
self.layer.addSublayer(trackLayer)
self.thumbLayer.backgroundColor = UIColor.clearColor().CGColor
self.thumbLayer.fillColor = self.thumbFillColor.CGColor
self.thumbLayer.strokeColor = self.thumbStrokeColor.CGColor
self.thumbLayer.lineWidth = 0.5
self.thumbLayer.frame = CGRect(x: 0, y: 0, width: self.thumbDimension, height: self.thumbDimension)
self.thumbLayer.path = UIBezierPath(ovalInRect: self.thumbLayer.bounds).CGPath
// Shadow
self.thumbLayer.shadowOffset = CGSize(width: 0, height: 2)
self.thumbLayer.shadowColor = UIColor.blackColor().CGColor
self.thumbLayer.shadowOpacity = 0.3
self.thumbLayer.shadowRadius = 2
self.thumbLayer.contentsScale = UIScreen.mainScreen().scale
self.layer.addSublayer(self.thumbLayer)
self.thumbAccessabilityElement = SWStepSliderAccessibilityElement(accessibilityContainer: self, slider: self)
if let e = self.thumbAccessabilityElement {
e.accessibilityLabel = "Text Slider"
e.accessibilityHint = "Increment of decrement to adjust the text size"
e.accessibilityTraits = UIAccessibilityTraitAdjustable
self.accessibilityElements = [e]
}
}
public override func layoutSubviews() {
super.layoutSubviews()
var rect = self.bounds
rect.origin.x = self.trackOffset
rect.origin.y = (rect.size.height - self.trackHeight) / 2
rect.size.height = self.trackHeight
rect.size.width = self.trackWidth
self.trackLayer.frame = rect
let center = CGPoint(x: self.trackOffset + CGFloat(self.value) * self.stepWidth, y: self.bounds.midY)
let thumbRect = CGRect(x: center.x - self.thumbDimension / 2, y: center.y - self.thumbDimension / 2, width: self.thumbDimension, height: self.thumbDimension)
self.thumbLayer.frame = thumbRect
if let e = self.thumbAccessabilityElement {
e.accessibilityFrame = self.convertRect(thumbRect, toView: nil)
self.accessibilityElements = [e]
}
}
public override func drawRect(rect: CGRect) {
super.drawRect(rect)
let ctx = UIGraphicsGetCurrentContext()
CGContextSaveGState(ctx!)
// Draw ticks
CGContextSetFillColorWithColor(ctx!, self.tickColor.CGColor)
for index in 0..<self.numberOfSteps {
let x = self.trackOffset + CGFloat(index) * self.stepWidth - 0.5 * self.tickWidth
let y = self.bounds.midY - 0.5 * self.tickHeight
// Clip the tick
let tickPath = UIBezierPath(rect: CGRect(x: x , y: y, width: self.tickWidth, height: self.tickHeight))
// Fill the tick
CGContextAddPath(ctx!, tickPath.CGPath)
CGContextFillPath(ctx!)
}
CGContextRestoreGState(ctx!)
}
public override func intrinsicContentSize() -> CGSize {
return CGSize(width: self.thumbDimension * CGFloat(self.numberOfSteps), height: self.thumbDimension)
}
public func setValueAndUpdateView(value: Int) {
self.value = self.clipValue(value)
CATransaction.begin()
CATransaction.setDisableActions(true)
// Update UI without animation
self.setNeedsLayout()
CATransaction.commit()
}
// MARK: - Touch
var previousLocation: CGPoint!
var dragging = false
var originalValue: Int!
public override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
let location = touch.locationInView(self)
self.originalValue = self.value
print("touch \(location)")
if self.thumbLayer.frame.contains(location) {
self.dragging = true
} else {
self.dragging = false
}
self.previousLocation = location
return self.dragging
}
public override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
let location = touch.locationInView(self)
let deltaLocation = location.x - self.previousLocation.x
let deltaValue = self.deltaValue(deltaLocation)
if deltaLocation < 0 {
// minus
self.value = self.clipValue(self.originalValue - deltaValue)
} else {
self.value = self.clipValue(self.originalValue + deltaValue)
}
CATransaction.begin()
CATransaction.setDisableActions(true)
// Update UI without animation
self.setNeedsLayout()
CATransaction.commit()
return true
}
public override func endTrackingWithTouch(touch: UITouch?, withEvent event: UIEvent?) {
self.previousLocation = nil
self.originalValue = nil
self.dragging = false
if self.continuous == false {
self.sendActionsForControlEvents(.ValueChanged)
}
}
// MARK: - Helper
func deltaValue(deltaLocation: CGFloat) -> Int {
return Int(round(fabs(deltaLocation) / self.stepWidth))
}
func clipValue(value: Int) -> Int {
return min(max(value, self.minimumValue), self.maximumValue)
}
// MARK: - Accessibility
override public var isAccessibilityElement: Bool {
get {
return false //return NO to be a container
}
set {
super.isAccessibilityElement = newValue
}
}
override public func accessibilityElementCount() -> Int {
return 1
}
override public func accessibilityElementAtIndex(index: Int) -> AnyObject? {
return self.thumbAccessabilityElement
}
override public func indexOfAccessibilityElement(element: AnyObject) -> Int {
return 0
}
}
| mit |
rodrigok/wwdc-2016-shcolarship | Rodrigo Nascimento/PageViewController.swift | 1 | 3084 | //
// PageViewController.swift
// Rodrigo Nascimento
//
// Created by Rodrigo Nascimento on 25/04/16.
// Copyright (c) 2016 Rodrigo Nascimento. All rights reserved.
//
import UIKit
class PageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
let pages = 4
var pageControl: UIPageControl!
override func viewDidLoad() {
super.viewDidLoad()
pageControl = UIPageControl(frame: CGRectMake(0.0, 0.0, self.view.frame.width, 30.0))
pageControl.pageIndicatorTintColor = UIColor(white: 0.9, alpha: 1)
pageControl.currentPageIndicatorTintColor = UIColor(red: 0.6745, green: 0.5765, blue: 0.3333, alpha: 0.5)
pageControl.numberOfPages = pages
self.view.addSubview(pageControl)
self.view.bringSubviewToFront(pageControl)
self.delegate = self
self.dataSource = self
self.view.backgroundColor = UIColor(rgba: "#292b36")
let pageContentViewController = self.viewControllerAtIndex(0)
self.setViewControllers([pageContentViewController!], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)
}
func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
self.pageControl.currentPage = (pageViewController.viewControllers![0] as! PageContentViewController).pageIndex!
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
var index = (viewController as! PageContentViewController).pageIndex!
index += 1
if(index >= pages){
return nil
}
return self.viewControllerAtIndex(index)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
var index = (viewController as! PageContentViewController).pageIndex!
if(index <= 0){
return nil
}
index -= 1
return self.viewControllerAtIndex(index)
}
func viewControllerAtIndex(index : Int) -> UIViewController? {
if((pages == 0) || (index >= pages)) {
return nil
}
let identifier = NSString(format: "PageContentViewController%d", index) as String
let pageContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier(identifier) as! PageContentViewController
pageContentViewController.pageIndex = index
pageContentViewController.pageViewController = self
return pageContentViewController
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
chris-wood/reveiller | reveiller/Pods/SwiftCharts/SwiftCharts/Layers/ChartPointsBubbleLayer.swift | 6 | 1803 | //
// ChartPointsBubbleLayer.swift
// Examples
//
// Created by ischuetz on 16/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
public class ChartPointsBubbleLayer<T: ChartPointBubble>: ChartPointsLayer<T> {
private let diameterFactor: Double
public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], displayDelay: Float = 0, maxBubbleDiameter: Double = 30, minBubbleDiameter: Double = 2) {
let (minDiameterScalar, maxDiameterScalar): (Double, Double) = chartPoints.reduce((min: 0, max: 0)) {tuple, chartPoint in
(min: min(tuple.min, chartPoint.diameterScalar), max: max(tuple.max, chartPoint.diameterScalar))
}
self.diameterFactor = (maxBubbleDiameter - minBubbleDiameter) / (maxDiameterScalar - minDiameterScalar)
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, displayDelay: displayDelay)
}
override public func chartViewDrawing(context context: CGContextRef, chart: Chart) {
for chartPointModel in self.chartPointsModels {
CGContextSetLineWidth(context, 1.0)
CGContextSetStrokeColorWithColor(context, chartPointModel.chartPoint.borderColor.CGColor)
CGContextSetFillColorWithColor(context, chartPointModel.chartPoint.bgColor.CGColor)
let diameter = CGFloat(chartPointModel.chartPoint.diameterScalar * diameterFactor)
let circleRect = (CGRectMake(chartPointModel.screenLoc.x - diameter / 2, chartPointModel.screenLoc.y - diameter / 2, diameter, diameter))
CGContextFillEllipseInRect(context, circleRect)
CGContextStrokeEllipseInRect(context, circleRect)
}
}
}
| mit |
Estimote/iOS-SDK | Examples/swift/LoyaltyStore/LoyaltyStore/Views/Customer/CustomerCell.swift | 1 | 1004 | //
// Please report any problems with this app template to contact@estimote.com
//
import UIKit
/// Customer cell used in StoreViewController to display customers
class CustomerCell: UITableViewCell {
@IBOutlet weak var cardView : CardView!
@IBOutlet weak var avatarImageView : AvatarImageView!
@IBOutlet weak var nameLabel : UILabel!
@IBOutlet weak var pointsLabel : UILabel!
override func awakeFromNib() {
}
override func setSelected(_ selected: Bool, animated: Bool) {
switch selected {
case true :
cardView.backgroundColor = UIColor.white
cardView.shadowVisible()
nameLabel.textColor = UIColor.black
pointsLabel.textColor = UIColor.black
case false :
cardView.backgroundColor = UIColor.init(red: 148/256, green: 106/256, blue: 207/256, alpha: 1)
cardView.shadowHidden()
nameLabel.textColor = UIColor.white
pointsLabel.textColor = UIColor.white
}
}
}
| mit |
ahoppen/swift | test/IRGen/rdar15304329.swift | 36 | 449 | // RUN: %empty-directory(%t)
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) %s -emit-ir | %FileCheck %s
// REQUIRES: objc_interop
// CHECK-NOT: @_TWvi{{.*}}
// CHECK: $s12rdar153043293BarC3fooAA3FooVySiGvpWvd
// CHECK-NOT: @_TWvi{{.*}}
import Foundation
struct Foo<T> { var x: T }
class Bar : NSObject {
var foo: Foo<Int>
init(foo: Foo<Int>) {
self.foo = foo
super.init()
}
}
| apache-2.0 |
MakeAWishFoundation/SwiftyMocky | Sources/Shared/Count.swift | 1 | 3546 | import Foundation
/// Count enum. Use it for all Verify features, when checking how many times something happened.
///
/// There are three ways of using it:
/// 1. Explicit literal - you can pass 0, 1, 2 ... to verify exact number
/// 2. Using predefined .custom, to specify custom matching rule.
/// 3. Using one of predefined rules, for example:
/// - .atLeastOnce
/// - .exactly(1)
/// - .from(2, to: 4)
/// - .less(than: 2)
/// - .lessOrEqual(to: 1)
/// - .more(than: 2)
/// - .moreOrEqual(to: 3)
/// - .never
public enum Count: ExpressibleByIntegerLiteral {
/// Count matching closure
public typealias CustomMatchingClosure = ( _ value: Int ) -> Bool
/// [Internal] Count is represented by integer literals, with type Int
public typealias IntegerLiteralType = Int
/// Called at least once
case atLeastOnce
/// Called exactly once
case once
/// Custom count resolving closure
case custom(CustomMatchingClosure)
/// Called exactly n times
case exactly(Int)
/// Called in a...b range
case from(Int, to: Int)
/// Called less than n times
case less(than: Int)
/// Called less than ot equal to n times
case lessOrEqual(to: Int)
/// Called more than n times
case more(than: Int)
/// Called more than ot equal to n times
case moreOrEqual(to: Int)
/// Never called
case never
/// Creates new count instance, matching specific count
///
/// - Parameter value: Exact count value
public init(integerLiteral value: IntegerLiteralType) {
self = .exactly(value)
}
}
// MARK: - CustomStringConvertible
extension Count: CustomStringConvertible {
/// Human readable description
public var description: String {
switch self {
case .atLeastOnce:
return "at least 1"
case .once:
return "once"
case .custom:
return "custom"
case .exactly(let value):
return "exactly \(value)"
case .from(let lowerBound, let upperBound):
return "from \(lowerBound) to \(upperBound)"
case .less(let value):
return "less than \(value)"
case .lessOrEqual(let value):
return "less than or equal to \(value)"
case .more(let value):
return "more than \(value)"
case .moreOrEqual(let value):
return "more than or equal to \(value)"
case .never:
return "none"
}
}
}
// MARK: - Countable
extension Count: Countable {
/// Returns whether given count matches countable case.
///
/// - Parameter count: Given count
/// - Returns: true, if it is within boundaries, false otherwise
public func matches(_ count: Int) -> Bool {
switch self {
case .atLeastOnce:
return count >= 1
case .once:
return count == 1
case .custom(let matchingRule):
return matchingRule(count)
case .exactly(let value):
return count == value
case .from(let lowerBound, to: let upperBound):
return count >= lowerBound && count <= upperBound
case .less(let value):
return count < value
case .lessOrEqual(let value):
return count <= value
case .more(let value):
return count > value
case .moreOrEqual(let value):
return count >= value
case .never:
return count == 0
}
}
}
| mit |
natecook1000/swift | test/IDE/complete_exception.swift | 3 | 11278 | // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=CATCH1 | %FileCheck %s -check-prefix=CATCH1
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=THROW1 > %t.throw1
// RUN: %FileCheck %s -check-prefix=THROW1 < %t.throw1
// RUN: %FileCheck %s -check-prefix=THROW1-LOCAL < %t.throw1
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=CATCH2 | %FileCheck %s -check-prefix=CATCH2
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=THROW2 | %FileCheck %s -check-prefix=THROW2
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=CATCH3 | %FileCheck %s -check-prefix=CATCH3
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_CATCH1 | %FileCheck %s -check-prefix=CATCH1
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_THROW1 | %FileCheck %s -check-prefix=THROW1
// FIXME: <rdar://problem/21001526> No dot code completion results in switch case or catch stmt at top-level
// RUNdisabled: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_CATCH2 | %FileCheck %s -check-prefix=CATCH2
// RUNdisabled: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_THROW2 | %FileCheck %s -check-prefix=THROW2
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=INSIDE_CATCH1 > %t.inside_catch1
// RUN: %FileCheck %s -check-prefix=STMT < %t.inside_catch1
// RUN: %FileCheck %s -check-prefix=IMPLICIT_ERROR < %t.inside_catch1
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=INSIDE_CATCH2 > %t.inside_catch2
// RUN: %FileCheck %s -check-prefix=STMT < %t.inside_catch2
// RUN: %FileCheck %s -check-prefix=EXPLICIT_ERROR_E < %t.inside_catch2
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=INSIDE_CATCH3 > %t.inside_catch3
// RUN: %FileCheck %s -check-prefix=STMT < %t.inside_catch3
// RUN: %FileCheck %s -check-prefix=EXPLICIT_NSERROR_E < %t.inside_catch3
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=INSIDE_CATCH4 > %t.inside_catch4
// RUN: %FileCheck %s -check-prefix=STMT < %t.inside_catch4
// RUN: %FileCheck %s -check-prefix=EXPLICIT_ERROR_PAYLOAD_I < %t.inside_catch4
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=INSIDE_CATCH5 > %t.inside_catch5
// RUN: %FileCheck %s -check-prefix=STMT < %t.inside_catch5
// RUN: %FileCheck %s -check-prefix=EXPLICIT_ERROR_E < %t.inside_catch5
// RUN: %FileCheck %s -check-prefix=NO_ERROR_AND_A < %t.inside_catch5
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=INSIDE_CATCH6 > %t.inside_catch6
// RUN: %FileCheck %s -check-prefix=STMT < %t.inside_catch6
// RUN: %FileCheck %s -check-prefix=NO_E < %t.inside_catch6
// RUN: %FileCheck %s -check-prefix=NO_ERROR_AND_A < %t.inside_catch6
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=INSIDE_CATCH_ERR_DOT1 | %FileCheck %s -check-prefix=ERROR_DOT
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=INSIDE_CATCH_ERR_DOT2 | %FileCheck %s -check-prefix=ERROR_DOT
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=INSIDE_CATCH_ERR_DOT3 | %FileCheck %s -check-prefix=NSERROR_DOT
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=INSIDE_CATCH_ERR_DOT4 | %FileCheck %s -check-prefix=INT_DOT
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_INSIDE_CATCH1 > %t.top_level_inside_catch1
// RUN: %FileCheck %s -check-prefix=STMT < %t.top_level_inside_catch1
// RUN: %FileCheck %s -check-prefix=IMPLICIT_ERROR < %t.top_level_inside_catch1
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_INSIDE_CATCH_ERR_DOT1 | %FileCheck %s -check-prefix=ERROR_DOT
// REQUIRES: objc_interop
import Foundation // importer SDK
protocol ErrorPro1 : Error {}
class Error1 : Error {}
class Error2 : Error {}
class Error3 {}
extension Error3 : Error{}
enum Error4 : Error {
case E1
case E2(Int32)
}
class NoneError1 {}
func getError1() -> Error1 { return Error1() }
func getNSError() -> NSError { return NSError(domain: "", code: 1, userInfo: [:]) }
func test001() {
do {} catch #^CATCH1^#
// CATCH1: Begin completions
// CATCH1-DAG: Decl[Enum]/CurrModule: Error4[#Error4#]; name=Error4{{$}}
// CATCH1-DAG: Decl[Class]/CurrModule: Error3[#Error3#]; name=Error3{{$}}
// CATCH1-DAG: Decl[Class]/CurrModule: Error2[#Error2#]; name=Error2{{$}}
// CATCH1-DAG: Decl[Class]/CurrModule: Error1[#Error1#]; name=Error1{{$}}
// CATCH1-DAG: Keyword[let]/None: let{{; name=.+$}}
// CATCH1-DAG: Decl[Class]/CurrModule: NoneError1[#NoneError1#]; name=NoneError1{{$}}
// CATCH1-DAG: Decl[Class]/OtherModule[Foundation]: NSError[#NSError#]{{; name=.+$}}
}
func test002() {
let text = "NonError"
let e1 = Error1()
let e2 = Error2()
throw #^THROW1^#
// THROW1: Begin completions
// THROW1-DAG: Decl[Enum]/CurrModule: Error4[#Error4#]; name=Error4{{$}}
// THROW1-DAG: Decl[Class]/CurrModule: Error3[#Error3#]; name=Error3{{$}}
// THROW1-DAG: Decl[Class]/CurrModule: Error2[#Error2#]; name=Error2{{$}}
// THROW1-DAG: Decl[Class]/CurrModule: Error1[#Error1#]; name=Error1{{$}}
// THROW1-DAG: Decl[Protocol]/CurrModule: ErrorPro1[#ErrorPro1#]; name=ErrorPro1{{$}}
// THROW1-DAG: Decl[FreeFunction]/CurrModule: getError1()[#Error1#]{{; name=.+$}}
// THROW1-DAG: Decl[FreeFunction]/CurrModule: getNSError()[#NSError#]{{; name=.+$}}
// If we could prove that there is no way to get to an Error value by
// starting from these, we could remove them. But that may be infeasible in
// the presence of overloaded operators.
// THROW1-DAG: Decl[Class]/CurrModule: NoneError1[#NoneError1#]; name=NoneError1{{$}}
// THROW1-LOCAL: Decl[LocalVar]/Local: text[#String#]; name=text{{$}}
// THROW1-LOCAL: Decl[LocalVar]/Local: e1[#Error1#]; name=e1{{$}}
// THROW1-LOCAL: Decl[LocalVar]/Local: e2[#Error2#]; name=e2{{$}}
}
func test003() {
do {} catch Error4.#^CATCH2^#
// CATCH2: Begin completions
// CATCH2: Decl[EnumElement]/CurrNominal: E1[#Error4#]{{; name=.+$}}
// CATCH2: Decl[EnumElement]/CurrNominal: E2({#Int32#})[#(Int32) -> Error4#]{{; name=.+$}}
// CATCH2: End completions
}
func test004() {
throw Error4.#^THROW2^#
// THROW2: Begin completions
// THROW2: Decl[EnumElement]/CurrNominal: E1[#Error4#]{{; name=.+$}}
// THROW2: Decl[EnumElement]/CurrNominal: E2({#Int32#})[#(Int32) -> Error4#]{{; name=.+$}}
// THROW2: End completions
}
func test005() {
do {} catch Error4.E2#^CATCH3^#
// CATCH3: Begin completions
// CATCH3: Pattern/CurrModule: ({#Int32#})[#Error4#]{{; name=.+$}}
// CATCH3: End completions
}
//===--- Top-level throw/catch
do {} catch #^TOP_LEVEL_CATCH1^# {}
throw #^TOP_LEVEL_THROW1^#
do {} catch Error4.#^TOP_LEVEL_CATCH2^# {}
throw Error4.#^TOP_LEVEL_THROW2^#
//===--- Inside catch body
// Statement-level code completions. This isn't exhaustive.
// STMT: Begin completions
// STMT-DAG: Keyword[if]/None: if; name=if
// STMT-DAG: Decl[Class]/CurrModule: Error1[#Error1#]; name=Error1
// STMT-DAG: Decl[Class]/CurrModule: Error2[#Error2#]; name=Error2
// STMT-DAG: Decl[FreeFunction]/CurrModule: getError1()[#Error1#]; name=getError1()
// STMT-DAG: Decl[FreeFunction]/CurrModule: getNSError()[#NSError#]; name=getNSError()
// STMT: End completions
func test006() {
do {
} catch {
#^INSIDE_CATCH1^#
}
// IMPLICIT_ERROR: Decl[LocalVar]/Local: error[#Error#]; name=error
}
func test007() {
do {
} catch let e {
#^INSIDE_CATCH2^#
}
// EXPLICIT_ERROR_E: Decl[LocalVar]/Local: e[#Error#]; name=e
}
func test008() {
do {
} catch let e as NSError {
#^INSIDE_CATCH3^#
}
// EXPLICIT_NSERROR_E: Decl[LocalVar]/Local: e[#NSError#]; name=e
}
func test009() {
do {
} catch Error4.E2(let i) {
#^INSIDE_CATCH4^#
}
// FIXME: we're getting parentheses around the type when it's unnamed...
// EXPLICIT_ERROR_PAYLOAD_I: Decl[LocalVar]/Local: i[#(Int32)#]; name=i
}
func test010() {
do {
} catch let awesomeError {
} catch let e {
#^INSIDE_CATCH5^#
} catch {}
// NO_ERROR_AND_A-NOT: awesomeError
// NO_ERROR_AND_A-NOT: Decl[LocalVar]/Local: error
}
func test011() {
do {
} catch let awesomeError {
} catch let excellentError {
} catch {}
#^INSIDE_CATCH6^#
// NO_E-NOT: excellentError
}
func test012() {
do {
} catch {
error.#^INSIDE_CATCH_ERR_DOT1^#
}
}
// ERROR_DOT: Begin completions
// ERROR_DOT: Keyword[self]/CurrNominal: self[#Error#]; name=self
func test013() {
do {
} catch let e {
e.#^INSIDE_CATCH_ERR_DOT2^#
}
}
func test014() {
do {
} catch let e as NSError {
e.#^INSIDE_CATCH_ERR_DOT3^#
}
// NSERROR_DOT: Begin completions
// NSERROR_DOT-DAG: Decl[InstanceVar]/CurrNominal: domain[#String#]; name=domain
// NSERROR_DOT-DAG: Decl[InstanceVar]/CurrNominal: code[#Int#]; name=code
// NSERROR_DOT-DAG: Decl[InstanceVar]/Super: hashValue[#Int#]; name=hashValue
// NSERROR_DOT-DAG: Decl[InstanceMethod]/Super: myClass()[#AnyClass!#]; name=myClass()
// NSERROR_DOT-DAG: Decl[InstanceMethod]/Super: isEqual({#(other): NSObject!#})[#Bool#]; name=isEqual(other: NSObject!)
// NSERROR_DOT-DAG: Decl[InstanceVar]/Super: hash[#Int#]; name=hash
// NSERROR_DOT-DAG: Decl[InstanceVar]/Super: description[#String#]; name=description
// NSERROR_DOT: End completions
}
func test015() {
do {
} catch Error4.E2(let i) where i == 2 {
i.#^INSIDE_CATCH_ERR_DOT4^#
}
}
// Check that we can complete on the bound value; Not exhaustive..
// INT_DOT: Begin completions
// INT_DOT-DAG: Decl[InstanceVar]/Super: bigEndian[#(Int32)#]; name=bigEndian
// INT_DOT-DAG: Decl[InstanceVar]/Super: littleEndian[#(Int32)#]; name=littleEndian
// INT_DOT: End completions
//===--- Inside catch body top-level
do {
} catch {
#^TOP_LEVEL_INSIDE_CATCH1^#
}
do {
} catch {
error.#^TOP_LEVEL_INSIDE_CATCH_ERR_DOT1^#
}
| apache-2.0 |
Johnykutty/SwiftLint | Source/SwiftLintFramework/Rules/NotificationCenterDetachmentRuleExamples.swift | 2 | 1433 | //
// NotificationCenterDetachmentRuleExamples.swift
// SwiftLint
//
// Created by Marcelo Fabri on 01/15/17.
// Copyright © 2017 Realm. All rights reserved.
//
internal struct NotificationCenterDetachmentRuleExamples {
static let swift3NonTriggeringExamples = [
"class Foo { \n" +
" deinit {\n" +
" NotificationCenter.default.removeObserver(self)\n" +
" }\n" +
"}\n",
"class Foo { \n" +
" func bar() {\n" +
" NotificationCenter.default.removeObserver(otherObject)\n" +
" }\n" +
"}\n"
]
static let swift2NonTriggeringExamples = [
"class Foo { \n" +
" deinit {\n" +
" NSNotificationCenter.defaultCenter.removeObserver(self)\n" +
" }\n" +
"}\n",
"class Foo { \n" +
" func bar() {\n" +
" NSNotificationCenter.defaultCenter.removeObserver(otherObject)\n" +
" }\n" +
"}\n"
]
static let swift3TriggeringExamples = [
"class Foo { \n" +
" func bar() {\n" +
" ↓NotificationCenter.default.removeObserver(self)\n" +
" }\n" +
"}\n"
]
static let swift2TriggeringExamples = [
"class Foo { \n" +
" func bar() {\n" +
" ↓NSNotificationCenter.defaultCenter.removeObserver(self)\n" +
" }\n" +
"}\n"
]
}
| mit |
arvedviehweger/swift | benchmark/single-source/StringTests.swift | 5 | 3941 | //===--- StringTests.swift ------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import TestsUtils
// FIXME(string)
public func run_StringHasPrefix(_ N: Int) {
#if _runtime(_ObjC)
let prefix = "prefix"
let testString = "prefixedString"
for _ in 0 ..< N {
for _ in 0 ..< 100_000 {
if !testString.hasPrefix(prefix) {
CheckResults(false, "prefix check failed")
}
}
}
#endif
}
// FIXME(string)
public func run_StringHasSuffix(_ N: Int) {
#if _runtime(_ObjC)
let suffix = "Suffixed"
let testString = "StringSuffixed"
for _ in 0 ..< N {
for _ in 0 ..< 100_000 {
if !testString.hasSuffix(suffix) {
CheckResults(false, "suffix check failed")
}
}
}
#endif
}
// FIXME(string)
public func run_StringHasPrefixUnicode(_ N: Int) {
#if _runtime(_ObjC)
let prefix = "❄️prefix"
let testString = "❄️prefixedString"
for _ in 0 ..< N {
for _ in 0 ..< 100_000 {
if !testString.hasPrefix(prefix) {
CheckResults(false, "prefix check failed")
}
}
}
#endif
}
// FIXME(string)
public func run_StringHasSuffixUnicode(_ N: Int) {
#if _runtime(_ObjC)
let suffix = "❄️Suffixed"
let testString = "String❄️Suffixed"
for _ in 0 ..< N {
for _ in 0 ..< 100_000 {
if !testString.hasSuffix(suffix) {
CheckResults(false, "suffix check failed")
}
}
}
#endif
}
@inline(never)
internal func compareEqual(_ str1: String, _ str2: String) -> Bool {
return str1 == str2
}
public func run_StringEqualPointerComparison(_ N: Int) {
let str1 = "The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. "
let str2 = str1
for _ in 0 ..< N {
for _ in 0 ..< 100_000 {
if !compareEqual(str1, str2) {
CheckResults(false, "Strings should be equal")
}
}
}
}
| apache-2.0 |
esttorhe/RxSwift | RxCocoa/RxCocoa/Common/DelegateProxy.swift | 1 | 3082 | //
// DelegateProxy.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/14/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxSwift
var delegateAssociatedTag: UInt8 = 0
var dataSourceAssociatedTag: UInt8 = 0
// This should be only used from `MainScheduler`
//
// Also, please take a look at `DelegateProxyType` protocol implementation
public class DelegateProxy : _RXDelegateProxy {
private var subjectsForSelector = [Selector: PublishSubject<[AnyObject]>]()
unowned let parentObject: AnyObject
public required init(parentObject: AnyObject) {
self.parentObject = parentObject
MainScheduler.ensureExecutingOnScheduler()
#if TRACE_RESOURCES
OSAtomicIncrement32(&resourceCount)
#endif
super.init()
}
public func observe(selector: Selector) -> Observable<[AnyObject]> {
if hasWiredImplementationForSelector(selector) {
print("Delegate proxy is already implementing `\(selector)`, a more performant way of registering might exist.")
}
if !self.respondsToSelector(selector) {
rxFatalError("This class doesn't respond to selector \(selector)")
}
let subject = subjectsForSelector[selector]
if let subject = subject {
return subject
}
else {
let subject = PublishSubject<[AnyObject]>()
subjectsForSelector[selector] = subject
return subject
}
}
// proxy
public override func interceptedSelector(selector: Selector, withArguments arguments: [AnyObject]!) {
trySendNext(subjectsForSelector[selector], arguments)
}
class func _pointer(p: UnsafePointer<Void>) -> UnsafePointer<Void> {
return p
}
public class func delegateAssociatedObjectTag() -> UnsafePointer<Void> {
return _pointer(&delegateAssociatedTag)
}
public class func createProxyForObject(object: AnyObject) -> AnyObject {
return self.init(parentObject: object)
}
public class func assignedProxyFor(object: AnyObject) -> AnyObject? {
let maybeDelegate: AnyObject? = objc_getAssociatedObject(object, self.delegateAssociatedObjectTag())
return castOptionalOrFatalError(maybeDelegate)
}
public class func assignProxy(proxy: AnyObject, toObject object: AnyObject) {
precondition(proxy.isKindOfClass(self.classForCoder()))
objc_setAssociatedObject(object, self.delegateAssociatedObjectTag(), proxy, .OBJC_ASSOCIATION_RETAIN)
}
public func setForwardToDelegate(delegate: AnyObject?, retainDelegate: Bool) {
self._setForwardToDelegate(delegate, retainDelegate: retainDelegate)
}
public func forwardToDelegate() -> AnyObject? {
return self._forwardToDelegate
}
deinit {
for v in subjectsForSelector.values {
sendCompleted(v)
}
#if TRACE_RESOURCES
OSAtomicDecrement32(&resourceCount)
#endif
}
} | mit |
practicalswift/swift | validation-test/compiler_crashers_2_fixed/0095-rdar30154791.swift | 55 | 457 | // RUN: not %target-swift-frontend %s -typecheck
struct X<T> {}
struct Y<T> {}
protocol P {
associatedtype T = X<U>
associatedtype U
func foo() -> T
}
protocol Q: P {
func bar() -> T
func bas() -> U
}
extension P {
func foo() -> X<U> { fatalError() }
}
extension Q {
func foo() -> Y<U> { fatalError() }
func bar() -> Y<U> { fatalError() }
}
struct S {}
extension S {
func bas() -> Int {}
}
extension S: Q {}
let x: Y = S().foo()
| apache-2.0 |
ello/ello-ios | Sources/Controllers/Following/FollowingViewController.swift | 1 | 5751 | ////
/// FollowingViewController.swift
//
import PromiseKit
class FollowingViewController: StreamableViewController {
override func trackerName() -> String? { return "Stream" }
override func trackerProps() -> [String: Any]? {
return ["kind": "Following"]
}
override func trackerStreamInfo() -> (String, String?)? {
return ("following", nil)
}
private var reloadFollowingContentObserver: NotificationObserver?
private var appBackgroundObserver: NotificationObserver?
private var appForegroundObserver: NotificationObserver?
private var newFollowingContentObserver: NotificationObserver?
private var _mockScreen: FollowingScreenProtocol?
var screen: FollowingScreenProtocol {
set(screen) { _mockScreen = screen }
get { return fetchScreen(_mockScreen) }
}
var generator: FollowingGenerator!
required init() {
super.init(nibName: nil, bundle: nil)
self.title = ""
generator = FollowingGenerator(destination: self)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
removeNotificationObservers()
}
override func loadView() {
let screen = FollowingScreen()
screen.delegate = self
view = screen
viewContainer = screen.streamContainer
}
override func viewDidLoad() {
super.viewDidLoad()
streamViewController.initialLoadClosure = { [weak self] in self?.loadFollowing() }
streamViewController.streamKind = .following
setupNavigationItems(streamKind: .following)
streamViewController.showLoadingSpinner()
streamViewController.loadInitialPage()
addNotificationObservers()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
addTemporaryNotificationObservers()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
removeTemporaryNotificationObservers()
}
private func updateInsets() {
updateInsets(maxY: max(screen.navigationBar.frame.maxY - 14, 0))
}
override func showNavBars(animated: Bool) {
super.showNavBars(animated: animated)
positionNavBar(screen.navigationBar, visible: true, animated: animated)
updateInsets()
}
override func hideNavBars(animated: Bool) {
super.hideNavBars(animated: animated)
positionNavBar(screen.navigationBar, visible: false, animated: animated)
updateInsets()
}
override func streamWillPullToRefresh() {
super.streamWillPullToRefresh()
screen.newPostsButtonVisible = false
}
override func streamViewInfiniteScroll() -> Promise<[Model]>? {
return generator.loadNextPage()
}
}
extension FollowingViewController {
private func setupNavigationItems(streamKind: StreamKind) {
screen.navigationBar.leftItems = [.burger]
screen.navigationBar.rightItems = [.gridList(isGrid: streamKind.isGridView)]
}
private func addTemporaryNotificationObservers() {
reloadFollowingContentObserver = NotificationObserver(
notification: NewContentNotifications.reloadFollowingContent
) { [weak self] in
guard let `self` = self else { return }
self.streamViewController.showLoadingSpinner()
self.screen.newPostsButtonVisible = false
self.streamViewController.loadInitialPage(reload: true)
}
}
private func removeTemporaryNotificationObservers() {
reloadFollowingContentObserver?.removeObserver()
}
private func addNotificationObservers() {
newFollowingContentObserver = NotificationObserver(
notification: NewContentNotifications.newFollowingContent
) { [weak self] in
guard let `self` = self else { return }
self.screen.newPostsButtonVisible = true
}
}
private func removeNotificationObservers() {
newFollowingContentObserver?.removeObserver()
appBackgroundObserver?.removeObserver()
}
}
extension FollowingViewController: StreamDestination {
var isPagingEnabled: Bool {
get { return streamViewController.isPagingEnabled }
set { streamViewController.isPagingEnabled = newValue }
}
func loadFollowing() {
streamViewController.isPagingEnabled = false
generator.load()
}
func replacePlaceholder(
type: StreamCellType.PlaceholderType,
items: [StreamCellItem],
completion: @escaping Block
) {
streamViewController.replacePlaceholder(type: type, items: items, completion: completion)
if type == .streamItems {
streamViewController.doneLoading()
}
}
func setPlaceholders(items: [StreamCellItem]) {
streamViewController.clearForInitialLoad(newItems: items)
}
func setPrimary(jsonable: Model) {
}
func setPagingConfig(responseConfig: ResponseConfig) {
streamViewController.responseConfig = responseConfig
}
func primaryModelNotFound() {
self.showGenericLoadFailure()
self.streamViewController.doneLoading()
}
}
extension FollowingViewController: FollowingScreenDelegate {
func scrollToTop() {
streamViewController.scrollToTop(animated: true)
}
func loadNewPosts() {
let scrollView = streamViewController.collectionView
scrollView.setContentOffset(CGPoint(x: 0, y: -scrollView.contentInset.top), animated: true)
postNotification(NewContentNotifications.reloadFollowingContent, value: ())
screen.newPostsButtonVisible = false
}
}
| mit |
huangboju/Moots | Examples/UIScrollViewDemo/UIScrollViewDemo/Account/Views/MyCoRightsRecommendView.swift | 1 | 5494 | //
// File.swift
// UIScrollViewDemo
//
// Created by 黄伯驹 on 2017/11/9.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
class MyCoRightsRecommendViewCell: UICollectionViewCell, Reusable {
private lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.backgroundColor = UIColor(white: 0.95, alpha: 1)
return imageView
}()
private lazy var titleLabel: UILabel = {
let titleLabel = generatLabel(with: UIFontMake(14))
titleLabel.backgroundColor = UIColor.blue
return titleLabel
}()
private lazy var pormtLabel: UILabel = {
let pormtLabel = generatLabel(with: UIFontMake(12))
pormtLabel.textColor = UIColor(hex: 0x4A4A4A)
pormtLabel.backgroundColor = UIColor.red
return pormtLabel
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor(white: 0.9, alpha: 1)
contentView.addSubview(imageView)
contentView.addSubview(titleLabel)
contentView.addSubview(pormtLabel)
}
override func layoutSubviews() {
super.layoutSubviews()
let width = bounds.width
imageView.frame = CGSize(width: width, height: 125).rect
titleLabel.frame = CGRect(x: 11, y: imageView.frame.maxY + 6, width: width - 22, height: 20)
pormtLabel.frame = CGRect(x: titleLabel.frame.minX, y: titleLabel.frame.maxY + 2, width: width - 22, height: 17)
}
private func generatLabel(with font: UIFont) -> UILabel {
let label = UILabel()
label.font = font
return label
}
public func updateCell() {}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class MyCoRightsRecommendView: UIView {
public var data: [String] = []
private let layout = MyCollectionViewLayout()
private(set) var collectionView: UICollectionView!
override func layoutSubviews() {
super.layoutSubviews()
collectionView.frame = bounds
layout.itemSize = CGSize(width: (bounds.width - 3) / 2, height: 181)
}
override init(frame: CGRect) {
super.init(frame: frame)
collectionView = {
self.layout.minimumLineSpacing = 11
self.layout.minimumInteritemSpacing = 3
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: self.layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = .white
collectionView.register(cellType: MyCoRightsRecommendViewCell.self)
collectionView.register(MyCollectionHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header")
return collectionView
}()
addSubview(collectionView)
}
private weak var headerView: FormView?
public func addHeaderView(_ headerView: FormView) {
self.headerView = headerView
collectionView.addSubview(headerView)
}
public func freshView() {
collectionView.reloadData()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension MyCoRightsRecommendView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: MyCoRightsRecommendViewCell = collectionView.dequeueReusableCell(for: indexPath)
cell.updateCell()
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
return collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath)
}
}
extension MyCoRightsRecommendView: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
headerView?.layoutIfNeeded()
// 导航栏似乎有影响
guard var size = headerView?.contentSize else {
return .zero
}
size.height -= 64
return CGSize(width: SCREEN_WIDTH, height: size.height)
}
}
class MyCollectionHeaderView: UICollectionReusableView {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .red
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class MyCollectionViewLayout: UICollectionViewFlowLayout {
override func prepare() {
super.prepare()
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let attrs = super.layoutAttributesForElements(in: rect)
if let aaa = attrs {
for attr in aaa {
if attr.representedElementKind == UICollectionView.elementKindSectionHeader {
print(attr)
}
}
}
return attrs
}
}
| mit |
banxi1988/BXLoadMoreControl | Example/Pods/PinAuto/Pod/Classes/UIView+PinAuto.swift | 4 | 14358 | //
// UIView+PinAuto.swift
// Pods
//
// Created by Haizhen Lee on 16/1/14.
//
//
import UIKit
// PinAuto Chian Style Method Value Container
open class LayoutConstraintParams{
open var priority:UILayoutPriority = UILayoutPriorityRequired
open var relation: NSLayoutRelation = NSLayoutRelation.equal
open var firstItemAttribute:NSLayoutAttribute = NSLayoutAttribute.notAnAttribute
open var secondItemAttribute:NSLayoutAttribute = NSLayoutAttribute.notAnAttribute
open var multiplier:CGFloat = 1.0
open var constant:CGFloat = 0
open let firstItem:UIView
open var secondItem:AnyObject?
open var identifier:String? = LayoutConstraintParams.constraintIdentifier
open static let constraintIdentifier = "pin_auto"
fileprivate let attributesOfOpposite: [NSLayoutAttribute] = [.right,.rightMargin,.trailing,.trailingMargin,.bottom,.bottomMargin]
fileprivate var shouldReverseValue:Bool{
if firstItemAttribute == secondItemAttribute{
return attributesOfOpposite.contains(firstItemAttribute)
}
return false
}
public init(firstItem:UIView){
self.firstItem = firstItem
}
open var required:LayoutConstraintParams{
priority = UILayoutPriorityRequired
return self
}
open func withPriority(_ value:UILayoutPriority) -> LayoutConstraintParams{
priority = value
return self
}
open var withLowPriority:LayoutConstraintParams{
priority = UILayoutPriorityDefaultLow
return self
}
open var withHighPriority:LayoutConstraintParams{
priority = UILayoutPriorityDefaultHigh
return self
}
open func decrPriorityBy(_ value:UILayoutPriority) -> LayoutConstraintParams{
priority = priority - value
return self
}
open func incrPriorityBy(_ value:UILayoutPriority) -> LayoutConstraintParams{
priority = priority - value
return self
}
open func withRelation(_ relation:NSLayoutRelation){
self.relation = relation
}
open var withGteRelation:LayoutConstraintParams{
self.relation = .greaterThanOrEqual
return self
}
open var withLteRelation:LayoutConstraintParams{
self.relation = .lessThanOrEqual
return self
}
open var withEqRelation:LayoutConstraintParams{
self.relation = .equal
return self
}
open func multiplyBy(_ multiplier:CGFloat) -> LayoutConstraintParams{
self.multiplier = multiplier
return self
}
open func to(_ value:CGFloat) -> LayoutConstraintParams{
constant = value
relation = .equal
return self
}
open func equal(_ value:CGFloat) -> LayoutConstraintParams{
constant = value
relation = .equal
return self
}
open func equalTo(_ value:CGFloat) -> LayoutConstraintParams{
constant = value
relation = .equal
return self
}
open func eq(_ value:CGFloat) -> LayoutConstraintParams{
constant = value
relation = .equal
return self
}
open func lte(_ value:CGFloat) -> LayoutConstraintParams{
constant = value
relation = .lessThanOrEqual
return self
}
open func gte(_ value:CGFloat) -> LayoutConstraintParams{
constant = value
relation = .greaterThanOrEqual
return self
}
open func to(_ item:UIView) -> LayoutConstraintParams{
secondItem = item
return self
}
open func to(_ item:UILayoutSupport) -> LayoutConstraintParams{
secondItem = item
return self
}
open func equalTo(_ item:UIView) -> LayoutConstraintParams{
secondItem = item
relation = .equal
secondItemAttribute = firstItemAttribute
return self
}
open func eqTo(_ item:UIView) -> LayoutConstraintParams{
secondItem = item
relation = .equal
secondItemAttribute = firstItemAttribute
return self
}
open func offset(_ value:CGFloat) -> LayoutConstraintParams{
constant = value
return self
}
open func lteTo(_ item:UIView) -> LayoutConstraintParams{
secondItem = item
relation = .lessThanOrEqual
secondItemAttribute = firstItemAttribute
return self
}
open func gteTo(_ item:UIView) -> LayoutConstraintParams{
secondItem = item
relation = .greaterThanOrEqual
secondItemAttribute = firstItemAttribute
return self
}
open func lessThanOrEqualTo(_ item:UIView) -> LayoutConstraintParams{
secondItem = item
relation = .lessThanOrEqual
secondItemAttribute = firstItemAttribute
return self
}
open func greaterThanOrEqualTo(_ item:UIView) -> LayoutConstraintParams{
secondItem = item
relation = .greaterThanOrEqual
secondItemAttribute = firstItemAttribute
return self
}
open func identifier(_ id:String?) -> LayoutConstraintParams{
self.identifier = id
return self
}
open func equalTo(_ itemAttribute:NSLayoutAttribute,ofView view:UIView) -> LayoutConstraintParams{
self.secondItem = view
self.relation = .equal
self.secondItemAttribute = itemAttribute
return self
}
open var inSuperview: LayoutConstraintParams{
secondItem = firstItem.superview
return self
}
open var toSuperview: LayoutConstraintParams{
secondItem = firstItem.superview
return self
}
open func autoadd() -> NSLayoutConstraint{
return install()
}
@discardableResult
open func install() -> NSLayoutConstraint{
let finalConstanValue = shouldReverseValue ? -constant : constant
let constraint = NSLayoutConstraint(item: firstItem,
attribute: firstItemAttribute,
relatedBy: relation,
toItem: secondItem,
attribute: secondItemAttribute,
multiplier: multiplier,
constant: finalConstanValue)
constraint.identifier = identifier
firstItem.translatesAutoresizingMaskIntoConstraints = false
if let secondItem = secondItem{
firstItem.assertHasSuperview()
let containerView:UIView
if let secondItemView = secondItem as? UIView{
if firstItem.superview == secondItemView{
containerView = secondItemView
}else if firstItem.superview == secondItemView.superview{
containerView = firstItem.superview!
}else{
fatalError("Second Item Should be First Item 's superview or sibling view")
}
}else if secondItem is UILayoutSupport{
containerView = firstItem.superview!
}else{
fatalError("Second Item Should be UIView or UILayoutSupport")
}
containerView.addConstraint(constraint)
}else{
firstItem.addConstraint(constraint)
}
return constraint
}
}
// PinAuto Core Method
public extension UIView{
fileprivate var pa_makeConstraint:LayoutConstraintParams{
assertHasSuperview()
return LayoutConstraintParams(firstItem: self)
}
public var pa_width:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.firstItemAttribute = .width
pa.secondItem = nil
pa.secondItemAttribute = .notAnAttribute
return pa
}
public var pa_height:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.firstItemAttribute = .height
pa.secondItem = nil
pa.secondItemAttribute = .notAnAttribute
return pa
}
@available(*,introduced: 1.2)
public func pa_aspectRatio(_ ratio:CGFloat) -> LayoutConstraintParams{
let pa = pa_makeConstraint
pa.firstItemAttribute = .height
pa.secondItemAttribute = .width
pa.secondItem = self
pa.multiplier = ratio // height = width * ratio
// ratio = width:height
return pa
}
public var pa_leading:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.firstItemAttribute = .leading
pa.secondItem = superview
pa.secondItemAttribute = .leading
return pa
}
public var pa_trailing:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .trailing
pa.secondItemAttribute = .trailing
return pa
}
public var pa_top:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .top
pa.secondItemAttribute = .top
return pa
}
public var pa_bottom:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .bottom
pa.secondItemAttribute = .bottom
return pa
}
public var pa_centerX:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .centerX
pa.secondItemAttribute = .centerX
return pa
}
public var pa_centerY:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .centerY
pa.secondItemAttribute = .centerY
return pa
}
public var pa_left:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .left
pa.secondItemAttribute = .left
return pa
}
public var pa_right:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .right
pa.secondItemAttribute = .right
return pa
}
public var pa_leadingMargin:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .leadingMargin
pa.secondItemAttribute = .leadingMargin
return pa
}
public var pa_trailingMargin:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .trailingMargin
pa.secondItemAttribute = .trailingMargin
return pa
}
public var pa_topMargin:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .topMargin
pa.secondItemAttribute = .topMargin
return pa
}
public var pa_bottomMargin:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .bottomMargin
pa.secondItemAttribute = .bottomMargin
return pa
}
public var pa_leftMargin:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .leftMargin
pa.secondItemAttribute = .leadingMargin
return pa
}
public var pa_rightMargin:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .rightMargin
pa.secondItemAttribute = .rightMargin
return pa
}
public var pa_centerXWithinMargins:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .centerXWithinMargins
pa.secondItemAttribute = .centerXWithinMargins
return pa
}
public var pa_centerYWithinMargins:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .centerYWithinMargins
pa.secondItemAttribute = .centerYWithinMargins
return pa
}
public var pa_baseline:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.firstItemAttribute = .lastBaseline
return pa
}
public var pa_firstBaseline:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.firstItemAttribute = .firstBaseline
return pa
}
public var pa_lastBaseline:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.firstItemAttribute = NSLayoutAttribute.lastBaseline
return pa
}
public func pa_below(_ item:UILayoutSupport,offset:CGFloat = 0) -> LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = item
pa.firstItemAttribute = .top
pa.relation = .equal
pa.secondItemAttribute = .bottom
pa.constant = offset
return pa
}
public func pa_below(_ item:UIView,offset:CGFloat = 0) -> LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = item
pa.firstItemAttribute = .top
pa.relation = .equal
pa.secondItemAttribute = .bottom
pa.constant = offset
return pa
}
public func pa_above(_ item:UIView,offset:CGFloat = 0) -> LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = item
pa.firstItemAttribute = .bottom
pa.relation = .equal
pa.secondItemAttribute = .top
pa.constant = -offset
return pa
}
public func pa_above(_ item:UILayoutSupport,offset:CGFloat = 0) -> LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = item
pa.firstItemAttribute = .bottom
pa.relation = .equal
pa.secondItemAttribute = .top
pa.constant = -offset
return pa
}
public func pa_toLeadingOf(_ item:UIView,offset:CGFloat = 0) -> LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = item
pa.firstItemAttribute = .trailing
pa.relation = .equal
pa.secondItemAttribute = .leading
pa.constant = -offset
return pa
}
public func pa_before(_ item:UIView,offset:CGFloat = 0) -> LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = item
pa.firstItemAttribute = .trailing
pa.relation = .equal
pa.secondItemAttribute = .leading
pa.constant = -offset
return pa
}
public func pa_toLeftOf(_ item:UIView,offset:CGFloat = 0) -> LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = item
pa.firstItemAttribute = .right
pa.relation = .equal
pa.secondItemAttribute = .left
pa.constant = -offset
return pa
}
public func pa_toTrailingOf(_ item:UIView,offset:CGFloat = 0) -> LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = item
pa.firstItemAttribute = .leading
pa.relation = .equal
pa.secondItemAttribute = .trailing
pa.constant = offset
return pa
}
public func pa_after(_ item:UIView,offset:CGFloat = 0) -> LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = item
pa.firstItemAttribute = .leading
pa.relation = .equal
pa.secondItemAttribute = .trailing
pa.constant = offset
return pa
}
public func pa_toRightOf(_ item:UIView,offset:CGFloat = 0) -> LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = item
pa.firstItemAttribute = .left
pa.relation = .equal
pa.secondItemAttribute = .right
pa.constant = offset
return pa
}
}
| mit |
corujautx/Announce | Sources/Core/Announce.swift | 1 | 906 | //
// Announce.swift
// Announce
//
// Created by Vitor Travain on 5/22/17.
// Copyright © 2017 Vitor Travain. All rights reserved.
//
import Foundation
import UIKit
@discardableResult public func announce<T: Announcement>(_ announcement: T,
withCustomPresenter presenter: Presenter) -> DismissalToken where T: UIView {
return presenter.present(announcement: announcement)
}
@discardableResult public func announce<T: Announcement>(_ announcement: T,
on context: PresentationContext,
withMode mode: PresentationMode = .indefinite) -> DismissalToken where T: UIView {
let presenter = PresenterFactory.presenter(withContext: context, andMode: mode)
return announce(announcement, withCustomPresenter: presenter)
}
| mit |
turingcorp/gattaca | gattaca/Controller/ProfileEdit/CProfileEdit.swift | 1 | 302 | import Foundation
class CProfileEdit:Controller<VProfileEdit, MProfileEdit>
{
//MARK: private
private func back()
{
parentController?.pop(
vertical:ControllerParent.Vertical.bottom)
}
//MARK: internal
func done()
{
back()
}
}
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/17144-swift-sourcemanager-getmessage.swift | 11 | 283 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol a
{
deinit {
println(
[ {
case
{
var d { func b {
enum b {
{
}
extension NSData {
class A {
class
case ,
| mit |
huonw/swift | validation-test/stdlib/Array/ArraySliceWithNonZeroStartIndex_RangeReplaceableRandomAccessCollectionVal.swift | 36 | 1493 | //===----------------------------------------------------------------------===//
// Automatically Generated From validation-test/stdlib/Array/Inputs/ArrayConformanceTests.swift.gyb
// Do Not Edit Directly!
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: optimized_stdlib
import StdlibUnittest
import StdlibCollectionUnittest
let tests = TestSuite("ArraySliceWithNonZeroStartIndex_RangeReplaceableRandomAccessCollectionVal")
func ArraySliceWithNonZeroStartIndex<T>(_ elements: [T]) -> ArraySlice<T> {
var r = ArraySlice<T>(_startIndex: 1000)
r.append(contentsOf: elements)
expectEqual(1000, r.startIndex)
return r
}
do {
var resiliencyChecks = CollectionMisuseResiliencyChecks.all
resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .none
// Test RangeReplaceableCollectionType conformance with value type elements.
tests.addRangeReplaceableRandomAccessSliceTests(
"ArraySliceWithNonZeroStartIndex.",
makeCollection: { (elements: [OpaqueValue<Int>]) in
return ArraySliceWithNonZeroStartIndex(elements)
},
wrapValue: identity,
extractValue: identity,
makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in
return ArraySliceWithNonZeroStartIndex(elements)
},
wrapValueIntoEquatable: identityEq,
extractValueFromEquatable: identityEq,
resiliencyChecks: resiliencyChecks)
} // do
runAllTests()
| apache-2.0 |
TouchInstinct/LeadKit | TIFoundationUtils/CodableKeyValueStorage/Sources/Encoders/JSONKeyValueEncoder.swift | 1 | 1630 | //
// Copyright (c) 2020 Touch Instinct
//
// 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
open class JSONKeyValueEncoder: CodableKeyValueEncoder {
private let jsonEncoder: JSONEncoder
public init(jsonEncoder: JSONEncoder = JSONEncoder()) {
self.jsonEncoder = jsonEncoder
}
open func encodeEncodable<Value: Encodable>(value: Value, for key: StorageKey<Value>) throws -> Data {
do {
return try jsonEncoder.encode(value)
} catch {
throw StorageError.unableToEncode(underlyingError: error)
}
}
}
| apache-2.0 |
SmallElephant/FEAlgorithm-Swift | 4-ListNode/4-ListNode/main.swift | 1 | 4745 | //
// main.swift
// 4-ListNode
//
// Created by FlyElephant on 16/6/12.
// Copyright © 2016年 FlyElephant. All rights reserved.
//
import Foundation
var node1=ListNode()
node1.value=10
var node2=ListNode()
node2.value=20
node1.next=node2
var node3=ListNode()
node3.value=30
node2.next=node3
var node4 = ListNode()
node4.value=40
node3.next=node4
var node5 = ListNode()
node5.value=50
node4.next=node5
//var listManager:ListNodeManager = ListNodeManager()
//var head:ListNode?
//var firstNode:ListNode?
//var deleteNode:ListNode?
//listManager.createList(&head, data: 11)
//firstNode = head
//
//listManager.createList(&head, data: 12)
//listManager.createList(&head, data: 13)
//deleteNode = head
//listManager.createList(&head, data: 14)
//listManager.createList(&head, data: 15)
//
//listManager.deleteNode(head: &firstNode, toBeDeleted: &deleteNode)
//print("FlyElephant")
//listManager.printList(firstNode)
var searchManager:ListNodeManager = ListNodeManager()
var headNode:ListNode?
var searchHeadNode:ListNode?
searchManager.createList(&headNode, data: 1)
searchHeadNode = headNode
searchManager.createList(&headNode, data: 2)
searchManager.createList(&headNode, data: 3)
searchManager.createList(&headNode, data: 4)
searchManager.createList(&headNode, data: 5)
searchManager.createList(&headNode, data: 6)
searchManager.createList(&headNode, data: 7)
searchManager.createList(&headNode, data: 8)
searchManager.createList(&headNode, data: 9)
var searchNode:SearchNode = SearchNode()
var reverseNode:ListNode? = searchNode.reverseNodeList(head: searchHeadNode)
//searchNode.printList(reverseNode)
var mergeHeadNode:ListNode?
var mergeHead1:ListNode?
searchNode.createList(&mergeHeadNode, data: 1)
mergeHead1 = mergeHeadNode
searchNode.createList(&mergeHeadNode, data: 3)
searchNode.createList(&mergeHeadNode, data: 5)
searchNode.createList(&mergeHeadNode, data: 7)
var mergeHeadNode2:ListNode?
var mergeHead2:ListNode?
searchNode.createList(&mergeHeadNode2, data: 2)
mergeHead2 = mergeHeadNode2
searchNode.createList(&mergeHeadNode2, data: 4)
searchNode.createList(&mergeHeadNode2, data: 6)
searchNode.createList(&mergeHeadNode2, data: 8)
searchNode.printList(mergeHead1)
searchNode.printList(mergeHead2)
var mergeResultNode:ListNode? = searchNode.mergeSortList(head: mergeHead1, nextHead: mergeHead2)
searchNode.printList(mergeResultNode)
//var resultNode:ListNode? = searchNode.findNodeByDescendIndex(head: searchHeadNode, index: 3)
//if resultNode != nil {
// print("FlyElephant-节点的Value--\(resultNode!.value!)")
//} else {
// print("节点没有值")
//}
//
//var centerNode:ListNode? = searchNode.findCenterNode(head: searchHeadNode)
//if centerNode != nil {
// print("FlyElephant-中点的Value--\(centerNode!.value!)")
//} else {
// print("中点没有值")
//}
var randomHead:RandomListNode = RandomListNode()
randomHead.data = "A"
var randomNode1:RandomListNode = RandomListNode()
randomNode1.data = "B"
randomHead.next = randomNode1
var randomNode2:RandomListNode = RandomListNode()
randomNode2.data = "C"
randomNode1.next = randomNode2
var randomNode3:RandomListNode = RandomListNode()
randomNode3.data = "D"
randomNode2.next = randomNode3
var randomNode4:RandomListNode = RandomListNode()
randomNode4.data = "E"
randomNode3.next = randomNode4
randomHead.sibling = randomNode2
randomNode1.sibling = randomNode4
randomNode3.sibling = randomNode1
var pHead:RandomListNode? = randomHead
var clone:RandomListClone = RandomListClone()
clone.randomListNodeClone(headNode: &pHead)
while pHead != nil {
print("随机节点--\(pHead!.data)---👬--\(pHead!.sibling?.data)")
pHead = pHead?.next
}
var firstSearchNode:ListNode?
var firstSearchHead:ListNode?
searchNode.createList(&firstSearchNode, data: 1)
firstSearchHead = firstSearchNode
searchNode.createList(&firstSearchNode, data: 2)
searchNode.createList(&firstSearchNode, data: 3)
searchNode.createList(&firstSearchNode, data: 6)
searchNode.createList(&firstSearchNode, data: 7)
var nextSearchNode:ListNode?
var nextSearchHead:ListNode?
searchNode.createList(&nextSearchNode, data: 4)
nextSearchHead = nextSearchNode
searchNode.createList(&nextSearchNode, data: 5)
searchNode.createList(&nextSearchNode, data: 6)
searchNode.createList(&nextSearchNode, data: 7)
searchNode.printList(nextSearchHead)
var commonNode:ListNode? = searchNode.findFirstCommon(firstHead: firstSearchHead, nextHead: nextSearchHead)
if commonNode == nil {
print("没有公共节点")
} else {
print("第一个公共节点的值-\(commonNode!.value!)")
}
var josephList:JosephList = JosephList()
var josephHeadNode:ListNode? = josephList.createList(number: 5)
josephList.printList(headNode: josephHeadNode!, number: 5)
| mit |
yoichitgy/SwinjectMVVMExample_ForBlog | Carthage/Checkouts/Himotoki/Tests/NestedObjectParsingTest.swift | 3 | 818 | //
// NestedObjectParsingTest.swift
// Himotoki
//
// Created by Syo Ikeda on 11/30/15.
// Copyright © 2015 Syo Ikeda. All rights reserved.
//
import XCTest
import Himotoki
class NestedObjectParsingTest: XCTestCase {
func testParseNestedObjectSuccess() {
let success: WithNestedObject? = try? decode([ "nested": [ "name": "Foo Bar" ] ])
XCTAssertNotNil(success)
XCTAssertEqual(success?.nestedName, "Foo Bar")
}
func testParseNestedObjectFailure() {
let failure: WithNestedObject? = try? decode([ "nested": "Foo Bar" ])
XCTAssertNil(failure)
}
}
struct WithNestedObject: Decodable {
let nestedName: String
static func decode(e: Extractor) throws -> WithNestedObject {
return self.init(nestedName: try e <| [ "nested", "name" ])
}
}
| mit |
breadwallet/breadwallet-ios | Screenshots/Screenshots.swift | 1 | 2010 | //
// Screenshots.swift
// Screenshots
//
// Created by Adrian Corscadden on 2017-07-02.
// Copyright © 2017-2019 Breadwinner AG. All rights reserved.
//
import XCTest
class Screenshots: XCTestCase {
override func setUp() {
super.setUp()
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
let app = XCUIApplication()
setupSnapshot(app)
app.launch()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
snapshot("2LockScreen")
let app = XCUIApplication()
let staticText = app.collectionViews.staticTexts["5"]
staticText.tap()
staticText.tap()
staticText.tap()
staticText.tap()
staticText.tap()
staticText.tap()
// go back to home screen if needed
let backButton = app.navigationBars.buttons.element(boundBy: 0)
if backButton.exists {
backButton.tap()
}
snapshot("0HomeScreen")
// tx list
let tablesQuery = app.tables
tablesQuery.staticTexts["Bitcoin"].tap()
snapshot("1TxList")
app.navigationBars.buttons.element(boundBy: 0).tap()
enum Rows: Int {
case bitcoin = 0
case addWallet = 4 // number of currencies
case settings
case security
case support
}
tablesQuery.buttons["Add Wallet"].tap()
snapshot("3AddWallet")
}
}
| mit |
zhangjk4859/MyWeiBoProject | sinaWeibo/sinaWeibo/Classes/Compose/表情选择器/EmoticonTextAttachment.swift | 1 | 845 | //
// EmoticonTextAttachment.swift
// sinaWeibo
//
// Created by 张俊凯 on 16/7/27.
// Copyright © 2016年 张俊凯. All rights reserved.
//
import UIKit
class EmoticonTextAttachment: NSTextAttachment {
// 保存对应表情的文字
var chs: String?
/// 根据表情模型, 创建表情字符串
class func imageText(emoticon: Emoticon, font: UIFont) -> NSAttributedString{
// 1.创建附件
let attachment = EmoticonTextAttachment()
attachment.chs = emoticon.chs
attachment.image = UIImage(contentsOfFile: emoticon.imagePath!)
// 设置了附件的大小
let s = font.lineHeight
attachment.bounds = CGRectMake(0, -4, s, s)
// 2. 根据附件创建属性字符串
return NSAttributedString(attachment: attachment)
}
}
| mit |
google/GoogleDataTransport | GoogleDataTransport/GDTCCTTestApp/gdthelpers.swift | 1 | 950 | /*
* Copyright 2019 Google
*
* 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 GoogleDataTransport
class FirelogTestMessageHolder: NSObject, GDTCOREventDataObject {
public var root: FirelogTestMessage = .init()
func transportBytes() -> Data {
do {
let data: Data? = try root.serializedData()
return data!
} catch {
print("There was an error producing proto bytes.")
return Data()
}
}
}
| apache-2.0 |
leizh007/HiPDA | HiPDA/HiPDA/Sections/Home/Post/PostResult.swift | 1 | 779 | //
// PostResult.swift
// HiPDA
//
// Created by leizh007 on 2017/5/17.
// Copyright © 2017年 HiPDA. All rights reserved.
//
import Foundation
enum PostError: Error {
case parseError(String)
case unKnown(String)
}
// MARK: - CustomStringConvertible
extension PostError: CustomStringConvertible {
var description: String {
switch self {
case let .parseError(errorString):
return errorString
case let .unKnown(errorString):
return errorString
}
}
}
extension PostError: LocalizedError {
var errorDescription: String? {
return description
}
}
typealias PostResult = HiPDA.Result<String, PostError>
typealias PostListResult = HiPDA.Result<(title: String?, posts: [Post]), PostError>
| mit |
microeditionbiz/ML-client | ML-client/View Controllers/InstallmentsViewController.swift | 1 | 3728 | //
// InstallmentsViewController.swift
// ML-client
//
// Created by Pablo Romero on 8/13/17.
// Copyright © 2017 Pablo Romero. All rights reserved.
//
import UIKit
class InstallmentsViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
var paymentInfo: PaymentInfo!
var installments: Installments?
var selectedPayerCost: Installments.PayerCost?
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
loadData()
}
// MARK: - Setup
private func setupTableView() {
// This is to don't have empty cells
tableView.tableFooterView = UIView()
tableView.backgroundColor = UIColor.clear
tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableViewAutomaticDimension
}
// MARK: - Content
private func setLoadingMode(on: Bool) {
if on {
activityIndicatorView.startAnimating()
} else {
activityIndicatorView.stopAnimating()
}
activityIndicatorView.isHidden = !on
tableView.isHidden = on
}
// MARK: - Networking
private func loadData() {
guard let paymentMethodId = paymentInfo?.paymentMethod?.id, let cardIssuerId = paymentInfo?.cardIssuer?.id, let amount = paymentInfo?.amount else {
assertionFailure("Missing required info")
return
}
setLoadingMode(on: true)
MPAPI.sharedInstance.installments(paymentMethodId: paymentMethodId, issuerId: cardIssuerId, amount: amount) { (installments, error) in
self.setLoadingMode(on: false)
if let error = error {
UIAlertController.presentAlert(withError: error, overViewController: self)
} else {
self.installments = installments
self.tableView.reloadData()
}
}
}
// MARK: - Actions
@IBAction func payAction(_ sender: UIBarButtonItem) {
if selectedPayerCost == nil {
UIAlertController.presentAlert(message: "Primero debe seleccionar un plan de pagos.", overViewController: self)
} else {
completePaymentFlow()
}
}
// MARK: - Navigation
fileprivate func completePaymentFlow() {
UIAlertController.presentQuestion(text: "Proceder con el pago?", okTitle: "Ok", cancelTitle: "Cancelar", overViewController: self) { (pay) in
if pay {
self.paymentInfo?.payerCost = self.selectedPayerCost
self.paymentInfo?.completePaymentFlow()
}
}
}
}
// MARK: - Extensions
extension InstallmentsViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return installments?.payerCosts?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let payerCost = installments!.payerCosts![indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "PayerCostCell", for: indexPath) as! PayerCostCell
cell.update(withPayerCost: payerCost)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedPayerCost = installments?.payerCosts![indexPath.row]
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
selectedPayerCost = nil
}
}
| mit |
RoRoche/iOSSwiftStarter | iOSSwiftStarter/Pods/Nimble/Sources/Nimble/Matchers/BeginWith.swift | 111 | 2446 | import Foundation
/// A Nimble matcher that succeeds when the actual sequence's first element
/// is equal to the expected value.
public func beginWith<S: SequenceType, T: Equatable where S.Generator.Element == T>(startingElement: T) -> NonNilMatcherFunc<S> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "begin with <\(startingElement)>"
if let actualValue = try actualExpression.evaluate() {
var actualGenerator = actualValue.generate()
return actualGenerator.next() == startingElement
}
return false
}
}
/// A Nimble matcher that succeeds when the actual collection's first element
/// is equal to the expected object.
public func beginWith(startingElement: AnyObject) -> NonNilMatcherFunc<NMBOrderedCollection> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "begin with <\(startingElement)>"
let collection = try actualExpression.evaluate()
return collection != nil && collection!.indexOfObject(startingElement) == 0
}
}
/// A Nimble matcher that succeeds when the actual string contains expected substring
/// where the expected substring's location is zero.
public func beginWith(startingSubstring: String) -> NonNilMatcherFunc<String> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "begin with <\(startingSubstring)>"
if let actual = try actualExpression.evaluate() {
let range = actual.rangeOfString(startingSubstring)
return range != nil && range!.startIndex == actual.startIndex
}
return false
}
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func beginWithMatcher(expected: AnyObject) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let actual = try! actualExpression.evaluate()
if let _ = actual as? String {
let expr = actualExpression.cast { $0 as? String }
return try! beginWith(expected as! String).matches(expr, failureMessage: failureMessage)
} else {
let expr = actualExpression.cast { $0 as? NMBOrderedCollection }
return try! beginWith(expected).matches(expr, failureMessage: failureMessage)
}
}
}
}
#endif
| apache-2.0 |
apple/swift-package-manager | Sources/PackageModel/Toolchain.swift | 2 | 2738 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift 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 http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TSCBasic
public protocol Toolchain {
/// Path of the librarian.
var librarianPath: AbsolutePath { get }
/// Path of the `swiftc` compiler.
var swiftCompilerPath: AbsolutePath { get }
/// Path containing the macOS Swift stdlib.
var macosSwiftStdlib: AbsolutePath { get throws }
/// Path of the `clang` compiler.
func getClangCompiler() throws -> AbsolutePath
// FIXME: This is a temporary API until index store is widely available in
// the OSS clang compiler. This API should not used for any other purpose.
/// Returns true if clang compiler's vendor is Apple and nil if unknown.
func _isClangCompilerVendorApple() throws -> Bool?
/// Additional flags to be passed to the build tools.
var extraFlags: BuildFlags { get }
/// Additional flags to be passed to the C compiler.
@available(*, deprecated, message: "use extraFlags.cCompilerFlags instead")
var extraCCFlags: [String] { get }
/// Additional flags to be passed to the Swift compiler.
@available(*, deprecated, message: "use extraFlags.swiftCompilerFlags instead")
var extraSwiftCFlags: [String] { get }
/// Additional flags to be passed to the C++ compiler.
@available(*, deprecated, message: "use extraFlags.cxxCompilerFlags instead")
var extraCPPFlags: [String] { get }
}
extension Toolchain {
public func _isClangCompilerVendorApple() throws -> Bool? {
return nil
}
public var macosSwiftStdlib: AbsolutePath {
get throws {
return try AbsolutePath(validating: "../../lib/swift/macosx", relativeTo: resolveSymlinks(swiftCompilerPath))
}
}
public var toolchainLibDir: AbsolutePath {
get throws {
// FIXME: Not sure if it's better to base this off of Swift compiler or our own binary.
return try AbsolutePath(validating: "../../lib", relativeTo: resolveSymlinks(swiftCompilerPath))
}
}
public var extraCCFlags: [String] {
extraFlags.cCompilerFlags
}
public var extraCPPFlags: [String] {
extraFlags.cxxCompilerFlags
}
public var extraSwiftCFlags: [String] {
extraFlags.swiftCompilerFlags
}
}
| apache-2.0 |
blockchain/My-Wallet-V3-iOS | Modules/BlockchainComponentLibrary/Sources/Examples/2 - Primitives/Buttons/SmallSecondaryButtonExamples.swift | 1 | 1049 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainComponentLibrary
import SwiftUI
struct SmallSecondaryButtonExamplesView: View {
var body: some View {
VStack(spacing: Spacing.baseline) {
SmallSecondaryButton(title: "OK", isLoading: false) {
print("Tapped")
}
.previewLayout(.sizeThatFits)
.previewDisplayName("Enabled")
SmallSecondaryButton(title: "OK", isLoading: false) {
print("Tapped")
}
.disabled(true)
.previewLayout(.sizeThatFits)
.previewDisplayName("Disabled")
SmallSecondaryButton(title: "OK", isLoading: true) {
print("Tapped")
}
.previewLayout(.sizeThatFits)
.previewDisplayName("Loading")
}
.padding()
}
}
struct SmallSecondaryButtonExamplesView_Previews: PreviewProvider {
static var previews: some View {
SmallSecondaryButtonExamplesView()
}
}
| lgpl-3.0 |
blockchain/My-Wallet-V3-iOS | Modules/FeatureDashboard/Sources/FeatureDashboardUI/BuyButton/BuyButtonReducer.swift | 1 | 439 | import ComposableArchitecture
import MoneyKit
let buyButtonReducer = Reducer<
BuyButtonState,
BuyButtonAction,
BuyButtonEnvironment
> { state, action, environment in
switch action {
case .buyTapped:
let cryptoCurrency: CryptoCurrency = state.cryptoCurrency ?? .bitcoin
return .fireAndForget {
environment.walletOperationsRouter.handleBuyCrypto(currency: cryptoCurrency)
}
}
}
| lgpl-3.0 |
blockchain/My-Wallet-V3-iOS | Modules/HDWallet/Sources/HDWalletKit/Models/Network.swift | 1 | 461 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
protocol CoinType {
static var coinType: UInt32 { get }
}
// TODO:
// * Move to BitcoinKit
// * Is this the right design???
struct Bitcoin: CoinType {
static let coinType: UInt32 = 0
}
struct Blockstack: CoinType {
static let coinType: UInt32 = 5757
}
// TODO:
// * For now `CoinType` is not supported by LibWally-Swift,
enum Network {
case main(CoinType.Type)
case test
}
| lgpl-3.0 |
XiongJoJo/OFO | App/OFO/OFOTests/OFOTests.swift | 1 | 943 | //
// OFOTests.swift
// OFOTests
//
// Created by iMac on 2017/6/1.
// Copyright © 2017年 JoJo. All rights reserved.
//
import XCTest
@testable import OFO
class OFOTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| apache-2.0 |
apple/swift-nio-http2 | Sources/NIOHPACK/HPACKHeader.swift | 1 | 25458 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
import NIOHTTP1
/// Very similar to `NIOHTTP1.HTTPHeaders`, but with extra data for storing indexing
/// information.
public struct HPACKHeaders: ExpressibleByDictionaryLiteral, Sendable {
/// The maximum size of the canonical connection header value array to use when removing
/// connection headers during `HTTPHeaders` normalisation. When using an array the removal
/// is O(H·C) where H is the length of headers to noramlize and C is the length of the
/// connection header value array.
///
/// Beyond this limit we construct a set of the connection header values to reduce the
/// complexity to O(H).
///
/// We use an array for small connection header lists as it is cheaper (values don't need to be
/// hashed and constructing a set incurs an additional allocation). The value of 32 was picked
/// as the crossover point where using an array became more expensive than using a set when
/// running the `hpackheaders_normalize_httpheaders_removing_10k_conn_headers` performance test
/// with varying input sizes.
@usableFromInline
static let connectionHeaderValueArraySizeLimit = 32
@usableFromInline
internal var headers: [HPACKHeader]
// see 8.1.2.2. Connection-Specific Header Fields in RFC 7540
@usableFromInline
static let illegalHeaders: [String] = ["connection", "keep-alive", "proxy-connection",
"transfer-encoding", "upgrade"]
/// Constructor that can be used to map between `HTTPHeaders` and `HPACKHeaders` types.
@inlinable
public init(httpHeaders: HTTPHeaders, normalizeHTTPHeaders: Bool) {
if normalizeHTTPHeaders {
self.headers = httpHeaders.map { HPACKHeader(name: $0.name.lowercased(), value: $0.value) }
let connectionHeaderValue = httpHeaders[canonicalForm: "connection"]
// Above a limit we use a set rather than scanning the connection header value array.
// See `Self.connectionHeaderValueArraySizeLimit`.
if connectionHeaderValue.count > Self.connectionHeaderValueArraySizeLimit {
var headersToRemove = Set(connectionHeaderValue)
// Since we have a set we can just merge in the illegal headers.
headersToRemove.formUnion(Self.illegalHeaders.lazy.map { $0[...] })
self.headers.removeAll { header in
headersToRemove.contains(header.name[...])
}
} else {
self.headers.removeAll { header in
connectionHeaderValue.contains(header.name[...]) ||
HPACKHeaders.illegalHeaders.contains(header.name)
}
}
} else {
self.headers = httpHeaders.map { HPACKHeader(name: $0.name, value: $0.value) }
}
}
/// Constructor that can be used to map between `HTTPHeaders` and `HPACKHeaders` types.
@inlinable
public init(httpHeaders: HTTPHeaders) {
self.init(httpHeaders: httpHeaders, normalizeHTTPHeaders: true)
}
/// Construct a `HPACKHeaders` structure.
///
/// The indexability of all headers is assumed to be the default, i.e. indexable and
/// rewritable by proxies.
///
/// - parameters
/// - headers: An initial set of headers to use to populate the header block.
@inlinable
public init(_ headers: [(String, String)] = []) {
self.headers = headers.map { HPACKHeader(name: $0.0, value: $0.1) }
}
/// Construct a `HPACKHeaders` structure.
///
/// The indexability of all headers is assumed to be the default, i.e. indexable and
/// rewritable by proxies.
///
/// - Parameter elements: name, value pairs provided by a dictionary literal.
@inlinable
public init(dictionaryLiteral elements: (String, String)...) {
self.init(elements)
}
/// Construct a `HPACKHeaders` structure.
///
/// The indexability of all headers is assumed to be the default, i.e. indexable and
/// rewritable by proxies.
///
/// - parameters
/// - headers: An initial set of headers to use to populate the header block.
/// - allocator: The allocator to use to allocate the underlying storage.
@available(*, deprecated, renamed: "init(_:)")
public init(_ headers: [(String, String)] = [], allocator: ByteBufferAllocator) {
// We no longer use an allocator so we don't need this method anymore.
self.init(headers)
}
/// Internal initializer to make things easier for unit tests.
@inlinable
init(fullHeaders: [(HPACKIndexing, String, String)]) {
self.headers = fullHeaders.map { HPACKHeader(name: $0.1, value: $0.2, indexing: $0.0) }
}
/// Internal initializer for use in HPACK decoding.
@inlinable
init(headers: [HPACKHeader]) {
self.headers = headers
}
/// Add a header name/value pair to the block.
///
/// This method is strictly additive: if there are other values for the given header name
/// already in the block, this will add a new entry. `add` performs case-insensitive
/// comparisons on the header field name.
///
/// - Parameter name: The header field name. This must be an ASCII string. For HTTP/2 lowercase
/// header names are strongly encouraged.
/// - Parameter value: The header field value to add for the given name.
@inlinable
public mutating func add(name: String, value: String, indexing: HPACKIndexing = .indexable) {
precondition(!name.utf8.contains(where: { !$0.isASCII }), "name must be ASCII")
self.headers.append(HPACKHeader(name: name, value: value, indexing: indexing))
}
/// Add a sequence of header name/value pairs to the block.
///
/// This method is strictly additive: if there are other entries with the same header
/// name already in the block, this will add new entries.
///
/// - Parameter contentsOf: The sequence of header name/value pairs. Header names must be ASCII
/// strings. For HTTP/2 lowercase header names are strongly recommended.
@inlinable
public mutating func add<S: Sequence>(contentsOf other: S, indexing: HPACKIndexing = .indexable) where S.Element == (String, String) {
self.reserveCapacity(self.headers.count + other.underestimatedCount)
for (name, value) in other {
self.add(name: name, value: value, indexing: indexing)
}
}
/// Add a sequence of header name/value/indexing triplet to the block.
///
/// This method is strictly additive: if there are other entries with the same header
/// name already in the block, this will add new entries.
///
/// - Parameter contentsOf: The sequence of header name/value/indexing triplets. Header names
/// must be ASCII strings. For HTTP/2 lowercase header names are strongly recommended.
@inlinable
public mutating func add<S: Sequence>(contentsOf other: S) where S.Element == HPACKHeaders.Element {
self.reserveCapacity(self.headers.count + other.underestimatedCount)
for (name, value, indexing) in other {
self.add(name: name, value: value, indexing: indexing)
}
}
/// Add a header name/value pair to the block, replacing any previous values for the
/// same header name that are already in the block.
///
/// This is a supplemental method to `add` that essentially combines `remove` and `add`
/// in a single function. It can be used to ensure that a header block is in a
/// well-defined form without having to check whether the value was previously there.
/// Like `add`, this method performs case-insensitive comparisons of the header field
/// names.
///
/// - Parameter name: The header field name. For maximum compatibility this should be an
/// ASCII string. For future-proofing with HTTP/2 lowercase header names are strongly
/// recommended.
/// - Parameter value: The header field value to add for the given name.
@inlinable
public mutating func replaceOrAdd(name: String, value: String, indexing: HPACKIndexing = .indexable) {
self.remove(name: name)
self.add(name: name, value: value, indexing: indexing)
}
/// Remove all values for a given header name from the block.
///
/// This method uses case-insensitive comparisons for the header field name.
///
/// - Parameter name: The name of the header field to remove from the block.
@inlinable
public mutating func remove(name nameToRemove: String) {
self.headers.removeAll { header in
return nameToRemove.isEqualCaseInsensitiveASCIIBytes(to: header.name)
}
}
/// Retrieve all of the values for a given header field name from the block.
///
/// This method uses case-insensitive comparisons for the header field name. It
/// does not return a maximally-decomposed list of the header fields, but instead
/// returns them in their original representation: that means that a comma-separated
/// header field list may contain more than one entry, some of which contain commas
/// and some do not. If you want a representation of the header fields suitable for
/// performing computation on, consider `getCanonicalForm`.
///
/// - Parameter name: The header field name whose values are to be retrieved.
/// - Returns: A list of the values for that header field name.
@inlinable
public subscript(name: String) -> [String] {
guard !self.headers.isEmpty else {
return []
}
var array: [String] = []
for header in self.headers {
if header.name.isEqualCaseInsensitiveASCIIBytes(to: name) {
array.append(header.value)
}
}
return array
}
/// Retrieves the first value for a given header field name from the block.
///
/// This method uses case-insensitive comparisons for the header field name. It
/// does not return the first value from a maximally-decomposed list of the header fields,
/// but instead returns the first value from the original representation: that means
/// that a comma-separated header field list may contain more than one entry, some of
/// which contain commas and some do not. If you want a representation of the header fields
/// suitable for performing computation on, consider `getCanonicalForm`.
///
/// - Parameter name: The header field name whose first value should be retrieved.
/// - Returns: The first value for the header field name.
@inlinable
public func first(name: String) -> String? {
guard !self.headers.isEmpty else {
return nil
}
return self.headers.first { $0.name.isEqualCaseInsensitiveASCIIBytes(to: name) }?.value
}
/// Checks if a header is present.
///
/// - parameters:
/// - name: The name of the header
/// - returns: `true` if a header with the name (and value) exists, `false` otherwise.
@inlinable
public func contains(name: String) -> Bool {
guard !self.headers.isEmpty else {
return false
}
for header in self.headers {
if header.name.isEqualCaseInsensitiveASCIIBytes(to: name) {
return true
}
}
return false
}
/// Retrieves the header values for the given header field in "canonical form": that is,
/// splitting them on commas as extensively as possible such that multiple values received on the
/// one line are returned as separate entries. Also respects the fact that Set-Cookie should not
/// be split in this way.
///
/// - Parameter name: The header field name whose values are to be retrieved.
/// - Returns: A list of the values for that header field name.
@inlinable
public subscript(canonicalForm name: String) -> [String] {
let result = self[name]
guard result.count > 0 else {
return []
}
// It's not safe to split Set-Cookie on comma.
if name.isEqualCaseInsensitiveASCIIBytes(to: "set-cookie") {
return result
}
// We slightly overcommit here to try to reduce the amount of resizing we do.
var trimmedResults: [String] = []
trimmedResults.reserveCapacity(result.count * 4)
// This loop operates entirely on the UTF-8 views. This vastly reduces the cost of this slicing and dicing.
for field in result {
for entry in field.utf8._lazySplit(separator: UInt8(ascii: ",")) {
let trimmed = entry._trimWhitespace()
if trimmed.isEmpty {
continue
}
// This constructor pair kinda sucks, but you can't create a String from a slice of UTF8View as
// cheaply as you can with a Substring, so we go through that initializer instead.
trimmedResults.append(String(Substring(trimmed)))
}
}
return trimmedResults
}
/// Special internal function for use by tests.
internal subscript(position: Int) -> (String, String) {
precondition(position < self.headers.endIndex, "Position \(position) is beyond bounds of \(self.headers.endIndex)")
let header = self.headers[position]
return (header.name, header.value)
}
}
extension HPACKHeaders {
/// The total number of headers that can be contained without allocating new storage.
@inlinable
public var capacity: Int {
return self.headers.capacity
}
/// Reserves enough space to store the specified number of headers.
///
/// - Parameter minimumCapacity: The requested number of headers to store.
@inlinable
public mutating func reserveCapacity(_ minimumCapacity: Int) {
self.headers.reserveCapacity(minimumCapacity)
}
}
extension HPACKHeaders: RandomAccessCollection {
public typealias Element = (name: String, value: String, indexable: HPACKIndexing)
public struct Index: Comparable {
@usableFromInline
let _base: Array<HPACKHeaders>.Index
@inlinable
init(_base: Array<HPACKHeaders>.Index) {
self._base = _base
}
@inlinable
public static func < (lhs: Index, rhs: Index) -> Bool {
return lhs._base < rhs._base
}
}
@inlinable
public var startIndex: HPACKHeaders.Index {
return .init(_base: self.headers.startIndex)
}
@inlinable
public var endIndex: HPACKHeaders.Index {
return .init(_base: self.headers.endIndex)
}
@inlinable
public func index(before i: HPACKHeaders.Index) -> HPACKHeaders.Index {
return .init(_base: self.headers.index(before: i._base))
}
@inlinable
public func index(after i: HPACKHeaders.Index) -> HPACKHeaders.Index {
return .init(_base: self.headers.index(after: i._base))
}
@inlinable
public subscript(position: HPACKHeaders.Index) -> Element {
let element = self.headers[position._base]
return (name: element.name, value: element.value, indexable: element.indexing)
}
// Why are we providing an `Iterator` when we could just use the default one?
// The answer is that we changed from Sequence to RandomAccessCollection in a SemVer minor release. The
// previous code had a special-case Iterator, and so to avoid breaking that abstraction we need to provide one
// here too. Happily, however, we can simply delegate to the underlying Iterator type.
/// An iterator of HTTP header fields.
///
/// This iterator will return each value for a given header name separately. That
/// means that `name` is not guaranteed to be unique in a given block of headers.
public struct Iterator: IteratorProtocol {
@usableFromInline
var _base: Array<HPACKHeader>.Iterator
@inlinable
init(_ base: HPACKHeaders) {
self._base = base.headers.makeIterator()
}
@inlinable
public mutating func next() -> Element? {
guard let element = self._base.next() else {
return nil
}
return (name: element.name, value: element.value, indexable: element.indexing)
}
}
@inlinable
public func makeIterator() -> HPACKHeaders.Iterator {
return Iterator(self)
}
}
extension HPACKHeaders: CustomStringConvertible {
public var description: String {
var headersArray: [(HPACKIndexing, String, String)] = []
headersArray.reserveCapacity(self.headers.count)
for h in self.headers {
headersArray.append((h.indexing, h.name, h.value))
}
return headersArray.description
}
}
// NOTE: This is a bad definition of equatable and hashable. In particular, both order and
// indexability are ignored. We should change it, but we should be careful when we do so.
// More discussion at https://github.com/apple/swift-nio-http2/issues/342.
extension HPACKHeaders: Equatable {
@inlinable
public static func ==(lhs: HPACKHeaders, rhs: HPACKHeaders) -> Bool {
guard lhs.headers.count == rhs.headers.count else {
return false
}
let lhsNames = Set(lhs.headers.map { $0.name })
let rhsNames = Set(rhs.headers.map { $0.name })
guard lhsNames == rhsNames else {
return false
}
for name in lhsNames {
guard lhs[name].sorted() == rhs[name].sorted() else {
return false
}
}
return true
}
}
extension HPACKHeaders: Hashable {
@inlinable
public func hash(into hasher: inout Hasher) {
// Discriminator, to indicate that this is a collection. This improves the performance
// of Sets and Dictionaries that include collections of HPACKHeaders by reducing hash collisions.
hasher.combine(self.count)
// This emulates the logic used in equatability, but we sort it to ensure that
// we hash equivalently.
let names = Set(self.headers.lazy.map { $0.name }).sorted()
for name in names {
hasher.combine(self[name].sorted())
}
}
}
/// Defines the types of indexing and rewriting operations a decoder may take with
/// regard to this header.
public enum HPACKIndexing: CustomStringConvertible, Sendable {
/// Header may be written into the dynamic index table or may be rewritten by
/// proxy servers.
case indexable
/// Header is not written to the dynamic index table, but proxies may rewrite
/// it en-route, as long as they preserve its non-indexable attribute.
case nonIndexable
/// Header may not be written to the dynamic index table, and proxies must
/// pass it on as-is without rewriting.
case neverIndexed
public var description: String {
switch self {
case .indexable:
return "[]"
case .nonIndexable:
return "[non-indexable]"
case .neverIndexed:
return "[neverIndexed]"
}
}
}
@usableFromInline
internal struct HPACKHeader: Sendable {
@usableFromInline
var indexing: HPACKIndexing
@usableFromInline
var name: String
@usableFromInline
var value: String
@inlinable
internal init(name: String, value: String, indexing: HPACKIndexing = .indexable) {
self.indexing = indexing
self.name = name
self.value = value
}
}
extension HPACKHeader {
@inlinable
internal var size: Int {
// RFC 7541 § 4.1:
//
// The size of an entry is the sum of its name's length in octets (as defined in
// Section 5.2), its value's length in octets, and 32.
//
// The size of an entry is calculated using the length of its name and value
// without any Huffman encoding applied.
return name.utf8.count + value.utf8.count + 32
}
}
internal extension UInt8 {
@inlinable
var isASCII: Bool {
return self <= 127
}
}
/* private but inlinable */
internal extension UTF8.CodeUnit {
@inlinable
var isASCIIWhitespace: Bool {
switch self {
case UInt8(ascii: " "),
UInt8(ascii: "\t"):
return true
default:
return false
}
}
}
extension Substring.UTF8View {
@inlinable
func _trimWhitespace() -> Substring.UTF8View {
guard let firstNonWhitespace = self.firstIndex(where: { !$0.isASCIIWhitespace }) else {
// The whole substring is ASCII whitespace.
return Substring().utf8
}
// There must be at least one non-ascii whitespace character, so banging here is safe.
let lastNonWhitespace = self.lastIndex(where: { !$0.isASCIIWhitespace })!
return self[firstNonWhitespace...lastNonWhitespace]
}
}
extension String.UTF8View {
@inlinable
func _lazySplit(separator: UTF8.CodeUnit) -> LazyUTF8ViewSplitSequence {
return LazyUTF8ViewSplitSequence(self, separator: separator)
}
@usableFromInline
struct LazyUTF8ViewSplitSequence: Sequence {
@usableFromInline typealias Element = Substring.UTF8View
@usableFromInline var _baseView: String.UTF8View
@usableFromInline var _separator: UTF8.CodeUnit
@inlinable
init(_ baseView: String.UTF8View, separator: UTF8.CodeUnit) {
self._baseView = baseView
self._separator = separator
}
@inlinable
func makeIterator() -> Iterator {
return Iterator(self)
}
@usableFromInline
struct Iterator: IteratorProtocol {
@usableFromInline var _base: LazyUTF8ViewSplitSequence
@usableFromInline var _lastSplitIndex: Substring.UTF8View.Index
@inlinable
init(_ base: LazyUTF8ViewSplitSequence) {
self._base = base
self._lastSplitIndex = base._baseView.startIndex
}
@inlinable
mutating func next() -> Substring.UTF8View? {
let endIndex = self._base._baseView.endIndex
guard self._lastSplitIndex != endIndex else {
return nil
}
let restSlice = self._base._baseView[self._lastSplitIndex...]
if let nextSplitIndex = restSlice.firstIndex(of: self._base._separator) {
// The separator is present. We want to drop the separator, so we need to advance the index past this point.
self._lastSplitIndex = self._base._baseView.index(after: nextSplitIndex)
return restSlice[..<nextSplitIndex]
} else {
// The separator isn't present, so we want the entire rest of the slice.
self._lastSplitIndex = self._base._baseView.endIndex
return restSlice
}
}
}
}
}
extension String.UTF8View {
/// Compares two UTF8 strings as case insensitive ASCII bytes.
///
/// - Parameter bytes: The string constant in the form of a collection of `UInt8`
/// - Returns: Whether the collection contains **EXACTLY** this array or no, but by ignoring case.
@inlinable
func compareCaseInsensitiveASCIIBytes(to other: String.UTF8View) -> Bool {
// fast path: we can get the underlying bytes of both
let maybeMaybeResult = self.withContiguousStorageIfAvailable { lhsBuffer -> Bool? in
other.withContiguousStorageIfAvailable { rhsBuffer in
if lhsBuffer.count != rhsBuffer.count {
return false
}
for idx in 0 ..< lhsBuffer.count {
// let's hope this gets vectorised ;)
if lhsBuffer[idx] & 0xdf != rhsBuffer[idx] & 0xdf && lhsBuffer[idx].isASCII {
return false
}
}
return true
}
}
if let maybeResult = maybeMaybeResult, let result = maybeResult {
return result
} else {
return self._compareCaseInsensitiveASCIIBytesSlowPath(to: other)
}
}
@inlinable
@inline(never)
func _compareCaseInsensitiveASCIIBytesSlowPath(to other: String.UTF8View) -> Bool {
return self.elementsEqual(other, by: { return (($0 & 0xdf) == ($1 & 0xdf) && $0.isASCII) })
}
}
extension String {
@inlinable
internal func isEqualCaseInsensitiveASCIIBytes(to: String) -> Bool {
return self.utf8.compareCaseInsensitiveASCIIBytes(to: to.utf8)
}
}
| apache-2.0 |
DimaKorol/CollectionViewAdapter | CollectionViewAdapter/DelegeteCellManager+CollectionViewDelegates.swift | 1 | 15555 | //
// DefaultCollectionViewDelegate.swift
// CollectionViewAdapter
//
// Created by dimakorol on 4/6/16.
// Copyright © 2016 dimakorol. All rights reserved.
//
import UIKit
extension DelegateCellManager: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return getCount()
}
public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
guard let (cellData, cellBinder) = getAllForIndex(indexPath.row) else {
if let cell = ownDataSourceDelegate?.collectionView(collectionView, cellForItemAtIndexPath: indexPath){
return cell
}
return UICollectionViewCell()
}
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellBinder.cellId, forIndexPath: indexPath)
bindData(cell, cellBinder: cellBinder, data: cellData.data)
return cell
}
public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int{
if let numberOfSections = ownDataSourceDelegate?.numberOfSectionsInCollectionView?(collectionView){
return numberOfSections
}
return 1
}
// // The view that is returned must be retrieved from a call to -dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath:
// public func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView{
// if let reusableView = ownDataSourceDelegate?.collectionView?(collectionView, viewForSupplementaryElementOfKind: kind, atIndexPath: indexPath){
// return reusableView
// }
// return UICollectionReusableView()
// }
@available(iOS 9.0, *)
public func collectionView(collectionView: UICollectionView, canMoveItemAtIndexPath indexPath: NSIndexPath) -> Bool{
if let canMoveItemAtIndexPath = ownDataSourceDelegate?.collectionView?(collectionView, canMoveItemAtIndexPath: indexPath){
return canMoveItemAtIndexPath
}
return false
}
@available(iOS 9.0, *)
public func collectionView(collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath){
ownDataSourceDelegate?.collectionView?(collectionView, moveItemAtIndexPath: sourceIndexPath, toIndexPath : destinationIndexPath)
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{
guard let (cellData, cellBinder) = getAllForIndex(indexPath.row) else {
return defaultSize(collectionView, layout: collectionViewLayout, defaultSizeForItemAtIndexPath: indexPath)
}
var size : CGSize?
if let autolayout = cellBinder.cellAutoSize where autolayout{
let cell = templateCell(cellBinder)
bindData(cell, cellBinder: cellBinder, data: cellData.data)
size = cell.estimateSizeWith(cellBinder, collectionViewSize: collectionView.frame.size)
if let correctedSize = cellBinder.cellSize?(collectionView, estimatedSize: size!){
size = correctedSize
}
} else{
if let newSize = cellBinder.collectionView?(collectionView, layout: collectionViewLayout, sizeForItemAtIndexPath: indexPath){
size = newSize
}
}
guard let resultSize = size else{
return defaultSize(collectionView, layout: collectionViewLayout, defaultSizeForItemAtIndexPath: indexPath)
}
return resultSize
}
func defaultSize(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, defaultSizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{
if let size = ownViewDelegateFlowLayout?.collectionView?(collectionView, layout: collectionViewLayout, sizeForItemAtIndexPath: indexPath){
return size
}
return (collectionViewLayout as! UICollectionViewFlowLayout).itemSize
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets{
if let edge = ownViewDelegateFlowLayout?.collectionView?(collectionView, layout: collectionViewLayout, insetForSectionAtIndex: section){
return edge
}
return (collectionViewLayout as! UICollectionViewFlowLayout).sectionInset
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat{
if let minimumLineSpacing = ownViewDelegateFlowLayout?.collectionView?(collectionView, layout: collectionViewLayout, minimumLineSpacingForSectionAtIndex: section){
return minimumLineSpacing
}
return (collectionViewLayout as! UICollectionViewFlowLayout).minimumLineSpacing
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat{
if let minimumInteritemSpacing = ownViewDelegateFlowLayout?.collectionView?(collectionView, layout: collectionViewLayout, minimumInteritemSpacingForSectionAtIndex: section){
return minimumInteritemSpacing
}
return (collectionViewLayout as! UICollectionViewFlowLayout).minimumInteritemSpacing
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{
if let headerReferenceSize = ownViewDelegateFlowLayout?.collectionView?(collectionView, layout: collectionViewLayout, referenceSizeForHeaderInSection: section){
return headerReferenceSize
}
return (collectionViewLayout as! UICollectionViewFlowLayout).headerReferenceSize
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize{
if let footerReferenceSize = ownViewDelegateFlowLayout?.collectionView?(collectionView, layout: collectionViewLayout, referenceSizeForFooterInSection: section){
return footerReferenceSize
}
return (collectionViewLayout as! UICollectionViewFlowLayout).footerReferenceSize
}
public func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool{
guard let cellBinder = getAllForIndex(indexPath.row)?.1,
shouldHighlightItemAtIndexPath = cellBinder.collectionView?(collectionView, shouldHighlightItemAtIndexPath: indexPath) else {
if let shouldHighlightItemAtIndexPath = ownViewDelegateFlowLayout?.collectionView?(collectionView, shouldHighlightItemAtIndexPath: indexPath){
return shouldHighlightItemAtIndexPath
}
return true
}
return shouldHighlightItemAtIndexPath
}
public func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath){
ownViewDelegateFlowLayout?.collectionView?(collectionView, didHighlightItemAtIndexPath: indexPath)
if let cellBinder = getAllForIndex(indexPath.row)?.1 {
cellBinder.collectionView?(collectionView, didHighlightItemAtIndexPath: indexPath)
}
}
public func collectionView(collectionView: UICollectionView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath){
ownViewDelegateFlowLayout?.collectionView?(collectionView, didUnhighlightItemAtIndexPath: indexPath)
if let cellBinder = getAllForIndex(indexPath.row)?.1 {
cellBinder.collectionView?(collectionView, didUnhighlightItemAtIndexPath: indexPath)
}
}
public func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool{
guard let cellBinder = getAllForIndex(indexPath.row)?.1,
shouldSelectItemAtIndexPath = cellBinder.collectionView?(collectionView, shouldSelectItemAtIndexPath: indexPath) else {
if let shouldSelectItemAtIndexPath = ownViewDelegateFlowLayout?.collectionView?(collectionView, shouldSelectItemAtIndexPath: indexPath){
return shouldSelectItemAtIndexPath
}
return true
}
return shouldSelectItemAtIndexPath
}
public func collectionView(collectionView: UICollectionView, shouldDeselectItemAtIndexPath indexPath: NSIndexPath) -> Bool{
guard let cellBinder = getAllForIndex(indexPath.row)?.1,
shouldDeselectItemAtIndexPath = cellBinder.collectionView?(collectionView, shouldSelectItemAtIndexPath: indexPath) else {
if let shouldDeselectItemAtIndexPath = ownViewDelegateFlowLayout?.collectionView?(collectionView, shouldSelectItemAtIndexPath: indexPath){
return shouldDeselectItemAtIndexPath
}
return true
}
return shouldDeselectItemAtIndexPath
}// called when the user taps on an already-selected item in multi-select mode
public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){
ownViewDelegateFlowLayout?.collectionView?(collectionView, didSelectItemAtIndexPath: indexPath)
if let cellBinder = getAllForIndex(indexPath.row)?.1 {
cellBinder.collectionView?(collectionView, didSelectItemAtIndexPath: indexPath)
}
}
public func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath){
ownViewDelegateFlowLayout?.collectionView?(collectionView, didDeselectItemAtIndexPath: indexPath)
if let cellBinder = getAllForIndex(indexPath.row)?.1 {
cellBinder.collectionView?(collectionView, didDeselectItemAtIndexPath: indexPath)
}
}
public func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath){
ownViewDelegateFlowLayout?.collectionView?(collectionView, willDisplayCell: cell, forItemAtIndexPath: indexPath)
if let cellBinder = getAllForIndex(indexPath.row)?.1 {
cellBinder.collectionView?(collectionView, willDisplayCell: cell, forItemAtIndexPath: indexPath)
}
}
public func collectionView(collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, atIndexPath indexPath: NSIndexPath){
ownViewDelegateFlowLayout?.collectionView?(collectionView, willDisplaySupplementaryView: view, forElementKind: elementKind, atIndexPath: indexPath)
if let cellBinder = getAllForIndex(indexPath.row)?.1 {
cellBinder.collectionView?(collectionView, willDisplaySupplementaryView: view, forElementKind: elementKind, atIndexPath: indexPath)
}
}
public func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath){
ownViewDelegateFlowLayout?.collectionView?(collectionView, didEndDisplayingCell: cell, forItemAtIndexPath: indexPath)
if let cellBinder = getAllForIndex(indexPath.row)?.1 {
cellBinder.collectionView?(collectionView, didEndDisplayingCell: cell, forItemAtIndexPath: indexPath)
}
}
public func collectionView(collectionView: UICollectionView, didEndDisplayingSupplementaryView view: UICollectionReusableView, forElementOfKind elementKind: String, atIndexPath indexPath: NSIndexPath){
ownViewDelegateFlowLayout?.collectionView?(collectionView, didEndDisplayingSupplementaryView: view, forElementOfKind: elementKind, atIndexPath: indexPath)
if let cellBinder = getAllForIndex(indexPath.row)?.1 {
cellBinder.collectionView?(collectionView, didEndDisplayingSupplementaryView: view, forElementOfKind: elementKind, atIndexPath: indexPath)
}
}
// These methods provide support for copy/paste actions on cells.
// All three should be implemented if any are.
public func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool{
guard let cellBinder = getAllForIndex(indexPath.row)?.1,
shouldShowMenuForItemAtIndexPath = cellBinder.collectionView?(collectionView, shouldShowMenuForItemAtIndexPath: indexPath) else {
if let shouldShowMenuForItemAtIndexPath = ownViewDelegateFlowLayout?.collectionView?(collectionView, shouldShowMenuForItemAtIndexPath: indexPath){
return shouldShowMenuForItemAtIndexPath
}
return false
}
return shouldShowMenuForItemAtIndexPath
}
public func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool{
guard let cellBinder = getAllForIndex(indexPath.row)?.1,
canPerformAction = cellBinder.collectionView?(collectionView, canPerformAction:action, forItemAtIndexPath: indexPath, withSender: sender) else {
if let canPerformAction = ownViewDelegateFlowLayout?.collectionView?(collectionView, canPerformAction:action, forItemAtIndexPath: indexPath, withSender: sender){
return canPerformAction
}
return false
}
return canPerformAction
}
public func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?){
ownViewDelegateFlowLayout?.collectionView?(collectionView, performAction: action, forItemAtIndexPath: indexPath, withSender: sender)
if let cellBinder = getAllForIndex(indexPath.row)?.1 {
cellBinder.collectionView?(collectionView, performAction: action, forItemAtIndexPath: indexPath, withSender: sender)
}
}
// Focus
@available(iOS 9.0, *)
public func collectionView(collectionView: UICollectionView, canFocusItemAtIndexPath indexPath: NSIndexPath) -> Bool{
guard let cellBinder = getAllForIndex(indexPath.row)?.1,
canFocusItemAtIndexPath = cellBinder.collectionView?(collectionView, canFocusItemAtIndexPath: indexPath) else {
if let canFocusItemAtIndexPath = ownViewDelegateFlowLayout?.collectionView?(collectionView, canFocusItemAtIndexPath: indexPath){
return canFocusItemAtIndexPath
}
return true
}
return canFocusItemAtIndexPath
}
}
| mit |
lemberg/obd2-swift-lib | OBD2-Swift/Classes/Parser/Descriptor01.swift | 1 | 7673 | //
// Descriptor.swift
// OBD2Swift
//
// Created by Max Vitruk on 5/25/17.
// Copyright © 2017 Lemberg. All rights reserved.
//
import Foundation
public class Mode01Descriptor : DescriptorProtocol {
public var response : Response
var descriptor : SensorDescriptor
required public init(describe response : Response) {
self.response = response
let pid = response.pid
self.mode = response.mode
guard pid >= 0x0 && pid <= 0x4E else {
assertionFailure("Unsuported pid group")
self.descriptor = SensorDescriptorTable[0]
return
}
self.descriptor = SensorDescriptorTable[Int(pid)]
}
public var mode : Mode
public var pid : UInt8 {
return response.pid
}
public var valueMetrics : Float? {
guard let data = response.data else {return nil}
guard !isAsciiEncoded else {return nil}
guard let exec = descriptor.calcFunction else {return nil}
return exec(data)
}
public var valueImperial : Float? {
guard let value = valueMetrics else {return nil}
guard let exec = descriptor.convertFunction else {return nil}
return exec(value)
}
public var unitsImperial : Float? {
guard let value = valueMetrics else {return nil}
guard let exec = descriptor.convertFunction else {return nil}
return exec(value)
}
public var asciValue : String? {
guard let data = response.data else {return nil}
guard isAsciiEncoded else {return nil}
return calculateStringForData(data: data)
}
public var description : String {
return descriptor.description
}
public var shortDescription :String {
return descriptor.shortDescription
}
public var unitImperial : String {
return descriptor.imperialUnit
}
public var unitMetric : String {
return descriptor.metricUnit
}
public var isAsciiEncoded : Bool {
return IS_ALPHA_VALUE(pid: pid)
}
public func stringRepresentation(metric : Bool, rounded : Bool = false) -> String {
if isAsciiEncoded {
return asciValue ?? ""
}else{
guard let value = self.value(metric: metric) else {return ""}
let units = self.units(metric: metric)
if rounded {
return "\(Int.init(value)) \(units)"
}else{
return "\(value) \(units)"
}
}
}
public func units(metric : Bool) -> String {
return metric ? descriptor.metricUnit : descriptor.imperialUnit
}
public func value(metric : Bool) -> Float? {
return metric ? valueMetrics : valueImperial
}
public func minValue(metric : Bool) -> Int {
if isAsciiEncoded {
return Int.min
}
return metric ? descriptor.minMetricValue : descriptor.minImperialValue
}
public func maxValue(metric : Bool) -> Int {
if isAsciiEncoded {
return Int.max
}
return metric ? descriptor.maxMetricValue : descriptor.maxImperialValue
}
//TODO: - Add multidescriptor to descriptor tables
// public func isMultiValue() -> Bool {
// return IS_MULTI_VALUE_SENSOR(pid: pid)
// }
//MARK: - String Calculation Methods
private func calculateStringForData(data : Data) -> String? {
switch pid {
case 0x03:
return calculateFuelSystemStatus(data)
case 0x12:
return calculateSecondaryAirStatus(data)
case 0x13:
return calculateOxygenSensorsPresent(data)
case 0x1C:
return calculateDesignRequirements(data)
case 0x1D:
return "" //TODO: pid 29 - Oxygen Sensor
case 0x1E:
return calculateAuxiliaryInputStatus(data)
default:
return nil
}
}
private func calculateAuxiliaryInputStatus(_ data : Data) -> String? {
var dataA = data[0]
dataA = dataA & ~0x7F // only bit 0 is valid
if dataA & 0x01 != 0 {
return "PTO_STATE: ON"
}else if dataA & 0x02 != 0 {
return "PTO_STATE: OFF"
}else {
return nil
}
}
private func calculateDesignRequirements(_ data : Data) -> String? {
var returnString : String?
let dataA = data[0]
switch dataA {
case 0x01:
returnString = "OBD II"
break
case 0x02:
returnString = "OBD"
break
case 0x03:
returnString = "OBD I and OBD II"
break
case 0x04:
returnString = "OBD I"
break
case 0x05:
returnString = "NO OBD"
break
case 0x06:
returnString = "EOBD"
break
case 0x07:
returnString = "EOBD and OBD II"
break
case 0x08:
returnString = "EOBD and OBD"
break
case 0x09:
returnString = "EOBD, OBD and OBD II"
break
case 0x0A:
returnString = "JOBD";
break
case 0x0B:
returnString = "JOBD and OBD II"
break
case 0x0C:
returnString = "JOBD and EOBD"
break
case 0x0D:
returnString = "JOBD, EOBD, and OBD II"
break
default:
returnString = "N/A"
break
}
return returnString
}
private func calculateOxygenSensorsPresent(_ data : Data) -> String {
var returnString : String = ""
let dataA = data[0]
if dataA & 0x01 != 0 {
returnString = "O2S11"
}
if dataA & 0x02 != 0 {
returnString = "\(returnString), O2S12"
}
if dataA & 0x04 != 0 {
returnString = "\(returnString), O2S13"
}
if dataA & 0x08 != 0 {
returnString = "\(returnString), O2S14"
}
if dataA & 0x10 != 0 {
returnString = "\(returnString), O2S21"
}
if dataA & 0x20 != 0 {
returnString = "\(returnString), O2S22"
}
if dataA & 0x40 != 0 {
returnString = "\(returnString), O2S23"
}
if dataA & 0x80 != 0 {
returnString = "\(returnString), O2S24"
}
return returnString
}
private func calculateOxygenSensorsPresentB(_ data : Data) -> String {
var returnString : String = ""
let dataA = data[0]
if(dataA & 0x01 != 0){
returnString = "O2S11"
}
if dataA & 0x02 != 0 {
returnString = "\(returnString), O2S12"
}
if dataA & 0x04 != 0 {
returnString = "\(returnString), O2S21"
}
if(dataA & 0x08 != 0) {
returnString = "\(returnString), O2S22"
}
if dataA & 0x10 != 0 {
returnString = "\(returnString), O2S31"
}
if dataA & 0x20 != 0 {
returnString = "\(returnString), O2S32"
}
if dataA & 0x40 != 0 {
returnString = "\(returnString), O2S41"
}
if dataA & 0x80 != 0 {
returnString = "\(returnString), O2S42"
}
return returnString
}
private func calculateFuelSystemStatus(_ data : Data) -> String {
var rvString : String = ""
let dataA = data[0]
switch dataA {
case 0x01:
rvString = "Open Loop"
break
case 0x02:
rvString = "Closed Loop"
break
case 0x04:
rvString = "OL-Drive"
break;
case 0x08:
rvString = "OL-Fault"
break
case 0x10:
rvString = "CL-Fault"
break
default:
break
}
return rvString
}
private func calculateSecondaryAirStatus(_ data : Data) -> String {
var rvString : String = ""
let dataA = data[0]
switch dataA {
case 0x01:
rvString = "AIR_STAT: UPS"
break
case 0x02:
rvString = "AIR_STAT: DNS"
break
case 0x04:
rvString = "AIR_STAT: OFF"
break
default:
break
}
return rvString
}
}
| mit |
akolov/FlingChallenge | FlingChallenge/FlingChallenge/CircularProgressIndicator.swift | 1 | 1965 | //
// CircularProgressIndicator.swift
// FlingChallenge
//
// Created by Alexander Kolov on 9/5/16.
// Copyright © 2016 Alexander Kolov. All rights reserved.
//
import UIKit
@IBDesignable
class CircularProgressIndicator: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
var progress: Float = 0 {
didSet {
shapeLayer.path = path.CGPath
if progress >= 1.0 && hideWhenFinished {
hidden = true
}
}
}
@IBInspectable
var hideWhenFinished: Bool = true
private func initialize() {
backgroundShapeLayer.fillColor = nil
backgroundShapeLayer.strokeColor = UIColor(white: 0, alpha: 0.5).CGColor
backgroundShapeLayer.lineWidth = 10
backgroundShapeLayer.addSublayer(shapeLayer)
}
override func layoutSubviews() {
super.layoutSubviews()
backgroundShapeLayer.path = UIBezierPath(ovalInRect: bounds).CGPath
}
override class func layerClass() -> AnyClass {
return CAShapeLayer.self
}
var backgroundShapeLayer: CAShapeLayer {
return layer as! CAShapeLayer
}
private(set) lazy var shapeLayer: CAShapeLayer = {
let layer = CAShapeLayer()
layer.fillColor = nil
layer.strokeColor = UIColor.whiteColor().CGColor
layer.lineWidth = 10
return layer
}()
override func intrinsicContentSize() -> CGSize {
return CGSize(width: 60, height: 60)
}
private var path: UIBezierPath {
let start = M_PI * 1.5
let end = start + M_PI * 2.0
let center = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
let radius = bounds.width / 2
let startAngle = CGFloat(start)
let endAngle = CGFloat(Float(end - start) * progress) + startAngle
let path = UIBezierPath()
path.addArcWithCenter(center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
return path
}
}
| mit |
hooman/swift | test/Concurrency/Runtime/async_task_cancellation_early.swift | 2 | 1231 | // RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking %import-libdispatch -parse-as-library) | %FileCheck %s --dump-input=always
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: libdispatch
// Temporarily disabled to unblock PR testing:
// REQUIRES: rdar80745964
// rdar://76038845
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime
import Dispatch
@available(SwiftStdlib 5.5, *)
func test_detach_cancel_child_early() async {
print(#function) // CHECK: test_detach_cancel_child_early
let h: Task<Bool, Error> = Task.detached {
async let childCancelled: Bool = { () -> Bool in
await Task.sleep(2_000_000_000)
return Task.isCancelled
}()
let xx = await childCancelled
print("child, cancelled: \(xx)") // CHECK: child, cancelled: true
let cancelled = Task.isCancelled
print("self, cancelled: \(cancelled)") // CHECK: self, cancelled: true
return cancelled
}
h.cancel()
print("handle cancel")
let got = try! await h.value
print("was cancelled: \(got)") // CHECK: was cancelled: true
}
@available(SwiftStdlib 5.5, *)
@main struct Main {
static func main() async {
await test_detach_cancel_child_early()
}
}
| apache-2.0 |
AndrewBennet/readinglist | ReadingList_UnitTests/ProprietaryURLManager.swift | 1 | 1062 | import XCTest
import Foundation
@testable import ReadingList
class ProprietaryURLManagerTests: XCTestCase {
let urlManager = ProprietaryURLManager()
override func setUp() {
super.setUp()
}
func testUrlToAction() {
performRoundTripTestFromURL(url: "readinglist://book/view?gbid=123456789", expectedAction: .viewBook(id: .googleBooksId("123456789")))
performRoundTripTestFromURL(url: "readinglist://book/view?mid=abcdef", expectedAction: .viewBook(id: .manualId("abcdef")))
performRoundTripTestFromURL(url: "readinglist://book/view?isbn=9780684833392", expectedAction: .viewBook(id: .isbn("9780684833392")))
}
func performRoundTripTestFromURL(url urlString: String, expectedAction: ProprietaryURLAction) {
let url = URL(string: urlString)!
let action = urlManager.getAction(from: url)
XCTAssertNotNil(action)
XCTAssertEqual(action, expectedAction)
let roundTripActionURL = urlManager.getURL(from: action!)
XCTAssertEqual(roundTripActionURL, url)
}
}
| gpl-3.0 |
vector-im/vector-ios | RiotSwiftUI/Modules/Template/TemplateAdvancedRoomsExample/TemplateRoomChat/TemplateRoomChatModels.swift | 1 | 3209 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
// MARK: - Coordinator
/// An image sent as a message.
struct TemplateRoomChatMessageImageContent: Equatable {
var image: UIImage
}
/// The text content of a message sent by a user.
struct TemplateRoomChatMessageTextContent: Equatable {
var body: String
}
/// The type of message a long with it's content.
enum TemplateRoomChatMessageContent: Equatable {
case text(TemplateRoomChatMessageTextContent)
case image(TemplateRoomChatMessageImageContent)
}
enum TemplateRoomChatBubbleItemContent: Equatable {
case message(TemplateRoomChatMessageContent)
}
/// One of the items grouped within a bubble(could be message types like text, image or video, or could be other items like url previews).
struct TemplateRoomChatBubbleItem: Identifiable, Equatable {
let id: String
var timestamp: Date
var content: TemplateRoomChatBubbleItemContent
}
/// A user who is a member of the room.
struct TemplateRoomChatMember: Identifiable, Equatable, Avatarable {
let id: String
let avatarUrl: String?
let displayName: String?
var mxContentUri: String? {
avatarUrl
}
var matrixItemId: String {
id
}
}
/// Represents a grouped bubble in the View(For example multiple message of different time sent close together).
struct TemplateRoomChatBubble: Identifiable, Equatable {
let id: String
let sender: TemplateRoomChatMember
var items: [TemplateRoomChatBubbleItem]
}
/// A chat message send to the timeline within a room.
struct TemplateRoomChatMessage: Identifiable {
let id: String
let content: TemplateRoomChatMessageContent
let sender: TemplateRoomChatMember
let timestamp: Date
}
// MARK: - View model
enum TemplateRoomChatRoomInitializationStatus {
case notInitialized
case initialized
case failedToInitialize
}
/// Actions sent by the `ViewModel` to the `Coordinator`
enum TemplateRoomChatViewModelAction {
case done
}
// MARK: - View
/// Actions send from the `View` to the `ViewModel`.
enum TemplateRoomChatViewAction {
case sendMessage
case done
}
/// State managed by the `ViewModel` delivered to the `View`.
struct TemplateRoomChatViewState: BindableState {
var roomInitializationStatus: TemplateRoomChatRoomInitializationStatus
let roomName: String?
var bubbles: [TemplateRoomChatBubble]
var bindings: TemplateRoomChatViewModelBindings
var sendButtonEnabled: Bool {
!bindings.messageInput.isEmpty
}
}
/// State bound directly to SwiftUI elements.
struct TemplateRoomChatViewModelBindings {
var messageInput: String
}
| apache-2.0 |
wltrup/Swift-WTCoreGraphicsExtensions | Example/Tests/WTCoreGraphicsExtensionsTestsBase.swift | 1 | 2652 | //
// WTCoreGraphicsExtensionsTestsBase.swift
// WTCoreGraphicsExtensions
//
// Created by Wagner Truppel on 2016.12.03.
//
// Copyright (c) 2016 Wagner Truppel. All rights reserved.
//
import XCTest
import Foundation
import WTCoreGraphicsExtensions
class WTCoreGraphicsExtensionsTestsBase: XCTestCase
{
var tolerance: CGFloat = 0
var N: Int = 0
var rangeMin: CGFloat = 0
var rangeMax: CGFloat = 0
// MARK: -
var expectedValue: CGFloat = 0
var resultedValue: CGFloat = 0
var expectedPoint = CGPoint.zero
var resultedPoint = CGPoint.zero
var expectedVector = CGVector.zero
var resultedVector = CGVector.zero
var expectedError: WTCoreGraphicsExtensionsError!
var resultedError: Error!
// MARK: -
final func assertAbsoluteDifferenceWithinTolerance()
{ XCTAssertTrue(abs(resultedValue - expectedValue) <= tolerance) }
/// Tests that uniformly generated pseudo-random values in the range [0, 1]
/// satisfy the properties that their average approaches 1/2 and their
/// variance approaches 1/12.
final func testRandomness(_ values: [CGFloat])
{
let n = CGFloat(values.count)
let average = values.reduce(0, +) / n
let variance = values
.map { ($0 - average)*($0 - average) }
.reduce(0, +) / n
expectedValue = 1.0/2.0
resultedValue = average
assertAbsoluteDifferenceWithinTolerance()
expectedValue = 1.0/12.0
resultedValue = variance
assertAbsoluteDifferenceWithinTolerance()
}
final func assertEqualPointsWithinTolerance()
{
expectedValue = expectedPoint.x
resultedValue = resultedPoint.x
assertAbsoluteDifferenceWithinTolerance()
expectedValue = expectedPoint.y
resultedValue = resultedPoint.y
assertAbsoluteDifferenceWithinTolerance()
}
final func assertEqualVectorsWithinTolerance()
{
expectedValue = expectedVector.dx
resultedValue = resultedVector.dx
assertAbsoluteDifferenceWithinTolerance()
expectedValue = expectedVector.dy
resultedValue = resultedVector.dy
assertAbsoluteDifferenceWithinTolerance()
}
final func assertEqualErrors()
{
XCTAssertTrue(resultedError is WTCoreGraphicsExtensionsError)
if let resultedError = resultedError as? WTCoreGraphicsExtensionsError
{ XCTAssertEqual(resultedError, expectedError) }
}
// MARK: -
override func setUp()
{
super.setUp()
tolerance = 1e-10
N = 100
rangeMin = -10
rangeMax = 10
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.