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 |
---|---|---|---|---|---|
bootstraponline/elements_of_interest | swift/elements_of_interest/elements_of_interest/elements.swift | 1 | 1627 | import Foundation
import XCTest
class Elements {
static func getResource(name: String, ofType: String) -> String {
let bundle = NSBundle(forClass: self)
let path = bundle.pathForResource(name, ofType: ofType)!
return path
}
static func getSnapshot() -> XCElementSnapshot {
// Must dynamically locate the bundle because main bundle isn't available in testing target
let path = getResource("elements", ofType: "plist")
let object = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as! NSArray
let snapshot = object.firstObject as! XCElementSnapshot
return snapshot
}
static func getSnapshotFromFile(path: String) -> XCElementSnapshot? {
// Could not cast value of type 'XCElementSnapshot' (0x101625238) to 'NSArray' (0x7fff7c5ee5f0).
let object = NSKeyedUnarchiver.unarchiveObjectWithFile(path)
// /Test/Attachments/Snapshot_ is always XCElementSnapshot
// /Test/Attachments/ElementsOfInterest_ is always NSArray
if object!.dynamicType == XCElementSnapshot.self {
return object as? XCElementSnapshot
} else {
let firstObject = (object as! NSArray).firstObject
if firstObject == nil { // sometimes the snapshot is nil :(
return nil
}
return firstObject as? XCElementSnapshot
}
}
static func getDesc() -> String {
let path = getResource("desc", ofType: "txt")
let url = NSURL(fileURLWithPath: path)
return try! String(contentsOfURL: url, encoding: NSUTF8StringEncoding)
}
}
| apache-2.0 |
podverse/podverse-ios | Podverse/FiltersTableHeaderView.swift | 1 | 13097 | //
// FiltersTableHeaderView.swift
// Podverse
//
// Created by Creon Creonopoulos on 10/3/17.
// Copyright © 2017 Podverse LLC. All rights reserved.
//
import UIKit
protocol FilterSelectionProtocol {
func filterButtonTapped()
func sortingButtonTapped()
func sortByRecent()
func sortByTop()
func sortByTopWithTimeRange(timeRange: SortingTimeRange)
}
class FiltersTableHeaderView: UIView {
var delegate:FilterSelectionProtocol?
var filterTitle = "" {
didSet {
DispatchQueue.main.async {
self.filterButton.setTitle(self.filterTitle + kDropdownCaret, for: .normal)
}
}
}
var sortingTitle = "" {
didSet {
DispatchQueue.main.async {
self.sortingButton.setTitle(self.sortingTitle + kDropdownCaret, for: .normal)
}
}
}
let filterButton = UIButton()
let sortingButton = UIButton()
let topBorder = UIView()
let bottomBorder = UIView()
func setupViews(isBlackBg: Bool = false) {
let titleColor:UIColor = isBlackBg ? .white : .black
let borderColor:UIColor = isBlackBg ? .darkGray : .lightGray
self.translatesAutoresizingMaskIntoConstraints = false
self.filterButton.translatesAutoresizingMaskIntoConstraints = false
self.sortingButton.translatesAutoresizingMaskIntoConstraints = false
self.topBorder.translatesAutoresizingMaskIntoConstraints = false
self.bottomBorder.translatesAutoresizingMaskIntoConstraints = false
self.filterButton.setTitle(filterTitle, for: .normal)
self.filterButton.setTitleColor(titleColor, for: .normal)
self.filterButton.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.semibold)
self.filterButton.contentHorizontalAlignment = .left
self.filterButton.addTarget(self, action: #selector(FiltersTableHeaderView.filterButtonTapped), for: .touchUpInside)
self.addSubview(filterButton)
let filterLeading = NSLayoutConstraint(item: self.filterButton,
attribute: .leading,
relatedBy: .equal,
toItem: self,
attribute: .leading,
multiplier: 1,
constant: 12)
let filterTop = NSLayoutConstraint(item: self.filterButton,
attribute: .top,
relatedBy: .equal,
toItem: self,
attribute: .top,
multiplier: 1,
constant: 0)
let filterHeight = NSLayoutConstraint(item: self.filterButton,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 44)
let filterWidth = NSLayoutConstraint(item: self.filterButton,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 140)
self.sortingButton.setTitle(sortingTitle, for: .normal)
self.sortingButton.setTitleColor(titleColor, for: .normal)
self.sortingButton.titleLabel?.font = UIFont.systemFont(ofSize: 16)
self.sortingButton.contentHorizontalAlignment = .right
self.sortingButton.addTarget(self, action: #selector(FiltersTableHeaderView.sortingButtonTapped), for: .touchUpInside)
let sortingLeading = NSLayoutConstraint(item: self,
attribute: .trailing,
relatedBy: .equal,
toItem: self.sortingButton,
attribute: .trailing,
multiplier: 1,
constant: 12)
let sortingTop = NSLayoutConstraint(item: self.sortingButton,
attribute: .top,
relatedBy: .equal,
toItem: self,
attribute: .top,
multiplier: 1,
constant: 0)
let sortingHeight = NSLayoutConstraint(item: self.sortingButton,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 44)
let sortingWidth = NSLayoutConstraint(item: self.sortingButton,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 140)
self.addSubview(self.sortingButton)
self.topBorder.backgroundColor = borderColor
let topBorderLeading = NSLayoutConstraint(item: self.topBorder,
attribute: .leading,
relatedBy: .equal,
toItem: self,
attribute: .leading,
multiplier: 1,
constant: 0)
let topBorderTop = NSLayoutConstraint(item: self.topBorder,
attribute: .top,
relatedBy: .equal,
toItem: self,
attribute: .top,
multiplier: 1,
constant: 0)
let topBorderTrailing = NSLayoutConstraint(item: self.topBorder,
attribute: .trailing,
relatedBy: .equal,
toItem: self,
attribute: .trailing,
multiplier: 1,
constant: 0)
let topBorderHeight = NSLayoutConstraint(item: self.topBorder,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 0.5)
self.addSubview(self.topBorder)
self.bottomBorder.backgroundColor = borderColor
let bottomBorderLeading = NSLayoutConstraint(item: self.bottomBorder,
attribute: .leading,
relatedBy: .equal,
toItem: self,
attribute: .leading,
multiplier: 1,
constant: 0)
let bottomBorderBottom = NSLayoutConstraint(item: self,
attribute: .bottom,
relatedBy: .equal,
toItem: self.bottomBorder,
attribute: .bottom,
multiplier: 1,
constant: 0)
let bottomBorderTrailing = NSLayoutConstraint(item: self.bottomBorder,
attribute: .trailing,
relatedBy: .equal,
toItem: self,
attribute: .trailing,
multiplier: 1,
constant: 0)
let bottomBorderHeight = NSLayoutConstraint(item: self.bottomBorder,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 0.5)
self.addSubview(self.bottomBorder)
self.addConstraints([filterLeading, filterTop, filterHeight, filterWidth, sortingLeading, sortingTop, sortingHeight, sortingWidth, topBorderLeading, topBorderTop, topBorderTrailing, topBorderHeight, bottomBorderLeading, bottomBorderBottom, bottomBorderTrailing, bottomBorderHeight])
}
func showSortByMenu(vc: Any) {
let alert = UIAlertController(title: "Sort By", message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: SortByOptions.top.text, style: .default, handler: { action in
self.delegate?.sortByTop()
}))
alert.addAction(UIAlertAction(title: SortByOptions.recent.text, style: .default, handler: { action in
self.delegate?.sortByRecent()
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
if let vc = vc as? UIViewController {
vc.present(alert, animated: true, completion: nil)
}
}
func showSortByTimeRangeMenu(vc: Any) {
let alert = UIAlertController(title: "Time Range", message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: SortingTimeRange.day.text, style: .default, handler: { action in
self.sortByTopWithTimeRange(timeRange: .day)
}))
alert.addAction(UIAlertAction(title: SortingTimeRange.week.text, style: .default, handler: { action in
self.sortByTopWithTimeRange(timeRange: .week)
}))
alert.addAction(UIAlertAction(title: SortingTimeRange.month.text, style: .default, handler: { action in
self.sortByTopWithTimeRange(timeRange: .month)
}))
alert.addAction(UIAlertAction(title: SortingTimeRange.year.text, style: .default, handler: { action in
self.sortByTopWithTimeRange(timeRange: .year)
}))
alert.addAction(UIAlertAction(title: SortingTimeRange.allTime.text, style: .default, handler: { action in
self.sortByTopWithTimeRange(timeRange: .allTime)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
if let vc = vc as? UIViewController {
vc.present(alert, animated: true, completion: nil)
}
}
func sortByRecent() {
self.delegate?.sortByRecent()
}
func sortByTop() {
self.delegate?.sortByTop()
}
func sortByTopWithTimeRange(timeRange: SortingTimeRange) {
self.delegate?.sortByTopWithTimeRange(timeRange: timeRange)
}
@objc func filterButtonTapped() {
self.delegate?.filterButtonTapped()
}
@objc func sortingButtonTapped() {
self.delegate?.sortingButtonTapped()
}
}
| agpl-3.0 |
doctorn/hac-website | Sources/HaCWebsiteLib/NotFoundHandler.swift | 1 | 335 | import Foundation
import Kitura
public class NotFoundHandler: RouterMiddleware {
public func handle(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) {
defer {
next()
}
if response.statusCode != .OK {
try? response.send(
NotFound().node.render()
).end()
}
}
} | mit |
nuclearace/SwiftDiscord | Sources/SwiftDiscord/Guild/DiscordEmoji.swift | 1 | 2530 | // The MIT License (MIT)
// Copyright (c) 2016 Erik Little
// 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.
/// Represents an Emoji.
public struct DiscordEmoji {
// MARK: Properties
/// The snowflake id of the emoji. Nil if the emoji is a unicode emoji
public let id: EmojiID?
/// Whether this is a managed emoji.
public let managed: Bool
/// The name of the emoji or unicode representation if it's a unicode emoji.
public let name: String
/// Whether this emoji requires colons.
public let requireColons: Bool
/// An array of role snowflake ids this emoji is active for.
public let roles: [RoleID]
init(emojiObject: [String: Any]) {
id = Snowflake(emojiObject["id"] as? String)
managed = emojiObject.get("managed", or: false)
name = emojiObject.get("name", or: "")
requireColons = emojiObject.get("require_colons", or: false)
roles = (emojiObject["roles"] as? [String])?.compactMap(Snowflake.init) ?? []
}
static func emojisFromArray(_ emojiArray: [[String: Any]]) -> [EmojiID: DiscordEmoji] {
var emojis = [EmojiID: DiscordEmoji]()
for emoji in emojiArray {
let emoji = DiscordEmoji(emojiObject: emoji)
if let emojiID = emoji.id {
emojis[emojiID] = emoji
} else {
DefaultDiscordLogger.Logger.debug("EmojisFromArray used on array with non-custom emoji", type: "DiscordEmoji")
}
}
return emojis
}
}
| mit |
DragonCherry/HFSwipeView | Example/HFSwipeView/AutoSlideController.swift | 1 | 4147 | //
// AutoSlideController.swift
// HFSwipeView
//
// Created by DragonCherry on 8/29/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import HFSwipeView
import TinyLog
class AutoSlideController: UIViewController {
fileprivate let sampleCount: Int = 3
fileprivate var didSetupConstraints: Bool = false
fileprivate lazy var swipeView: HFSwipeView = {
let view = HFSwipeView.newAutoLayout()
view.isDebug = true
view.autoAlignEnabled = true
view.circulating = true
view.dataSource = self
view.delegate = self
view.pageControlHidden = true
view.currentPage = 0
view.autoAlignEnabled = true
return view
}()
fileprivate var currentView: UIView?
fileprivate var itemSize: CGSize {
return CGSize(width: 100, height: 100)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.automaticallyAdjustsScrollViewInsets = false
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(swipeView)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
swipeView.startAutoSlide(forTimeInterval: 5)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
swipeView.stopAutoSlide()
}
override func updateViewConstraints() {
if !didSetupConstraints {
swipeView.autoSetDimension(.height, toSize: itemSize.height)
swipeView.autoPinEdge(toSuperviewEdge: .leading)
swipeView.autoPinEdge(toSuperviewEdge: .trailing)
swipeView.autoAlignAxis(toSuperviewAxis: .horizontal)
didSetupConstraints = true
}
super.updateViewConstraints()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.swipeView.setBorder(0.5, color: .black)
}
func updateCellView(_ view: UIView, indexPath: IndexPath, isCurrent: Bool) {
if let label = view as? UILabel {
if isCurrent {
// old view
currentView?.backgroundColor = .white
currentView = label
currentView?.backgroundColor = .yellow
} else {
label.backgroundColor = .white
}
label.textAlignment = .center
label.text = "\(indexPath.row)"
label.setBorder(1, color: .black)
} else {
assertionFailure("failed to retrieve UILabel for index: \(indexPath.row)")
}
}
}
// MARK: - HFSwipeViewDelegate
extension AutoSlideController: HFSwipeViewDelegate {
func swipeView(_ swipeView: HFSwipeView, didFinishScrollAtIndexPath indexPath: IndexPath) {
log("HFSwipeView(\(swipeView.tag)) -> \(indexPath.row)")
}
func swipeView(_ swipeView: HFSwipeView, didSelectItemAtPath indexPath: IndexPath) {
log("HFSwipeView(\(swipeView.tag)) -> \(indexPath.row)")
}
func swipeView(_ swipeView: HFSwipeView, didChangeIndexPath indexPath: IndexPath, changedView view: UIView) {
log("HFSwipeView(\(swipeView.tag)) -> \(indexPath.row)")
}
}
// MARK: - HFSwipeViewDataSource
extension AutoSlideController: HFSwipeViewDataSource {
func swipeViewItemSize(_ swipeView: HFSwipeView) -> CGSize {
return itemSize
}
func swipeViewItemCount(_ swipeView: HFSwipeView) -> Int {
return sampleCount
}
func swipeView(_ swipeView: HFSwipeView, viewForIndexPath indexPath: IndexPath) -> UIView {
return UILabel(frame: CGRect(origin: .zero, size: itemSize))
}
func swipeView(_ swipeView: HFSwipeView, needUpdateViewForIndexPath indexPath: IndexPath, view: UIView) {
updateCellView(view, indexPath: indexPath, isCurrent: false)
}
func swipeView(_ swipeView: HFSwipeView, needUpdateCurrentViewForIndexPath indexPath: IndexPath, view: UIView) {
updateCellView(view, indexPath: indexPath, isCurrent: true)
}
}
| mit |
weiss19ja/LocalizableUI | LocalizableUIExampleTests/ExampleViewControllerTests.swift | 1 | 1097 | //
// ExampleViewControllerTests.swift
// LocalizableUIExampleTests
//
// Created by Jan Weiß on 08.12.17.
// Copyright © 2017 Jan Weiß, Philipp Weiß. All rights reserved.
//
import XCTest
import LocalizableUI
@testable import LocalizableUI_Example
private enum Constants {
static let exampleViewControllerStoryboardId = "ExampleViewController"
static let mainStoryboardName = "Main"
}
class ExampleViewControllerTests: XCTestCase {
func testLanguageChangeForCustomView() {
let mainStoryboard = UIStoryboard(name: Constants.mainStoryboardName, bundle: Bundle.main)
let exampleViewController = mainStoryboard.instantiateViewController(withIdentifier: Constants.exampleViewControllerStoryboardId) as! ExampleViewController
let window = UIApplication.shared.delegate?.window!
window?.rootViewController = exampleViewController
exampleViewController.didSelectAlertButton(UIButton(type: .system))
sleep(5)
XCTAssertNotNil(exampleViewController.presentedViewController)
}
}
| mit |
JGiola/swift-package-manager | Tests/BuildTests/XCTestManifests.swift | 1 | 2026 | #if !canImport(ObjectiveC)
import XCTest
extension BuildPlanTests {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__BuildPlanTests = [
("testBasicClangPackage", testBasicClangPackage),
("testBasicExtPackages", testBasicExtPackages),
("testBasicReleasePackage", testBasicReleasePackage),
("testBasicSwiftPackage", testBasicSwiftPackage),
("testBuildSettings", testBuildSettings),
("testClangTargets", testClangTargets),
("testCLanguageStandard", testCLanguageStandard),
("testCModule", testCModule),
("testCppModule", testCppModule),
("testDynamicProducts", testDynamicProducts),
("testExecAsDependency", testExecAsDependency),
("testExtraBuildFlags", testExtraBuildFlags),
("testIndexStore", testIndexStore),
("testNonReachableProductsAndTargets", testNonReachableProductsAndTargets),
("testPkgConfigGenericDiagnostic", testPkgConfigGenericDiagnostic),
("testPkgConfigHintDiagnostic", testPkgConfigHintDiagnostic),
("testPlatforms", testPlatforms),
("testREPLArguments", testREPLArguments),
("testSwiftCAsmMixed", testSwiftCAsmMixed),
("testSwiftCMixed", testSwiftCMixed),
("testSystemPackageBuildPlan", testSystemPackageBuildPlan),
("testTestModule", testTestModule),
("testWindowsTarget", testWindowsTarget),
]
}
extension IncrementalBuildTests {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__IncrementalBuildTests = [
("testIncrementalSingleModuleCLibraryInSources", testIncrementalSingleModuleCLibraryInSources),
]
}
public func __allTests() -> [XCTestCaseEntry] {
return [
testCase(BuildPlanTests.__allTests__BuildPlanTests),
testCase(IncrementalBuildTests.__allTests__IncrementalBuildTests),
]
}
#endif
| apache-2.0 |
bradhilton/Table | Table/UIViewController.swift | 1 | 5470 | //
// UIViewController.swift
// Table
//
// Created by Bradley Hilton on 2/16/18.
// Copyright © 2018 Brad Hilton. All rights reserved.
//
extension Optional {
mutating func pop() -> Wrapped? {
defer { self = .none }
return self
}
}
extension Sequence {
func first<U>(where hasValue: (Element) -> U?) -> U? {
for element in self {
if let value = hasValue(element) {
return value
}
}
return nil
}
}
let swizzleViewControllerMethods: () -> () = {
method_exchangeImplementations(
class_getInstanceMethod(UIViewController.self, #selector(UIViewController.swizzledViewDidLoad))!,
class_getInstanceMethod(UIViewController.self, #selector(UIViewController.viewDidLoad))!
)
method_exchangeImplementations(
class_getInstanceMethod(UIViewController.self, #selector(UIViewController.swizzledViewWillAppear))!,
class_getInstanceMethod(UIViewController.self, #selector(UIViewController.viewWillAppear))!
)
method_exchangeImplementations(
class_getInstanceMethod(UIViewController.self, #selector(UIViewController.swizzledViewDidAppear))!,
class_getInstanceMethod(UIViewController.self, #selector(UIViewController.viewDidAppear))!
)
method_exchangeImplementations(
class_getInstanceMethod(UIViewController.self, #selector(UIViewController.swizzledViewWillDisappear))!,
class_getInstanceMethod(UIViewController.self, #selector(UIViewController.viewWillDisappear))!
)
method_exchangeImplementations(
class_getInstanceMethod(UIViewController.self, #selector(UIViewController.swizzledViewDidLayoutSubviews))!,
class_getInstanceMethod(UIViewController.self, #selector(UIViewController.viewDidLayoutSubviews))!
)
return {}
}()
extension UIViewController {
public func firstSubview<T : UIView>(class: T.Type = T.self, key: AnyHashable? = nil) -> T? {
return view.firstSubview(class: T.self, key: key)
?? children.first { $0.firstSubview(class: T.self, key: key) }
}
var configureView: ((UIViewController) -> ())? {
get {
return storage[\.configureView]
}
set {
swizzleViewControllerMethods()
if viewIsVisible && storage[\.configureView] == nil {
storage[\.configureView] = newValue
newValue?(self)
} else {
storage[\.configureView] = newValue
}
}
}
var previousViewFrame: CGRect {
get {
return storage[\.previousViewFrame, default: .zero]
}
set {
storage[\.previousViewFrame] = newValue
}
}
var updateViewOnLayout: Bool {
get {
return storage[\.updateViewOnLayout, default: false]
}
set {
storage[\.updateViewOnLayout] = newValue
}
}
var updateView: ((UIViewController) -> ())? {
get {
return storage[\.updateView]
}
set {
swizzleViewControllerMethods()
if viewIsVisible {
storage[\.updateView] = updateViewOnLayout ? newValue : nil
newValue?(self)
} else {
storage[\.updateView] = newValue
}
}
}
var updateNavigationItem: ((UIViewController) -> ())? {
get {
return storage[\.updateNavigationItem]
}
set {
swizzleViewControllerMethods()
if viewIsVisible {
storage[\.updateNavigationItem] = nil
newValue?(self)
} else {
storage[\.updateNavigationItem] = newValue
}
}
}
var viewIsVisible: Bool {
return viewIfLoaded?.window != nil
}
var viewHasAppeared: Bool {
get {
return storage[\.viewHasAppeared, default: false]
}
set {
storage[\.viewHasAppeared] = newValue
}
}
@objc func swizzledViewDidLoad() {
self.swizzledViewDidLoad()
UIView.performWithoutAnimation {
configureView?(self)
if !updateViewOnLayout {
updateView.pop()?(self)
}
}
}
@objc func swizzledViewWillAppear(animated: Bool) {
self.swizzledViewWillAppear(animated: animated)
UIView.performWithoutAnimation {
if !updateViewOnLayout {
updateView.pop()?(self)
}
updateNavigationItem.pop()?(self)
}
}
@objc func swizzledViewDidLayoutSubviews() {
self.swizzledViewDidLayoutSubviews()
if updateViewOnLayout && view.frame != previousViewFrame {
if previousViewFrame == .zero {
UIView.performWithoutAnimation {
updateView?(self)
}
} else {
updateView?(self)
}
}
previousViewFrame = view.frame
}
@objc func swizzledViewDidAppear(animated: Bool) {
self.swizzledViewDidAppear(animated: animated)
viewHasAppeared = true
presentController()
}
@objc func swizzledViewWillDisappear(animated: Bool) {
self.swizzledViewWillDisappear(animated: animated)
viewHasAppeared = false
}
}
| mit |
bradhilton/Table | Table/UISplitViewController.swift | 1 | 6986 | //
// UISplitViewController.swift
// AlertBuilder
//
// Created by Bradley Hilton on 3/14/18.
//
//private class NavigationControllerDelegate : NSObject, UINavigationControllerDelegate {
//
// func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
// if let splitViewController = navigationController.splitViewController, !(viewController is UINavigationController) {
// splitViewController.state?.willPopDetail()
// }
// }
//
//}
//
//private class SplitViewControllerDelegate : NSObject, UISplitViewControllerDelegate {
//
// func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool {
// return !(splitViewController.state?.collapseDetailOntoMaster ?? false)
// }
//
// func splitViewController(_ splitViewController: UISplitViewController, separateSecondaryFrom primaryViewController: UIViewController) -> UIViewController? {
// return splitViewController.detailViewController ?? splitViewController.state?.detail.newViewController()
// }
//
//}
extension UISplitViewController {
// public struct State {
// public let master: Controller
// public let detail: Controller
// public let collapseDetailOntoMaster: Bool
// public let willPopDetail: () -> ()
// public init(master: Controller, detail: Controller, collapseDetailOntoMaster: Bool, willPopDetail: @escaping () -> ()) {
// self.master = master
// self.detail = detail
// self.collapseDetailOntoMaster = collapseDetailOntoMaster
// self.willPopDetail = willPopDetail
// }
// }
//
// public var state: State? {
// get {
// return storage[\.state]
// }
// set {
// storage[\.state] = newValue
// delegate = defaultDelegate
// guard let state = state else { return }
// let masterViewController = self.masterViewController.flatMap { viewController in
// guard viewController.type == state.master.type else { return nil }
// viewController.update = state.master.update
// return viewController
// } ?? state.master.newViewController()
// let detailViewController = self.detailViewController.flatMap { viewController in
// guard viewController.type == state.detail.type else { return nil }
// viewController.update = update
// return viewController
// } ?? state.detail.newViewController()
// switch (isCollapsed, state.collapseDetailOntoMaster) {
// case (true, true):
// if !detailIsCollapsedOntoMaster {
// viewControllers = [masterViewController]
// showDetailViewController(detailViewController, sender: nil)
// detailViewController.navigationController?.delegate = navigationControllerDelegate
// }
// case (true, false):
// if detailIsCollapsedOntoMaster {
//
// }
// viewControllers = [masterViewController]
// case (false, _):
// viewControllers = [masterViewController, detailViewController]
// }
// }
// }
//
// var masterViewController: UIViewController? {
// return viewControllers.first
// }
//
// var detailViewController: UIViewController? {
// return viewControllers.count == 2 ? viewControllers[1] : nil
// }
//
// var detailIsCollapsedOntoMaster: Bool {
// return (masterViewController as? UINavigationController)?.viewControllers.last.map { $0 is UINavigationController } ?? false
// }
//
// private var defaultDelegate: SplitViewControllerDelegate {
// return storage[\.defaultDelegate, default: SplitViewControllerDelegate()]
// }
//
// private var navigationControllerDelegate: NavigationControllerDelegate {
// return storage[\.navigationControllerDelegate, default: NavigationControllerDelegate()]
// }
}
public class SplitNavigationController : UISplitViewController, UISplitViewControllerDelegate {
public typealias State = (master: NavigationItem, detail: NavigationItem, showDetailWhenCompact: Bool)
public var state: State {
didSet {
detailNavigationController.root = state.detail
update(isCompact: traitCollection.horizontalSizeClass == .compact)
}
}
public let masterNavigationController: UINavigationController
public let detailNavigationController: UINavigationController
public init() {
state = (NavigationItem { _ in }, NavigationItem { _ in }, false)
masterNavigationController = UINavigationController()
detailNavigationController = UINavigationController()
super.init(nibName: nil, bundle: nil)
preferredDisplayMode = .allVisible
masterNavigationController.root = state.master
detailNavigationController.root = state.detail
delegate = self
}
public override func viewDidLoad() {
super.viewDidLoad()
viewControllers = [masterNavigationController, detailNavigationController]
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool {
update(isCompact: true)
return true
}
public func splitViewController(_ splitViewController: UISplitViewController, separateSecondaryFrom primaryViewController: UIViewController) -> UIViewController? {
update(isCompact: false)
return detailNavigationController
}
private var willPop: (() -> ())?
func update(isCompact: Bool) {
if isCompact, state.showDetailWhenCompact {
state.detail.willPop = state.detail.willPop ?? willPop
if !state.master.stack.contains(where: { $0 === state.detail }) {
state.master.stack.last?.next = state.detail
}
masterNavigationController.root = state.master
} else {
if let item = state.master.stack.first(where: { $0.next === state.detail }) {
willPop = state.detail.willPop.pop()
item.next = nil
}
masterNavigationController.root = state.master
// MARK: Performance equality check
if viewControllers != [masterNavigationController, detailNavigationController] {
viewControllers = [masterNavigationController, detailNavigationController]
}
}
}
}
| mit |
kickstarter/ios-ksapi | KsApi/models/lenses/UpdateLenses.swift | 1 | 4097 | import Prelude
extension Update {
public enum lens {
public static let body = Lens<Update, String?>(
view: { $0.body },
set: { Update(body: $0, commentsCount: $1.commentsCount, hasLiked: $1.hasLiked, id: $1.id,
isPublic: $1.isPublic, likesCount: $1.likesCount, projectId: $1.projectId,
publishedAt: $1.publishedAt, sequence: $1.sequence, title: $1.title, urls: $1.urls, user: $1.user,
visible: $1.visible) }
)
public static let commentsCount = Lens<Update, Int?>(
view: { $0.commentsCount },
set: { Update(body: $1.body, commentsCount: $0, hasLiked: $1.hasLiked, id: $1.id,
isPublic: $1.isPublic, likesCount: $1.likesCount, projectId: $1.projectId,
publishedAt: $1.publishedAt, sequence: $1.sequence, title: $1.title, urls: $1.urls, user: $1.user,
visible: $1.visible) }
)
public static let id = Lens<Update, Int>(
view: { $0.id },
set: { Update(body: $1.body, commentsCount: $1.commentsCount, hasLiked: $1.hasLiked, id: $0,
isPublic: $1.isPublic, likesCount: $1.likesCount, projectId: $1.projectId,
publishedAt: $1.publishedAt, sequence: $1.sequence, title: $1.title, urls: $1.urls, user: $1.user,
visible: $1.visible) }
)
public static let likesCount = Lens<Update, Int?>(
view: { $0.likesCount },
set: { Update(body: $1.body, commentsCount: $1.commentsCount, hasLiked: $1.hasLiked, id: $1.id,
isPublic: $1.isPublic, likesCount: $0, projectId: $1.projectId,
publishedAt: $1.publishedAt, sequence: $1.sequence, title: $1.title, urls: $1.urls, user: $1.user,
visible: $1.visible) }
)
public static let projectId = Lens<Update, Int>(
view: { $0.projectId },
set: { Update(body: $1.body, commentsCount: $1.commentsCount, hasLiked: $1.hasLiked, id: $1.id,
isPublic: $1.isPublic, likesCount: $1.likesCount, projectId: $0,
publishedAt: $1.publishedAt, sequence: $1.sequence, title: $1.title, urls: $1.urls, user: $1.user,
visible: $1.visible) }
)
public static let publishedAt = Lens<Update, TimeInterval?>(
view: { $0.publishedAt },
set: { Update(body: $1.body, commentsCount: $1.commentsCount, hasLiked: $1.hasLiked, id: $1.id,
isPublic: $1.isPublic, likesCount: $1.likesCount, projectId: $1.projectId,
publishedAt: $0, sequence: $1.sequence, title: $1.title, urls: $1.urls, user: $1.user,
visible: $1.visible) }
)
public static let sequence = Lens<Update, Int>(
view: { $0.sequence },
set: { Update(body: $1.body, commentsCount: $1.commentsCount, hasLiked: $1.hasLiked, id: $1.id,
isPublic: $1.isPublic, likesCount: $1.likesCount, projectId: $1.projectId,
publishedAt: $1.publishedAt, sequence: $0, title: $1.title, urls: $1.urls, user: $1.user,
visible: $1.visible) }
)
public static let title = Lens<Update, String>(
view: { $0.title },
set: { Update(body: $1.body, commentsCount: $1.commentsCount, hasLiked: $1.hasLiked, id: $1.id,
isPublic: $1.isPublic, likesCount: $1.likesCount, projectId: $1.projectId,
publishedAt: $1.publishedAt, sequence: $1.sequence, title: $0, urls: $1.urls, user: $1.user,
visible: $1.visible) }
)
public static let user = Lens<Update, User?>(
view: { $0.user },
set: { Update(body: $1.body, commentsCount: $1.commentsCount, hasLiked: $1.hasLiked, id: $1.id,
isPublic: $1.isPublic, likesCount: $1.likesCount, projectId: $1.projectId,
publishedAt: $1.publishedAt, sequence: $1.sequence, title: $1.title, urls: $1.urls, user: $0,
visible: $1.visible) }
)
public static let isPublic = Lens<Update, Bool>(
view: { $0.isPublic },
set: { Update(body: $1.body, commentsCount: $1.commentsCount, hasLiked: $1.hasLiked, id: $1.id,
isPublic: $0, likesCount: $1.likesCount, projectId: $1.projectId,
publishedAt: $1.publishedAt, sequence: $1.sequence, title: $1.title, urls: $1.urls, user: $1.user,
visible: $1.visible) }
)
}
}
| apache-2.0 |
kootsoop/buzzlr | buzzlr/buzzlr/TumblrData.swift | 1 | 365 | //
// TumblrData.swift
// buzzlr
//
// Created by Peter Kootsookos on 8/25/15.
// Copyright (c) 2015 Peter J. Kootsookos. All rights reserved.
//
import Foundation
class TumblrData
{
private var json :JSON
init(data: NSData!)
{
json = JSON(data)
var response = json["response"][0]["photos"]["original_size"]["url"]
print("\(response)")
}
} | mit |
takeo-asai/math-puzzle | problems/47.swift | 1 | 4328 | struct Board: Hashable {
let values: [[Bool]]
init(_ values: [[Bool]]) {
self.values = values
}
init(n: Int, var values: [Bool]) {
var vs: [[Bool]] = []
while !values.isEmpty {
vs += [Array(values[0..<n])]
values = Array(values[n..<values.count])
}
self.values = vs
}
func counts() -> [Int] {
var cs: [Int] = []
for v in values {
cs += [v.reduce(0) {$0 + ($1 ? 1 : 0)}]
}
for j in 0 ..< values[0].count {
var c = 0
for i in 0 ..< values.count {
c += values[i][j] ? 1 : 0
}
cs += [c]
}
return cs
}
var hashValue: Int {
get {
return counts().description.hashValue
}
}
}
func == (lhs: Board, rhs: Board) -> Bool {
return lhs.hashValue == rhs.hashValue
}
extension Array {
// ExSwift
//
// Created by pNre on 03/06/14.
// Copyright (c) 2014 pNre. All rights reserved.
//
// https://github.com/pNre/ExSwift/blob/master/ExSwift/Array.swift
// https://github.com/pNre/ExSwift/blob/master/LICENSE
/**
- parameter length: The length of each permutation
- returns: All permutations of a given length within an array
*/
func permutation (length: Int) -> [[Element]] {
if length < 0 || length > self.count {
return []
} else if length == 0 {
return [[]]
} else {
var permutations: [[Element]] = []
let combinations = combination(length)
for combination in combinations {
var endArray: [[Element]] = []
var mutableCombination = combination
permutations += self.permutationHelper(length, array: &mutableCombination, endArray: &endArray)
}
return permutations
}
}
private func permutationHelper(n: Int, inout array: [Element], inout endArray: [[Element]]) -> [[Element]] {
if n == 1 {
endArray += [array]
}
for var i = 0; i < n; i++ {
permutationHelper(n - 1, array: &array, endArray: &endArray)
let j = n % 2 == 0 ? i : 0
let temp: Element = array[j]
array[j] = array[n - 1]
array[n - 1] = temp
}
return endArray
}
func combination (length: Int) -> [[Element]] {
if length < 0 || length > self.count {
return []
}
var indexes: [Int] = (0..<length).reduce([]) {$0 + [$1]}
var combinations: [[Element]] = []
let offset = self.count - indexes.count
while true {
var combination: [Element] = []
for index in indexes {
combination.append(self[index])
}
combinations.append(combination)
var i = indexes.count - 1
while i >= 0 && indexes[i] == i + offset {
i--
}
if i < 0 {
break
}
i++
let start = indexes[i-1] + 1
for j in (i-1)..<indexes.count {
indexes[j] = start + j - i + 1
}
}
return combinations
}
/**
- parameter length: The length of each permutations
- returns: All of the permutations of this array of a given length, allowing repeats
*/
func repeatedPermutation(length: Int) -> [[Element]] {
if length < 1 {
return []
}
var indexes: [[Int]] = []
indexes.repeatedPermutationHelper([], length: length, arrayLength: self.count, indexes: &indexes)
return indexes.map({ $0.map({ i in self[i] }) })
}
private func repeatedPermutationHelper(seed: [Int], length: Int, arrayLength: Int, inout indexes: [[Int]]) {
if seed.count == length {
indexes.append(seed)
return
}
for i in (0..<arrayLength) {
var newSeed: [Int] = seed
newSeed.append(i)
self.repeatedPermutationHelper(newSeed, length: length, arrayLength: arrayLength, indexes: &indexes)
}
}
}
let n = 4
var cache: [Board: Int] = [: ]
for v in [true, false].repeatedPermutation(n*n) {
let b = Board(n: n, values: v)
if let c = cache[b] {
cache[b] = c + 1
} else {
cache[b] = 1
}
}
let f = cache.filter {_, value in value == 1}
print(f.count)
| mit |
bitjammer/swift | validation-test/stdlib/Collection/MinimalMutableRangeReplaceableRandomAccessCollection.swift | 22 | 4238 | // -*- swift -*-
//===----------------------------------------------------------------------===//
// Automatically Generated From validation-test/stdlib/Collection/Inputs/Template.swift.gyb
// Do Not Edit Directly!
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
import StdlibCollectionUnittest
var CollectionTests = TestSuite("Collection")
// Test collections using value types as elements.
do {
var resiliencyChecks = CollectionMisuseResiliencyChecks.all
resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap
CollectionTests.addRangeReplaceableRandomAccessCollectionTests(
makeCollection: { (elements: [OpaqueValue<Int>]) in
return MinimalMutableRangeReplaceableRandomAccessCollection(elements: elements)
},
wrapValue: identity,
extractValue: identity,
makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in
return MinimalMutableRangeReplaceableRandomAccessCollection(elements: elements)
},
wrapValueIntoEquatable: identityEq,
extractValueFromEquatable: identityEq,
resiliencyChecks: resiliencyChecks
)
CollectionTests.addMutableRandomAccessCollectionTests(
makeCollection: { (elements: [OpaqueValue<Int>]) in
return MinimalMutableRangeReplaceableRandomAccessCollection(elements: elements)
},
wrapValue: identity,
extractValue: identity,
makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in
return MinimalMutableRangeReplaceableRandomAccessCollection(elements: elements)
},
wrapValueIntoEquatable: identityEq,
extractValueFromEquatable: identityEq,
makeCollectionOfComparable: { (elements: [MinimalComparableValue]) in
return MinimalMutableRangeReplaceableRandomAccessCollection(elements: elements)
},
wrapValueIntoComparable: identityComp,
extractValueFromComparable: identityComp,
resiliencyChecks: resiliencyChecks
, withUnsafeMutableBufferPointerIsSupported: false,
isFixedLengthCollection: true
)
}
// Test collections using a reference type as element.
do {
var resiliencyChecks = CollectionMisuseResiliencyChecks.all
resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap
CollectionTests.addRangeReplaceableRandomAccessCollectionTests(
makeCollection: { (elements: [LifetimeTracked]) in
return MinimalMutableRangeReplaceableRandomAccessCollection(elements: elements)
},
wrapValue: { (element: OpaqueValue<Int>) in
LifetimeTracked(element.value, identity: element.identity)
},
extractValue: { (element: LifetimeTracked) in
OpaqueValue(element.value, identity: element.identity)
},
makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in
// FIXME: use LifetimeTracked.
return MinimalMutableRangeReplaceableRandomAccessCollection(elements: elements)
},
wrapValueIntoEquatable: identityEq,
extractValueFromEquatable: identityEq,
resiliencyChecks: resiliencyChecks
)
CollectionTests.addMutableRandomAccessCollectionTests(
makeCollection: { (elements: [LifetimeTracked]) in
return MinimalMutableRangeReplaceableRandomAccessCollection(elements: elements)
},
wrapValue: { (element: OpaqueValue<Int>) in
LifetimeTracked(element.value, identity: element.identity)
},
extractValue: { (element: LifetimeTracked) in
OpaqueValue(element.value, identity: element.identity)
},
makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in
// FIXME: use LifetimeTracked.
return MinimalMutableRangeReplaceableRandomAccessCollection(elements: elements)
},
wrapValueIntoEquatable: identityEq,
extractValueFromEquatable: identityEq,
makeCollectionOfComparable: { (elements: [MinimalComparableValue]) in
// FIXME: use LifetimeTracked.
return MinimalMutableRangeReplaceableRandomAccessCollection(elements: elements)
},
wrapValueIntoComparable: identityComp,
extractValueFromComparable: identityComp,
resiliencyChecks: resiliencyChecks
, withUnsafeMutableBufferPointerIsSupported: false,
isFixedLengthCollection: true
)
}
runAllTests()
| apache-2.0 |
bitjammer/swift | validation-test/compiler_crashers_fixed/25655-void.swift | 65 | 448 | // 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
// RUN: not %target-swift-frontend %s -typecheck
let a{class B<h:B
struct D:A.b
protocol A
class A
| apache-2.0 |
Dean151/TDPeopleStackView | TDPeopleStackView/Classes/TDPeopleStackView.swift | 1 | 7426 | //
// TDPeopleStackView.swift
// Pods
//
// Created by Thomas Durand on 01/05/2016.
//
//
import UIKit
// MARK: - Data Source
@objc public protocol TDPeopleStackViewDataSource: class {
func numberOfPeopleInStackView(peopleStackView: TDPeopleStackView) -> Int
optional func peopleStackView(peopleStackView: TDPeopleStackView, imageAtIndex index: Int) -> UIImage?
optional func peopleStackView(peopleStackView: TDPeopleStackView, placeholderTextAtIndex index: Int) -> String?
}
// MARK: - Delegate
@objc public protocol TDPeopleStackViewDelegate: class {
/**
Should return the button to show in the button for the peopleStackView.
- parameter peopleStackView: the instance of `TDPeopleStackView` for the button
- returns: A button to show in the peopleStackView
*/
optional func buttonForPeopleStackView(peopleStackView: TDPeopleStackView) -> UIButton?
/**
The text to show in the button for the peopleStackView. Will not be called when `buttonForPeopleStackView(_:)` is called
- parameter peopleStackView: the instance of `TDPeopleStackView` for the button
- returns: A String to show in the button
*/
optional func titleForButtonInPeopleStackView(peopleStackView: TDPeopleStackView) -> String?
/**
Will be called when the button from an instance of a `TDPeopleStackView` is pressed
- parameter button: The button that have been pressed
- parameter peopleStackView: the instance of `TDPeopleStackView` that received the press event
*/
optional func peopleStackViewButtonPressed(button: UIButton, peopleStackView: TDPeopleStackView)
}
// MARK: - Public properties
@objc public class TDPeopleStackView: UIView {
/**
Constant that allow to set the space between circles.
Below 1, there will be an overlap between circles
Default value is 0.75
*/
public var overlapConstant: CGFloat = 0.75 {
didSet {
if !firstLayoutDone { return }
reloadData()
}
}
/**
The maximum number of circle to show before folding.
Set to 0 for unlimited
*/
public var maxNumberOfCircles: Int = 0 {
didSet {
if !firstLayoutDone { return }
reloadData()
}
}
/**
The color of the people circle's background when there is no image to show
*/
public var placeholderBackgroundColor = UIColor.lightGrayColor() {
didSet {
if !firstLayoutDone { return }
reloadData()
}
}
/**
The color of the people circle's text when there is no image to show
*/
public var placeholderTextColor = UIColor.whiteColor() {
didSet {
if !firstLayoutDone { return }
reloadData()
}
}
/**
The font of the people circle's text when there is no image to show
*/
public var placeholderTextFont: UIFont = UIFont.systemFontOfSize(24) {
didSet {
if !firstLayoutDone { return }
reloadData()
}
}
/**
The data source for this `PeopleStackView` instance
*/
public var dataSource: TDPeopleStackViewDataSource?
/**
The delegate for this `PeopleStackView` instance
*/
public var delegate: TDPeopleStackViewDelegate?
private var firstLayoutDone = false
public override func layoutSubviews() {
super.layoutSubviews()
firstLayoutDone = true
reloadData()
}
@objc private func buttonPressed(sender: UIButton) {
self.delegate?.peopleStackViewButtonPressed?(sender, peopleStackView: self)
}
}
// MARK: - Drawing
extension TDPeopleStackView {
public func reloadData() {
// Remove all subviews
subviews.forEach({ $0.removeFromSuperview() })
// Create the show more button if needed
var button: UIButton?
if let fullButton = delegate?.buttonForPeopleStackView?(self) {
button = fullButton
} else if let buttonText = delegate?.titleForButtonInPeopleStackView?(self) {
button = UIButton(type: .System)
button?.setTitle(buttonText, forState: .Normal)
button?.sizeToFit()
}
if let button = button {
button.frame = CGRectMake(bounds.width - button.bounds.width, (bounds.height-button.bounds.height)/2, button.bounds.width, button.bounds.height)
button.addTarget(self, action: #selector(TDPeopleStackView.buttonPressed(_:)), forControlEvents: .TouchUpInside)
addSubview(button)
}
// Calculate the size of circles
let circleDiameter = min(bounds.width, bounds.height)
let circleSize = CGSizeMake(circleDiameter, circleDiameter)
for index in 0..<(dataSource?.numberOfPeopleInStackView(self) ?? 0) {
let origin = CGPointMake(circleDiameter * CGFloat(index) * overlapConstant, 0)
let rect = CGRect(origin: origin, size: circleSize)
// Calculate next circule to know when we should stop the loop
let nextOrigin = CGPointMake(circleDiameter * CGFloat(index+1) * overlapConstant, 0)
let nextRect = CGRect(origin: nextOrigin, size: circleSize)
let willDrawLastCircle = nextRect.origin.x + nextRect.width > (bounds.width - (button?.bounds.width ?? 0) ) ||
(maxNumberOfCircles > 0 && index+1 > maxNumberOfCircles)
var circleView: UIView!
if let image = dataSource?.peopleStackView?(self, imageAtIndex: index) where !willDrawLastCircle {
// We have an image, and it's not the last to be drawn
let imageView = UIImageView(frame: rect)
imageView.image = image
imageView.contentMode = .ScaleAspectFill
circleView = imageView
} else {
// We create a label to show initials or the number of people for the last circle
let label = UILabel(frame: rect)
label.textColor = placeholderTextColor
label.textAlignment = .Center
if willDrawLastCircle {
if #available(iOS 8.2, *) {
label.font = UIFont.systemFontOfSize(30, weight: UIFontWeightThin)
} else {
label.font = UIFont(name: "HelveticaNeue-Thin", size: 30)!
}
label.text = "\(dataSource?.numberOfPeopleInStackView(self) ?? 0)"
} else {
label.font = placeholderTextFont
label.text = dataSource?.peopleStackView?(self, placeholderTextAtIndex: index)
}
circleView = label
}
circleView.layer.cornerRadius = circleDiameter/2
circleView.clipsToBounds = true
circleView.layer.borderColor = UIColor.whiteColor().CGColor
circleView.layer.borderWidth = 1.0
circleView.backgroundColor = self.placeholderBackgroundColor
addSubview(circleView)
if willDrawLastCircle {
break;
}
}
setNeedsDisplay()
}
}
| mit |
pyro2927/PlexNotifier | PlexNotifier/main.swift | 1 | 186 | //
// main.swift
// PlexNotifier
//
// Created by Joseph Pintozzi on 6/8/14.
// Copyright (c) 2014 pyro2927. All rights reserved.
//
import Cocoa
NSApplicationMain(C_ARGC, C_ARGV)
| gpl-2.0 |
firebase/firebase-ios-sdk | scripts/health_metrics/generate_code_coverage_report/Sources/Utils/MetricsServiceRequest.swift | 1 | 2852 | /*
* Copyright 2021 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
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
public func sendMetricsServiceRequest(repo: String, commits: String, jsonContent: Data,
token: String,
is_presubmit: Bool, branch: String?, pullRequest: Int?,
pullRequestNote: String?, baseCommit: String?) {
var request: URLRequest
var semaphore = DispatchSemaphore(value: 0)
let endpoint =
"https://api.firebase-sdk-health-metrics.com/repos/\(repo)/commits/\(commits)/reports?"
var pathPara: [String] = []
if is_presubmit {
guard let pr = pullRequest else {
print(
"The pull request number should be specified for an API pull-request request to the Metrics Service."
)
return
}
guard let bc = baseCommit else {
print(
"Base commit hash should be specified for an API pull-request request to the Metrics Service."
)
return
}
pathPara.append("pull_request=\(String(pr))")
if let note = pullRequestNote {
let compatible_url_format_note = note
.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
pathPara.append("note=\(compatible_url_format_note))")
}
pathPara.append("base_commit=\(bc)")
} else {
guard let branch = branch else {
print("Targeted merged branch should be specified.")
return
}
pathPara.append("branch=\(branch)")
}
let webURL = endpoint + pathPara.joined(separator: "&")
guard let metricsServiceURL = URL(string: webURL) else {
print("URL Path \(webURL) is not valid.")
return
}
request = URLRequest(url: metricsServiceURL, timeoutInterval: Double.infinity)
request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = jsonContent
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print(String(describing: error))
return
}
print(String(data: data, encoding: .utf8)!)
semaphore.signal()
}
task.resume()
semaphore.wait()
}
| apache-2.0 |
hanhailong/practice-swift | Networking/Serializing and Deserializing JSON Objects/Serializing and Deserializing JSON ObjectsTests/Serializing_and_Deserializing_JSON_ObjectsTests.swift | 2 | 1000 | //
// Serializing_and_Deserializing_JSON_ObjectsTests.swift
// Serializing and Deserializing JSON ObjectsTests
//
// Created by Domenico on 16/05/15.
// Copyright (c) 2015 Domenico. All rights reserved.
//
import UIKit
import XCTest
class Serializing_and_Deserializing_JSON_ObjectsTests: 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.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
typelift/SwiftCheck | Tests/SwiftCheckTests/TestSpec.swift | 1 | 2662 | //
// TestSpec.swift
// SwiftCheck
//
// Created by Robert Widmann on 6/23/15.
// Copyright © 2015 TypeLift. All rights reserved.
//
import SwiftCheck
import XCTest
#if SWIFT_PACKAGE
import FileCheck
#endif
enum MyException: String, Error, Arbitrary {
case phony
case baloney
static var arbitrary: Gen<MyException> {
return Gen.fromElements(of: [ .phony, .baloney ])
}
}
class TestSpec : XCTestCase {
func testAll() {
XCTAssert(fileCheckOutput {
// CHECK: *** Passed 100 tests
// CHECK-NEXT: .
property("Dictionaries behave") <- forAll { (xs : Dictionary<Int, Int>) in
return true
}
// CHECK-NEXT: *** Passed 100 tests
// CHECK-NEXT: .
property("Optionals behave") <- forAll { (xs : Int?) in
return true
}
// CHECK-NEXT: *** Passed 100 tests
// CHECK-NEXT: .
property("Sets behave") <- forAll { (xs : Set<Int>) in
return true
}
// CHECK-NEXT: *** Passed 100 tests
// CHECK-NEXT: .
property("Results behave") <- forAll { (xs : Result<String, MyException>) in
return true
}
// CHECK-NEXT: *** Passed 100 tests
// CHECK-NEXT: (100%, {{Right|Left}} identity, {{Right|Left}} identity)
// CHECK: Failed: (Bad Sort Right)
// CHECK-NEXT: Pass the seed values {{[0-9]+}} {{[0-9]+}} to replay the test.
property("The reverse of the reverse of an array is that array") <- forAll { (xs : Array<Int>) in
return
(xs.reversed().reversed() == xs) <?> "Left identity"
^&&^
(xs == xs.reversed().reversed()) <?> "Right identity"
}
/// CHECK: +++ OK, failed as expected. Proposition: Failing conjunctions print labelled properties
/// CHECK-NEXT: Falsifiable (after 1 test):
/// CHECK-NEXT: []
/// CHECK-NEXT: .
property("Failing conjunctions print labelled properties") <- forAll { (xs : Array<Int>) in
return (xs.sorted().sorted() == xs.sorted()).verbose <?> "Sort Left"
^&&^
((xs.sorted() != xs.sorted().sorted()).verbose <?> "Bad Sort Right")
}.expectFailure
// CHECK-NEXT: *** Passed 100 tests
// CHECK-NEXT: .
property("map behaves") <- forAll { (xs : Array<Int>) in
return forAll { (f : ArrowOf<Int, Int>) in
return xs.map(f.getArrow) == xs.map(f.getArrow)
}
}
// CHECK-NEXT: *** Passed 100 tests
// CHECK-NEXT: .
property("filter behaves") <- forAll { (xs : Array<Int>) in
return forAll { (pred : ArrowOf<Int, Bool>) in
let f = pred.getArrow
return (xs.filter(f).reduce(true, { (acc, val) in acc && f(val) }) as Bool)
}
}
})
}
#if !(os(macOS) || os(iOS) || os(watchOS) || os(tvOS))
static var allTests = testCase([
("testAll", testAll),
])
#endif
}
| mit |
danielsaidi/KeyboardKit | Tests/KeyboardKitTests/Layout/Providers/StandardKeyboardLayoutProviderTests.swift | 1 | 3068 | //
// StandardKeyboardLayoutProviderTests.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2021-02-17.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import Quick
import Nimble
import KeyboardKit
class StandardKeyboardLayoutProviderTests: QuickSpec {
override func spec() {
var provider: StandardKeyboardLayoutProvider!
var inputProvider: MockKeyboardInputSetProvider!
var context: MockKeyboardContext!
var device: MockDevice!
beforeEach {
context = MockKeyboardContext()
device = MockDevice()
context.device = device
inputProvider = MockKeyboardInputSetProvider()
inputProvider.alphabeticInputSetValue = AlphabeticKeyboardInputSet(rows: KeyboardInputRows([["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"]]))
inputProvider.numericInputSetValue = NumericKeyboardInputSet(rows: KeyboardInputRows([["1", "2", "3"], ["1", "2", "3"], ["1", "2", "3"]]))
inputProvider.symbolicInputSetValue = SymbolicKeyboardInputSet(rows: KeyboardInputRows([[",", ".", "-"], [",", ".", "-"], [",", ".", "-"]]))
provider = StandardKeyboardLayoutProvider(
inputSetProvider: inputProvider,
dictationReplacement: .go)
}
describe("keyboard layout for context") {
it("is phone layout if context device is phone") {
device.userInterfaceIdiomValue = .phone
let layout = provider.keyboardLayout(for: context)
let phoneLayout = provider.iPhoneProvider.keyboardLayout(for: context)
let padLayout = provider.iPadProvider.keyboardLayout(for: context)
expect(layout.items).to(equal(phoneLayout.items))
expect(layout.items).toNot(equal(padLayout.items))
}
it("is pad layout if context device is pad") {
device.userInterfaceIdiomValue = .pad
let layout = provider.keyboardLayout(for: context)
let phoneLayout = provider.iPhoneProvider.keyboardLayout(for: context)
let padLayout = provider.iPadProvider.keyboardLayout(for: context)
expect(layout.items).toNot(equal(phoneLayout.items))
expect(layout.items).to(equal(padLayout.items))
}
}
describe("registering input set provider") {
it("changes the provider instance for all providers") {
let newInputProvider = MockKeyboardInputSetProvider()
provider.register(inputSetProvider: newInputProvider)
expect(provider.inputSetProvider).toNot(be(inputProvider))
expect(provider.inputSetProvider).to(be(newInputProvider))
expect(provider.iPhoneProvider.inputSetProvider).to(be(newInputProvider))
expect(provider.iPadProvider.inputSetProvider).to(be(newInputProvider))
}
}
}
}
| mit |
loudnate/LoopKit | LoopKitUI/Views/SuspendResumeTableViewCell.swift | 1 | 2276 | //
// SuspendResumeTableViewCell.swift
// LoopKitUI
//
// Created by Pete Schwamb on 11/16/18.
// Copyright © 2018 LoopKit Authors. All rights reserved.
//
import LoopKit
public class SuspendResumeTableViewCell: TextButtonTableViewCell {
public enum Action {
case suspend
case resume
}
public var shownAction: Action {
switch basalDeliveryState {
case .active, .suspending, .tempBasal, .cancelingTempBasal, .initiatingTempBasal:
return .suspend
case .suspended, .resuming:
return .resume
}
}
private func updateTextLabel() {
switch self.basalDeliveryState {
case .active, .tempBasal:
textLabel?.text = LocalizedString("Suspend Delivery", comment: "Title text for button to suspend insulin delivery")
case .suspending:
self.textLabel?.text = LocalizedString("Suspending", comment: "Title text for button when insulin delivery is in the process of being stopped")
case .suspended:
textLabel?.text = LocalizedString("Resume Delivery", comment: "Title text for button to resume insulin delivery")
case .resuming:
self.textLabel?.text = LocalizedString("Resuming", comment: "Title text for button when insulin delivery is in the process of being resumed")
case .initiatingTempBasal:
self.textLabel?.text = LocalizedString("Starting Temp Basal", comment: "Title text for suspend resume button when temp basal starting")
case .cancelingTempBasal:
self.textLabel?.text = LocalizedString("Canceling Temp Basal", comment: "Title text for suspend resume button when temp basal canceling")
}
}
private func updateLoadingState() {
self.isLoading = {
switch self.basalDeliveryState {
case .suspending, .resuming, .initiatingTempBasal, .cancelingTempBasal:
return true
default:
return false
}
}()
self.isEnabled = !self.isLoading
}
public var basalDeliveryState: PumpManagerStatus.BasalDeliveryState = .active(Date()) {
didSet {
updateTextLabel()
updateLoadingState()
}
}
}
| mit |
wupingzj/YangRepoApple | QiuTuiJian/QiuTuiJian/MapInfo.swift | 1 | 304 | //
// MapInfo.swift
// QiuTuiJian
//
// Created by Ping on 30/09/2014.
// Copyright (c) 2014 Yang Ltd. All rights reserved.
//
import Foundation
enum MapInfo {
case ShowUser
case ShowBusinessEntity
case ShowBoth // show information for both user's current location and business entity
} | gpl-2.0 |
raphaelmor/GeoJSON | GeoJSONTests/Geometry/PolygonTests.swift | 1 | 5922 | // PolygonTests.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2014 Raphaël Mor
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import XCTest
import GeoJSON
class PolygonTests: XCTestCase {
var geoJSON: GeoJSON!
var twoRingPolygon: Polygon!
override func setUp() {
super.setUp()
geoJSON = geoJSONfromString("{ \"type\": \"Polygon\", \"coordinates\": [ [[0.0, 0.0], [1.0, 1.0], [2.0, 2.0], [0.0, 0.0]] ] }")
let firstRing = LineString(points:[
Point(coordinates:[0.0,0.0])!,
Point(coordinates:[1.0,1.0])!,
Point(coordinates:[2.0,2.0])!,
Point(coordinates:[0.0,0.0])!
])!
let secondRing = LineString(points: [
Point(coordinates:[10.0,10.0])!,
Point(coordinates:[11.0,11.0])!,
Point(coordinates:[12.0,12.0])!,
Point(coordinates:[10.0,10.0])!
])!
twoRingPolygon = Polygon(linearRings: [firstRing, secondRing])
}
override func tearDown() {
geoJSON = nil
twoRingPolygon = nil
super.tearDown()
}
// MARK: - Nominal cases
// MARK: Decoding
func testBasicPolygonShouldBeRecognisedAsSuch() {
XCTAssertEqual(geoJSON.type, GeoJSONType.Polygon)
}
func testPolygonShouldBeAGeometry() {
XCTAssertTrue(geoJSON.isGeometry())
}
func testEmptyPolygonShouldBeParsedCorrectly() {
geoJSON = geoJSONfromString("{ \"type\": \"Polygon\", \"coordinates\": [] }")
if let geoPolygon = geoJSON.polygon {
XCTAssertEqual(geoPolygon.linearRings.count, 0)
} else {
XCTFail("Polygon not parsed properly")
}
}
func testBasicPolygonShouldBeParsedCorrectly() {
if let geoPolygon = geoJSON.polygon {
XCTAssertEqual(geoPolygon.linearRings.count, 1)
XCTAssertTrue(geoPolygon.linearRings[0].isLinearRing())
XCTAssertEqualWithAccuracy(geoPolygon.linearRings[0][0].longitude, 0.0, 0.000001)
XCTAssertEqualWithAccuracy(geoPolygon.linearRings[0][0].latitude, 0.0, 0.000001)
XCTAssertEqualWithAccuracy(geoPolygon.linearRings[0][1].longitude, 1.0, 0.000001)
XCTAssertEqualWithAccuracy(geoPolygon.linearRings[0][1].latitude, 1.0, 0.000001)
XCTAssertEqualWithAccuracy(geoPolygon.linearRings[0][2].longitude, 2.0, 0.000001)
XCTAssertEqualWithAccuracy(geoPolygon.linearRings[0][2].latitude, 2.0, 0.000001)
XCTAssertEqualWithAccuracy(geoPolygon.linearRings[0][3].longitude, 0.0, 0.000001)
XCTAssertEqualWithAccuracy(geoPolygon.linearRings[0][3].latitude, 0.0, 0.000001)
} else {
XCTFail("Polygon not parsed Properly")
}
}
// MARK: Encoding
func testBasicPolygonShouldBeEncoded() {
XCTAssertNotNil(twoRingPolygon,"Valid Polygon should be encoded properly")
if let jsonString = stringFromJSON(twoRingPolygon.json()) {
XCTAssertEqual(jsonString, "[[[0,0],[1,1],[2,2],[0,0]],[[10,10],[11,11],[12,12],[10,10]]]")
} else {
XCTFail("Valid Polygon should be encoded properly")
}
}
func testZeroRingPolygonShouldBeValid() {
let zeroRingPolygon = Polygon(linearRings:[])!
if let jsonString = stringFromJSON(zeroRingPolygon.json()) {
XCTAssertEqual(jsonString, "[]")
}else {
XCTFail("Empty Polygon should be encoded properly")
}
}
func testPolygonShouldHaveTheRightPrefix() {
XCTAssertEqual(twoRingPolygon.prefix,"coordinates")
}
func testBasicPolygonInGeoJSONShouldBeEncoded() {
let geoJSON = GeoJSON(polygon: twoRingPolygon)
if let jsonString = stringFromJSON(geoJSON.json()) {
checkForSubstring("\"coordinates\":[[[0,0],[1,1],[2,2],[0,0]],[[10,10],[11,11],[12,12],[10,10]]]", jsonString)
checkForSubstring("\"type\":\"Polygon\"", jsonString)
} else {
XCTFail("Valid Polygon in GeoJSON should be encoded properly")
}
}
// MARK: - Error cases
// MARK: Decoding
func testPolygonWithoutCoordinatesShouldRaiseAnError() {
geoJSON = geoJSONfromString("{ \"type\": \"Polygon\"}")
if let error = geoJSON.error {
XCTAssertEqual(error.domain, GeoJSONErrorDomain)
XCTAssertEqual(error.code, GeoJSONErrorInvalidGeoJSONObject)
}
else {
XCTFail("Invalid Polygon should raise an invalid object error")
}
}
func testPolygonWithAnInvalidLinearRingShouldRaiseAnError() {
geoJSON = geoJSONfromString("{ \"type\": \"Polygon\", \"coordinates\": [ [[0.0, 0.0], [1.0, 1.0], [2.0, 2.0], [3.0, 3.0]] ] }")
if let error = geoJSON.error {
XCTAssertEqual(error.domain, GeoJSONErrorDomain)
XCTAssertEqual(error.code, GeoJSONErrorInvalidGeoJSONObject)
}
else {
XCTFail("Invalid Polygon should raise an invalid object error")
}
}
func testIllFormedMultiLineStringShouldRaiseAnError() {
geoJSON = geoJSONfromString("{ \"type\": \"Polygon\", \"coordinates\": [ [0.0, 1.0], {\"invalid\" : 2.0} ] }")
if let error = geoJSON.error {
XCTAssertEqual(error.domain, GeoJSONErrorDomain)
XCTAssertEqual(error.code, GeoJSONErrorInvalidGeoJSONObject)
}
else {
XCTFail("Invalid Polygon should raise an invalid object error")
}
}
// MARK: Encoding
}
| mit |
JPIOS/JDanTang | JDanTang/JDanTang/Class/MainClass/DanTang/DanTang/View/JDanTangCell.swift | 1 | 1403 | //
// JDanTangCell.swift
// JDanTang
//
// Created by mac_KY on 2017/6/26.
// Copyright © 2017年 mac_KY. All rights reserved.
//
import UIKit
import Kingfisher
class JDanTangCell: UICollectionViewCell {
@IBOutlet weak var imgV: UIImageView!//图片
@IBOutlet weak var descLb: UILabel!//描述
@IBOutlet weak var priceLb: UILabel!//价格
@IBOutlet weak var praiseLB: UILabel!//赞的个数
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
cornerRadiu(radiu: 2)
}
func setModel(model:JDanTangModel) {
/*
这个框架和 SD_WebImage差不多
options:[.transition(ImageTransition.fade(1))](demo中看到,暂时不理解)
progressBlock:进度显示
image, error, cacheType, imageURL: 失败的回调 可分析失败原因
*/
let url = URL.init(string: model.cover_image_url!)
imgV.kf.setImage(with: url, placeholder: UIImage.init(named:"Me_ProfileBackground"), options: [.transition(ImageTransition.fade(1))], progressBlock: { (receivedSize, totalSize) in
}) { ( image, error, cacheType, imageURL ) in
}
descLb.text = model.name
priceLb.text = model.price
praiseLB.text = String.init(format: "%d", model.favorites_count!)
}
}
| apache-2.0 |
devpunk/cartesian | cartesian/View/DrawProject/Size/VDrawProjectSizeDimension.swift | 1 | 3412 | import UIKit
class VDrawProjectSizeDimension:UIView
{
private(set) weak var textField:UITextField!
private let kLabelHeight:CGFloat = 45
private let kLabelBottom:CGFloat = -5
private let kFieldMargin:CGFloat = 19
private let kFieldTop:CGFloat = 25
private let kCornerRadius:CGFloat = 4
private let kBackgroundMargin:CGFloat = 9
private let kBorderWidth:CGFloat = 1
init(title:String)
{
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.clear
translatesAutoresizingMaskIntoConstraints = false
let label:UILabel = UILabel()
label.isUserInteractionEnabled = false
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.clear
label.textAlignment = NSTextAlignment.center
label.font = UIFont.regular(size:16)
label.textColor = UIColor.black
label.text = title
let textField:UITextField = UITextField()
textField.borderStyle = UITextBorderStyle.none
textField.translatesAutoresizingMaskIntoConstraints = false
textField.clipsToBounds = true
textField.backgroundColor = UIColor.clear
textField.placeholder = NSLocalizedString("VDrawProjectSizeDimension_placeholder", comment:"")
textField.keyboardType = UIKeyboardType.numbersAndPunctuation
textField.keyboardAppearance = UIKeyboardAppearance.light
textField.spellCheckingType = UITextSpellCheckingType.no
textField.autocorrectionType = UITextAutocorrectionType.no
textField.autocapitalizationType = UITextAutocapitalizationType.none
textField.clearButtonMode = UITextFieldViewMode.never
textField.returnKeyType = UIReturnKeyType.next
textField.tintColor = UIColor.black
textField.textColor = UIColor.black
textField.font = UIFont.numeric(size:20)
self.textField = textField
let background:UIView = UIView()
background.backgroundColor = UIColor.white
background.translatesAutoresizingMaskIntoConstraints = false
background.clipsToBounds = true
background.isUserInteractionEnabled = false
background.layer.cornerRadius = kCornerRadius
background.layer.borderColor = UIColor(white:0, alpha:0.1).cgColor
background.layer.borderWidth = kBorderWidth
addSubview(label)
addSubview(background)
addSubview(textField)
NSLayoutConstraint.bottomToBottom(
view:label,
toView:self,
constant:kLabelBottom)
NSLayoutConstraint.height(
view:label,
constant:kLabelHeight)
NSLayoutConstraint.equalsHorizontal(
view:label,
toView:self)
NSLayoutConstraint.topToTop(
view:textField,
toView:self,
constant:kFieldTop)
NSLayoutConstraint.bottomToTop(
view:textField,
toView:label)
NSLayoutConstraint.equalsHorizontal(
view:textField,
toView:self,
margin:kFieldMargin)
NSLayoutConstraint.equals(
view:textField,
toView:background,
margin:kBackgroundMargin)
}
required init?(coder:NSCoder)
{
return nil
}
}
| mit |
sunshineclt/NKU-Helper | NKU Helper/功能/评教/CourseToEvaluate.swift | 1 | 647 | //
// CourseToEvaluate.swift
// NKU Helper
//
// Created by 陈乐天 on 1/21/16.
// Copyright © 2016 陈乐天. All rights reserved.
//
import Foundation
class CourseToEvaluate {
var className: String
var teacherName: String
var hasEvaluated: Bool
var index: Int
init(className: String, teacherName: String, hasEvaluated: String, index: Int) {
self.className = className
self.teacherName = teacherName
if hasEvaluated == "未评价" {
self.hasEvaluated = false
}
else {
self.hasEvaluated = true
}
self.index = index
}
}
| gpl-3.0 |
RaviDesai/RSDRestServices | Pod/Classes/ResponseParsers/APIJSONSerializableResponseParser.swift | 1 | 3063 | //
// JSONResponseParser.swift
// CEVFoundation
//
// Created by Ravi Desai on 6/10/15.
// Copyright (c) 2015 CEV. All rights reserved.
//
import Foundation
import RSDSerialization
public class APIJSONSerializableResponseParser<T: SerializableFromJSON> : APIResponseParserProtocol {
public init() {
self.acceptTypes = ["application/json"]
}
public init(versionRepresentation: ModelResourceVersionRepresentation, vendor: String, version: String) {
if (versionRepresentation == ModelResourceVersionRepresentation.CustomContentType) {
self.acceptTypes = ["application/\(vendor).v\(version)+json"]
} else {
self.acceptTypes = ["application/json"]
}
}
public init(acceptTypes: [String]) {
self.acceptTypes = acceptTypes
}
public private(set) var acceptTypes: [String]?
public class func convertToSerializable(response: NetworkResponse) -> (T?, NSError?) {
let (jsonOptional, error) = response.getJSON()
if let json:JSON = jsonOptional {
if let obj = T.createFromJSON(json) {
return (obj, nil)
} else {
let userInfo = [NSLocalizedDescriptionKey: "JSON deserialization error", NSLocalizedFailureReasonErrorKey: "JSON deserialization error"]
let jsonError = NSError(domain: "com.careevolution.direct", code: 48103001, userInfo: userInfo)
return (nil, jsonError)
}
} else {
return (nil, error)
}
}
public class func convertToSerializableArray(response: NetworkResponse) -> ([T]?, NSError?) {
let (jsonOptional, error) = response.getJSON()
if let json:JSON = jsonOptional {
if let objArray = ModelFactory<T>.createFromJSONArray(json) {
return (objArray.map { $0 }, nil)
} else {
let userInfo = [NSLocalizedDescriptionKey: "JSON deserialization error", NSLocalizedFailureReasonErrorKey: "JSON deserialization error"]
let jsonError = NSError(domain: "com.careevolution.direct", code: 48103001, userInfo: userInfo)
return (nil, jsonError)
}
} else {
return (nil, error)
}
}
public func Parse(response: NetworkResponse) -> (T?, NSError?) {
let (jsonOptional, jsonError) = response.getJSON()
if (jsonOptional != nil) {
return APIJSONSerializableResponseParser.convertToSerializable(response)
}
let responseError = response.getError() ?? jsonError;
return (nil, responseError)
}
public func ParseToArray(response: NetworkResponse) -> ([T]?, NSError?) {
let (jsonOptional, jsonError) = response.getJSON()
if (jsonOptional != nil) {
return APIJSONSerializableResponseParser.convertToSerializableArray(response)
}
let responseError = response.getError() ?? jsonError;
return (nil, responseError)
}
} | mit |
Syniverse/Push-Notification-SDK | ios/demo/Downloader/NotificationService.swift | 1 | 3765 | //
// NotificationService.swift
// Downloader
//
// Created by Slav Sarafski on 26/10/16.
// Copyright © 2016 softavail. All rights reserved.
//
import UserNotifications
import SCGPushSDK
import MobileCoreServices
@available(iOSApplicationExtension 10.0, *)
class NotificationService: UNNotificationServiceExtension {
var hasApppId: Bool = false
var hasToken: Bool = false
var hasBaseUrl: Bool = false
override init () {
super.init()
if let defaults:UserDefaults = UserDefaults(suiteName: "group.com.syniverse.scg.push.demo") {
if let appId = defaults.string(forKey: "scg-push-appid") as String! {
debugPrint("Info: [SCGPush] successfully assigned appid")
SCGPush.sharedInstance().appID = appId
self.hasApppId = true
}
if let token = defaults.string(forKey: "scg-push-token") as String! {
debugPrint("Info: [SCGPush] successfully assigned acces token")
SCGPush.sharedInstance().accessToken = token
self.hasToken = true
}
if let baseUrl = defaults.string(forKey: "scg-push-baseurl") as String! {
debugPrint("Info: [SCGPush] successfully assigned baseurl")
SCGPush.sharedInstance().callbackURI = baseUrl
self.hasBaseUrl = true
}
} else {
debugPrint("Error: [SCGPush] could not access defaults with suite group.com.syniverse.scg.push.demo")
}
}
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
if !self.hasToken || !self.hasApppId || !self.hasBaseUrl {
debugPrint("Error: [SCGPush] wont load attachment cause baseurl, accesstoken or appid is missing")
contentHandler(request.content.copy() as! UNNotificationContent)
} else if let attachmentID = request.content.userInfo["scg-attachment-id"] as? String, let messageID = request.content.userInfo["scg-message-id"] as? String {
// Download the attachment
debugPrint("Notice: [SCGPush] will try to load attachment \(attachmentID) for message \(messageID)")
SCGPush.sharedInstance().loadAttachment(withMessageId: messageID, andAttachmentId: attachmentID, completionBlock: { (contentUrl, contentType) in
debugPrint("Info: [SCGPush] successfully loaded attachment with content-type: \(contentType)")
let bestAttemptContent:UNMutableNotificationContent = request.content.mutableCopy() as! UNMutableNotificationContent
let options = [UNNotificationAttachmentOptionsTypeHintKey: contentType]
if let attachment = try? UNNotificationAttachment(identifier: attachmentID, url: contentUrl, options: options) {
bestAttemptContent.attachments = [attachment]
} else {
debugPrint("Error: [SCGPush] could not create attachment with content-type: \(contentType)")
}
contentHandler(bestAttemptContent)
}, failureBlock: { (error) in
debugPrint("Error: [SCGPush] failed to load attachment: \(attachmentID)")
contentHandler(request.content.mutableCopy() as! UNMutableNotificationContent)
})
} else {
debugPrint("Error: [SCGPush] wont load attachment cause accesstoken or appid is missing")
contentHandler(request.content.copy() as! UNNotificationContent)
}
}
override func serviceExtensionTimeWillExpire() {
// No best attempt from us
}
}
| mit |
airspeedswift/swift-compiler-crashes | fixed/00111-swift-constraints-constraintsystem-simplifyconstraint.swift | 12 | 232 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
() {
g g h g
}
}
func e(i: d) -> <f>(() -> f)>
| mit |
Jamnitzer/MBJ_ImageProcessing | MBJ_ImageProcessing/MBJ_ImageProcessing/MBJContext.swift | 1 | 1330 | //
// MBEContext.m
// ImageProcessing
//
// Created by Warren Moore on 10/8/14.
// Copyright (c) 2014 Metal By Example. All rights reserved.
//------------------------------------------------------------------------
// converted to Swift by Jamnitzer (Jim Wrenholt)
//------------------------------------------------------------------------
import Foundation
import Metal
//------------------------------------------------------------------------------
class MBJContext
{
var device:MTLDevice! = nil
var library:MTLLibrary! = nil
var commandQueue:MTLCommandQueue! = nil
//------------------------------------------------------------------------
init(device:MTLDevice?)
{
if (device != nil)
{
self.device = device
}
else
{
self.device = MTLCreateSystemDefaultDevice()
}
self.library = self.device!.newDefaultLibrary()
self.commandQueue = self.device!.newCommandQueue()
}
//------------------------------------------------------------------------
class func newContext() -> MBJContext
{
return MBJContext(device:nil)
}
//------------------------------------------------------------------------
}
//------------------------------------------------------------------------------
| mit |
bravelocation/yeltzland-ios | yeltzland/Views/Modifiers/SingleLineTextModifier.swift | 1 | 603 | //
// SingleLineTextModifier.swift
// Yeltzland
//
// Created by John Pollard on 15/06/2022.
// Copyright © 2022 John Pollard. All rights reserved.
//
import SwiftUI
@available(iOS 13, *)
struct SingleLineTextModifier: ViewModifier {
func body(content: Content) -> some View {
content
.lineLimit(1)
.allowsTightening(true)
.minimumScaleFactor(0.5)
.truncationMode(.tail)
}
}
@available(iOS 13, *)
extension View {
@warn_unqualified_access
func singleLine() -> some View {
modifier(SingleLineTextModifier())
}
}
| mit |
djera/MRTableViewCellCountScrollIndicator | Example/MRTableViewCellCountScrollIndicator/ArticleList.swift | 1 | 317 | //
// ArticleList.swift
// MRTableViewCellCountScrollIndicator
//
// Created by Tovarna Idej on 13/07/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Foundation
import CoreData
class ArticleList: NSManagedObject {
// Insert code here to add functionality to your managed object subclass
}
| mit |
AmirDaliri/BaboonProject | Baboon/Baboon/TableViewController.swift | 1 | 908 | //
// TableViewController.swift
// Baboon
//
// Created by Amir Daliri on 3/22/17.
// Copyright © 2017 Baboon. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let detail = segue.destination as? DetailViewController,
let selectedIndexPath = tableView.indexPathForSelectedRow {
detail.detailText = "Item #\(selectedIndexPath.row)"
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "Item #\(indexPath.row)"
return cell
}
}
| mit |
lanjing99/iOSByTutorials | iOS 8 by tutorials/Chapter 15 - Beginning CloudKit/BabiFud-Starter/BabiFud/AppDelegate.swift | 2 | 1804 | /*
* Copyright (c) 2014 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
// doWorkaround()
let navBarController = self.window!.rootViewController as UITabBarController
let splitViewController = navBarController.viewControllers![0] as UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.endIndex-1] as UINavigationController
splitViewController.delegate = navigationController.topViewController as DetailViewController
return true
}
}
| mit |
sbcmadn1/swift | swiftweibo05/GZWeibo05/Class/Model/CZUser.swift | 2 | 1712 | //
// CZUser.swift
// GZWeibo05
//
// Created by zhangping on 15/10/31.
// Copyright © 2015年 zhangping. All rights reserved.
//
import UIKit
class CZUser: NSObject {
/// 字符串型的用户UID
var idstr: String?
/// 友好显示名称
var name: String?
/// 用户头像地址(中图),50×50像素
var profile_image_url: String?
/// verified_type 没有认证:-1 认证用户:0 企业认证:2,3,5 达人:220
var verified_type: Int = -1
var verifiedTypeImage: UIImage? {
switch verified_type {
case 0:
return UIImage(named: "avatar_vip")
case 2,3,5:
return UIImage(named: "avatar_enterprise_vip")
case 220:
return UIImage(named: "avatar_grassroot")
default:
return nil
}
}
/// 会员等级 1-6
var mbrank: Int = 0
// 计算型属性,根据不同会员等级返回不同的图片
var mbrankImage: UIImage? {
if mbrank > 0 && mbrank <= 6 {
return UIImage(named: "common_icon_membership_level\(mbrank)")
}
return nil
}
/// 字典转模型
init(dict: [String: AnyObject]) {
super.init()
// KVC赋值
setValuesForKeysWithDictionary(dict)
}
// 字典的key在模型中找不到
override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
/// 对象的打印
override var description: String {
let properties = ["idstr", "name", "profile_image_url", "verified_type", "mbrank"]
return "\n\t用户模型:\(dictionaryWithValuesForKeys(properties))"
}
}
| mit |
jinyuli/RequestQueue | RequestQueueTests/RequestQueueTest.swift | 1 | 7699 | //
// RequestQueueTest.swift
// Queue
//
// Created by Jamse Li on 10/12/15.
// Copyright © 2015 eLivingStore. All rights reserved.
//
import Foundation
import XCTest
@testable import RequestQueue
class RequestQueueTest: XCTestCase {
typealias StringQueue = RequestQueue<String>
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testAdd() {
let op: StringQueue.Operation = {(key: String, callback: StringQueue.OperationCallback) in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
NSThread.sleepForTimeInterval(3)
callback(key:key, result:nil, error:nil, context:nil)
})
}
let queue = StringQueue(op: op)
let expect = expectationWithDescription("wait for queue")
let key = "test1"
let value:StringQueue.OperationCallback = {(returnedKey:String, result:Any?, error:NSError?, context:Any?) in
XCTAssertEqual(returnedKey, key, "should be the same key")
expect.fulfill()
}
queue.add(key, value: value)
queue.queue.addOperationWithBlock { () -> Void in
XCTAssertEqual(1, queue.map.count, "should be only 1 element in the queue")
}
waitForExpectationsWithTimeout(5) { (error:NSError?) -> Void in
XCTAssertEqual(0, queue.map.count, "should be 0 now")
}
}
func testRetry() {
var retry:Int = 0;
let op: StringQueue.Operation = {(key: String, callback: StringQueue.OperationCallback) in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
NSThread.sleepForTimeInterval(2)
//fail for the first time
if retry == 0 {
callback(key:key, result:nil, error:NSError(domain: "test", code: 100, userInfo: nil), context:nil)
retry = 1
} else {
callback(key:key, result:nil, error:nil, context:nil)
}
})
}
let queue = StringQueue(op: op, concurrentCount:1, maxRetryTimes:1)
let expect = expectationWithDescription("wait for queue")
let key = "test1"
let value:StringQueue.OperationCallback = {(returnedKey:String, result:Any?, error:NSError?, context:Any?) in
XCTAssertEqual(returnedKey, key, "should be the same key")
expect.fulfill()
}
queue.add(key, value: value)
queue.queue.addOperationWithBlock { () -> Void in
XCTAssertEqual(1, queue.map.count, "should be only 1 element in the queue")
}
waitForExpectationsWithTimeout(5) { (error:NSError?) -> Void in
XCTAssertEqual(retry, 1, "should be retried")
XCTAssertEqual(0, queue.map.count, "should be 0 now")
}
}
func testNoRetry() {
var retry:Int = 0;
let op: StringQueue.Operation = {(key: String, callback: StringQueue.OperationCallback) in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
NSThread.sleepForTimeInterval(2)
//fail for the first time
if retry == 0 {
retry = 1
callback(key:key, result:nil, error:NSError(domain: "test", code: 100, userInfo: nil), context:nil)
} else {
retry = 2
callback(key:key, result:nil, error:nil, context:nil)
}
})
}
let queue = StringQueue(op: op, concurrentCount:1, maxRetryTimes:0)
let expect = expectationWithDescription("wait for queue")
let key = "test1"
let value:StringQueue.OperationCallback = {(returnedKey:String, result:Any?, error:NSError?, context:Any?) in
XCTAssertEqual(returnedKey, key, "should be the same key")
expect.fulfill()
}
queue.add(key, value: value)
queue.queue.addOperationWithBlock { () -> Void in
XCTAssertEqual(1, queue.map.count, "should be only 1 element in the queue")
}
waitForExpectationsWithTimeout(5) { (error:NSError?) -> Void in
XCTAssertEqual(retry, 1, "should be no retry")
XCTAssertEqual(0, queue.map.count, "should be 0 now")
}
}
func testAdd_Remove() {
let op: StringQueue.Operation = {(key: String, callback: StringQueue.OperationCallback) in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
NSThread.sleepForTimeInterval(3)
callback(key:key, result:nil, error:nil, context:nil)
})
}
let queue = StringQueue(op: op, concurrentCount:1)
let expect = expectationWithDescription("wait for queue")
let key = "test1"
let value:StringQueue.OperationCallback = {(returnedKey:String, result:Any?, error:NSError?, context:Any?) in
XCTAssertEqual(returnedKey, key, "should be the same key")
expect.fulfill()
}
let key2 = "test2"
let value2:StringQueue.OperationCallback = {(returnedKey:String, result:Any?, error:NSError?, context:Any?) in
XCTAssertEqual(returnedKey, key2, "should be the same key")
expect.fulfill()
}
queue.add(key, value: value)
queue.add(key2, value: value2)
queue.queue.addOperationWithBlock { () -> Void in
XCTAssertEqual(2, queue.map.count, "should be two elements in the queue")
}
//remove one before it's executed
queue.remove(key2)
queue.queue.addOperationWithBlock { () -> Void in
XCTAssertEqual(1, queue.map.count, "should be only 1 element in the queue")
}
waitForExpectationsWithTimeout(5) { (error:NSError?) -> Void in
XCTAssertEqual(0, queue.map.count, "should be 0 now")
}
}
func testRemoveAll() {
let op: StringQueue.Operation = {(key: String, callback: StringQueue.OperationCallback) in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
NSThread.sleepForTimeInterval(3)
callback(key:key, result:nil, error:nil, context:nil)
})
}
let queue = StringQueue(op: op)
let key = "test1"
let value:StringQueue.OperationCallback = {(returnedKey:String, result:Any?, error:NSError?, context:Any?) in
XCTFail("should have been removed, no callback")
}
queue.add(key, value: value)
queue.queue.addOperationWithBlock { () -> Void in
XCTAssertEqual(1, queue.map.count, "should be only 1 element in the queue")
}
queue.removeAll()
queue.queue.addOperationWithBlock { () -> Void in
XCTAssertEqual(0, queue.map.count, "should be no element in the queue")
}
NSThread.sleepForTimeInterval(4)//wait for enough time
}
func testPerformance() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| apache-2.0 |
FirebaseExtended/mlkit-material-ios | ShowcaseApp/ShowcaseAppSwiftTests/ShowcaseAppSwiftTests.swift | 1 | 1380 | /**
* Copyright 2019 Google ML Kit team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import XCTest
@testable import ShowcaseAppSwift
class ShowcaseAppSwiftTests: XCTestCase {
override func 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.
}
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 |
ahoppen/swift | test/Interop/Cxx/class/inline-function-codegen/constructor-calls-method-execution.swift | 8 | 339 | // RUN: %target-run-simple-swift(-I %S/Inputs -Xfrontend -enable-experimental-cxx-interop)
//
// REQUIRES: executable_test
import ConstructorCallsMethod
import StdlibUnittest
var MembersTestSuite = TestSuite("MembersTestSuite")
MembersTestSuite.test("constructor calls method") {
expectEqual(42, callConstructor(41))
}
runAllTests()
| apache-2.0 |
tripleCC/GanHuoCode | GanHuo/Models/GanHuoObject.swift | 1 | 4631 | //
// GanHuoObject.swift
//
//
// Created by tripleCC on 16/3/4.
//
//
import Foundation
import CoreData
import SwiftyJSON
//@objc(GanHuoObject)
/* http://stackoverflow.com/questions/25076276/unable-to-find-specific-subclass-of-nsmanagedobject */
public final class GanHuoObject: NSManagedObject ,TPCCoreDataHelper {
public typealias RawType = [String : JSON]
static var queryString = ""
static var sortString = "publishedAt"
static var ascending = false
static var fetchOffset = 0
static var fetchLimit = TPCLoadGanHuoDataOnce
static var request: NSFetchRequest {
let fetchRequest = NSFetchRequest(entityName: entityName)
fetchRequest.fetchLimit = fetchLimit
fetchRequest.fetchBatchSize = 20;
fetchRequest.fetchOffset = fetchOffset
if queryString.characters.count > 0 {
let predicate = NSPredicate(format: queryString)
fetchRequest.predicate = predicate
}
fetchRequest.sortDescriptors = [NSSortDescriptor(key: sortString, ascending: ascending)]
return fetchRequest
}
init(context: NSManagedObjectContext, dict: RawType) {
let entity = NSEntityDescription.entityForName(GanHuoObject.entityName, inManagedObjectContext: context)!
super.init(entity: entity, insertIntoManagedObjectContext: context)
initializeWithRawType(dict)
}
@objc
private override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
static func insertObjectInBackgroundContext(dict: RawType) -> GanHuoObject {
if let id = dict["_id"]?.stringValue {
let results = fetchById(id)
if let ganhuo = results.first {
ganhuo.initializeWithRawType(dict)
return ganhuo
}
}
return GanHuoObject(dict: dict)
}
// static func insertObjectToContext(context: NSManagedObjectContext, dict: RawType) {
// let ganhuo = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: context) as! GanHuoObject
// ganhuo.initializeWithRawType(dict)
// }
convenience init(dict: RawType) {
self.init(context: TPCCoreDataManager.shareInstance.backgroundManagedObjectContext, dict: dict)
}
func initializeWithRawType(dict: RawType) {
who = dict["who"]?.stringValue ?? ""
publishedAt = dict["publishedAt"]?.stringValue ?? ""
objectId = dict["_id"]?.stringValue ?? ""
used = dict["used"]?.numberValue ?? NSNumber()
type = dict["type"]?.stringValue ?? ""
createdAt = dict["createdAt"]?.stringValue ?? ""
desc = TPCTextParser.shareTextParser.parseOriginString(dict["desc"]?.stringValue ?? "")
url = dict["url"]?.stringValue ?? ""
TPCInAppSearchUtil.indexedItemWithType(type!, who: who!, contentDescription: desc!, uniqueIdentifier: url!)
calculateCellHeight()
}
private func calculateCellHeight() {
cellHeight = TPCCategoryTableViewCell.cellHeightWithGanHuo(self)
}
}
typealias GanHuoObjectFetch = GanHuoObject
extension GanHuoObjectFetch {
static func fetchByTime(time: (year: Int, month: Int, day: Int)) -> [GanHuoObject] {
queryString = String(format: "publishedAt CONTAINS '%04ld-%02ld-%02ld'", time.year, time.month, time.day)
return fetchInBackgroundContext()
}
static func fetchById(id: String) -> [GanHuoObject] {
queryString = "objectId == '\(id)'"
return fetchInBackgroundContext()
}
static func fetchByCategory(category: String?, offset: Int) -> [GanHuoObject] {
if let category = category {
queryString = "type == '\(category)'"
} else {
queryString = ""
}
fetchOffset = offset
fetchLimit = TPCLoadGanHuoDataOnce
return fetchInBackgroundContext()
}
static func fetchFavorite() -> [GanHuoObject] {
queryString = "favorite == \(NSNumber(bool: true))"
sortString = "favoriteAt"
fetchLimit = 1000
return fetchInBackgroundContext()
}
static func fetchSearchResultsByKey(key: String) -> [GanHuoObject] {
queryString = "desc CONTAINS '\(key)' "
fetchLimit = 1000
return fetchInBackgroundContext()
}
}
infix operator !? { }
func !?<T: StringLiteralConvertible> (wrapped: T?, @autoclosure failureText: ()->String) -> T {
assert(wrapped != nil, failureText)
return wrapped ?? ""
}
| mit |
bingoogolapple/SwiftNote-PartOne | 多个自定义单元格-Storyboard/多个自定义单元格-Storyboard/ViewController.swift | 1 | 2022 | //
// ViewController.swift
// 多个自定义单元格-Storyboard
//
// Created by bingoogol on 14/9/27.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
class ViewController: UITableViewController {
var dataList:NSArray!
let MY_CELL_ID = "MyCell"
let HER_CELL_ID = "HerCell"
override func viewDidLoad() {
super.viewDidLoad()
var path = NSBundle.mainBundle().pathForResource("messages", ofType: "plist")
dataList = NSArray(contentsOfFile: path!)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var dict = dataList[indexPath.row] as NSDictionary
var fromSelf = dict["fromSelf"]!.boolValue as Bool
var cell:UITableViewCell
var button:UIButton
if fromSelf {
cell = tableView.dequeueReusableCellWithIdentifier(MY_CELL_ID) as UITableViewCell
button = cell.viewWithTag(100) as UIButton
button.setBackgroundImage(UIImage(named: "chatto_bg_normal.png"), forState: UIControlState.Normal)
button.setBackgroundImage(UIImage(named: "chatto_bg_focused.png"), forState: UIControlState.Highlighted)
} else {
cell = tableView.dequeueReusableCellWithIdentifier(HER_CELL_ID) as UITableViewCell
button = cell.viewWithTag(100) as UIButton
button.setBackgroundImage(UIImage(named: "chatfrom_bg_normal.png"), forState: UIControlState.Normal)
button.setBackgroundImage(UIImage(named: "chatfrom_bg_focused.png"), forState: UIControlState.Highlighted)
}
button.titleLabel?.text = dict["content"] as NSString
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80
}
} | apache-2.0 |
dreamsxin/swift | validation-test/compiler_crashers_fixed/01325-swift-typebase-isequal.swift | 11 | 463 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
extension Array {
let f = b([0x31] = T, A = {
}
class A {
}
protocol A
| apache-2.0 |
salemoh/GoldenQuraniOS | GoldenQuranSwift/GoldenQuranSwift/SearchViewController.swift | 1 | 7180 | //
// SearchViewController.swift
// GoldenQuranSwift
//
// Created by Omar Fraiwan on 4/13/17.
// Copyright © 2017 Omar Fraiwan. All rights reserved.
//
import UIKit
enum SearchType:Int {
case verse = 1
case topic
case mojam
}
class SearchViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var segmntedControl: GQSegmentedControl!
var currentSearchType:SearchType = .verse
var searchResults = [SearchResult]()
override func viewDidLoad() {
super.viewDidLoad()
let closeBtnItem = UIBarButtonItem(title:NSLocalizedString("CLOSE", comment: ""),style:.plain , target:self , action:#selector(self.closePressed))
self.navigationItem.setLeftBarButtonItems([closeBtnItem], animated: true)
// Do any additional setup after loading the view.
self.title = NSLocalizedString("SEARCH_TITLE", comment: "")
tableView.keyboardDismissMode = .onDrag
tableView.estimatedRowHeight = 50
tableView.estimatedSectionHeaderHeight = 40
self.searchBar.becomeFirstResponder()
segmntedControl.setTitle(NSLocalizedString("SEARCH_MUSHAF_VERSES_SEGMENT", comment: "") , forSegmentAt: 0)
segmntedControl.setTitle(NSLocalizedString("SEARCH_MUSHAF_TOPICS_SEGMENT", comment: ""), forSegmentAt: 1)
segmntedControl.setTitle(NSLocalizedString("SEARCH_MUSHAF_MO3JAM_SEGMENT", comment: ""), forSegmentAt: 2)
updateToNewSearchMethod()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func closePressed(){
self.searchBar.resignFirstResponder()
self.dismiss(animated: true, completion: nil)
}
@IBAction func searchSegmentChanged(_ sender: GQSegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
currentSearchType = .verse
case 1:
currentSearchType = .topic
case 2:
currentSearchType = .mojam
default:
currentSearchType = .verse
}
updateToNewSearchMethod()
}
func updateToNewSearchMethod(){
switch currentSearchType {
case .verse:
currentSearchType = .verse
self.searchBar.placeholder = NSLocalizedString("SEARCH_MUSHAF_VERSES_PLACEHOLDER", comment: "")
case .topic:
currentSearchType = .topic
self.searchBar.placeholder = NSLocalizedString("SEARCH_MUSHAF_TOPICS_PLACEHOLDER", comment: "")
case .mojam:
currentSearchType = .mojam
self.searchBar.placeholder = NSLocalizedString("SEARCH_MUSHAF_MO3JAM_PLACEHOLDER", comment: "")
}
doSearch()
}
func doSearch(){
guard let query = self.searchBar.text, query.characters.count > 0 else {
return
}
switch currentSearchType {
case .verse:
searchResults = DBManager.shared.searchMushafVerse(keyword: query);
case .topic:
searchResults = DBManager.shared.searchMushafByTopic(keyword: query);
case .mojam:
searchResults = DBManager.shared.searchMushafMo3jam(keyword: query);
}
self.tableView.reloadData()
}
/*
// 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.
}
*/
}
extension SearchViewController:UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.characters.count >= 3 {
doSearch()
}
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
if let _ = searchBar.text {
doSearch()
}
searchBar.resignFirstResponder()
}
}
extension SearchViewController:UITableViewDelegate{
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
/// Navigate to search data
}
}
extension SearchViewController:UITableViewDataSource {
//SearchVerseTableViewCell
//SearchTopicTableViewCell
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cell = tableView.dequeueReusableCell(withIdentifier: "SearchHeaderTableViewCell") as! SearchHeaderTableViewCell
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
let str = String(formatter.string(from: NSNumber(value: searchResults.count))!)
cell.lblResultsCount.text = String(format: NSLocalizedString("SEARCH_RESULTS_%@", comment: ""), str!).correctLanguageNumbers()
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return searchResults.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
switch currentSearchType {
case .topic:
let cell = tableView.dequeueReusableCell(withIdentifier: "SearchTopicTableViewCell") as! SearchTopicTableViewCell
let searchResult = searchResults[indexPath.row]
let sora = String(format:"Sora%d" , searchResult.soraNo!)
cell.lblTo.text = NSLocalizedString("SEARCH_TO", comment: "")
cell.lblSora.text = NSLocalizedString( sora , comment: "")
cell.lblFromVerse.text = String(format:"%d", searchResult.fromVerse!).correctLanguageNumbers()
cell.lblToVerse.text = String(format:"%d", searchResult.toVerse!).correctLanguageNumbers()
cell.lblSearchContent.text = searchResult.content
// cell.setNeedsLayout()
return cell
default:
let cell = tableView.dequeueReusableCell(withIdentifier: "SearchVerseTableViewCell") as! SearchVerseTableViewCell
let searchResult = searchResults[indexPath.row]
let sora = String(format:"Sora%d" , searchResult.soraNo!)
cell.lblSearchSora.text = NSLocalizedString( sora , comment: "")
cell.lblSearchVerse.text = String(format:"%d", searchResult.fromVerse!).correctLanguageNumbers()
cell.lblSearchContent.text = searchResult.content
// cell.setNeedsLayout()
return cell
}
}
}
| mit |
cenfoiOS/ImpesaiOSCourse | CleanSwiftExample/CleanSwiftExample/Scenes/ToDoTasksList/ToDoTasksListViewController.swift | 1 | 2901 | //
// ToDoTasksListViewController.swift
// CleanSwiftExample
//
// Created by Cesar Brenes on 6/6/17.
// Copyright (c) 2017 César Brenes Solano. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so you can apply
// clean architecture to your iOS and Mac projects, see http://clean-swift.com
//
import UIKit
protocol ToDoTasksListViewControllerInput{
func displayTestInformation(viewModel: ToDoTasksList.TestInformation.ViewModel)
func displayDataSource(viewModel: ToDoTasksList.DataSource.ViewModel)
}
protocol ToDoTasksListViewControllerOutput{
func requestTestInformation(request: ToDoTasksList.TestInformation.Request)
func requestDataSource(request: ToDoTasksList.DataSource.Request)
}
class ToDoTasksListViewController: UIViewController, ToDoTasksListViewControllerInput{
var output: ToDoTasksListViewControllerOutput!
var router: ToDoTasksListRouter!
var taskArray: [ToDoTasksList.TaskModelCell] = []
@IBOutlet weak var tableView: UITableView!
// MARK: Object lifecycle
override func awakeFromNib(){
super.awakeFromNib()
ToDoTasksListConfigurator.sharedInstance.configure(viewController: self)
}
// MARK: View lifecycle
override func viewDidLoad(){
super.viewDidLoad()
requestTestInformation(number: "5")
requestDataSource()
registerCustomCell()
}
// MARK: Event handling
func requestTestInformation(number: String){
let request = ToDoTasksList.TestInformation.Request(numberText: number)
output.requestTestInformation(request: request)
}
func requestDataSource(){
let request = ToDoTasksList.DataSource.Request()
output.requestDataSource(request: request)
}
func displayDataSource(viewModel: ToDoTasksList.DataSource.ViewModel){
print("ARRAY SIZE: \(viewModel.tasks.count)")
taskArray = viewModel.tasks
tableView.reloadData()
}
// MARK: Display logic
func displayTestInformation(viewModel: ToDoTasksList.TestInformation.ViewModel){
print("EL RESULTADO ES \(viewModel.numberText)")
}
}
extension ToDoTasksListViewController: UITableViewDataSource, UITableViewDelegate{
func registerCustomCell(){
let nib = UINib(nibName: "ToDoListCustomCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "ToDoListCustomCell")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return taskArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoListCustomCell") as! ToDoListCustomCell
cell.setupCell(task: taskArray[indexPath.row])
return cell
}
}
| mit |
emilstahl/swift | test/expr/closure/anonymous.swift | 14 | 258 | // RUN: %target-parse-verify-swift
func takeIntToInt(f: (Int) -> Int) { }
func takeIntIntToInt(f: (Int, Int) -> Int) { }
// Simple closures with anonymous arguments
func simple() {
takeIntToInt({return $0 + 1})
takeIntIntToInt({return $0 + $1 + 1})
}
| apache-2.0 |
LockLight/Weibo_Demo | SinaWeibo/SinaWeibo/Classes/View/PhotoBrowser(图片浏览器)/WBPhotoBrowserController.swift | 1 | 2982 | //
// WBPhotoBrowserController.swift
// SinaWeibo
//
// Created by locklight on 17/4/9.
// Copyright © 2017年 LockLight. All rights reserved.
//
import UIKit
class WBPhotoBrowserController: UIViewController {
//当前展示图片的index
var index:Int = 0
//图片的url数组
var pic_urlArr:[String] = []
//重载构造函数,设置所需参数
init(index:Int, pic_urlArr:[String]){
super.init(nibName: nil, bundle: nil)
self.index = index
self.pic_urlArr = pic_urlArr
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.randomColor()
setupUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension WBPhotoBrowserController{
func setupUI(){
//创建分页控制器
let pageVC = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: [UIPageViewControllerOptionInterPageSpacingKey:20])
//添加到当前控制器
self.addChildViewController(pageVC)
self.view.addSubview(pageVC.view)
pageVC.didMove(toParentViewController: self)
//设置分页控制器的子控制器
let photoViewerVC = WBPhotoViewerController(index: index, pic_urlArr: pic_urlArr)
pageVC.setViewControllers([photoViewerVC], direction: .forward, animated: true, completion: nil)
pageVC.dataSource = self
let tap = UITapGestureRecognizer(target: self, action: #selector(back))
self.view.addGestureRecognizer(tap)
}
func back(){
self.dismiss(animated: false, completion: nil)
}
}
//MARK - 分页控制器的数据源方法
extension WBPhotoBrowserController:UIPageViewControllerDataSource{
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
let currentIndex = (viewController as! WBPhotoViewerController).index
//到头
if(currentIndex == 0){
return nil
}
let photoViewer = WBPhotoViewerController(index: currentIndex - 1, pic_urlArr: pic_urlArr)
return photoViewer
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
let currentIndex = (viewController as! WBPhotoViewerController).index
//到尾
if(currentIndex == pic_urlArr.count - 1){
return nil
}
let photoViewer = WBPhotoViewerController(index: currentIndex + 1, pic_urlArr: pic_urlArr)
return photoViewer
}
}
| mit |
MaxHasADHD/TraktKit | Tests/TraktKitTests/ScrobbleTests.swift | 1 | 3673 | //
// ScrobbleTests.swift
// TraktKitTests
//
// Created by Maximilian Litteral on 3/29/18.
// Copyright © 2018 Maximilian Litteral. All rights reserved.
//
import XCTest
@testable import TraktKit
class ScrobbleTests: XCTestCase {
let session = MockURLSession()
lazy var traktManager = TestTraktManager(session: session)
override func tearDown() {
super.tearDown()
session.nextData = nil
session.nextStatusCode = StatusCodes.Success
session.nextError = nil
}
// MARK: - Start
func test_start_watching_in_media_center() {
session.nextData = jsonData(named: "test_start_watching_in_media_center")
session.nextStatusCode = StatusCodes.SuccessNewResourceCreated
let expectation = XCTestExpectation(description: "Start watching in media center")
let scrobble = TraktScrobble(movie: SyncId(trakt: 12345), progress: 1.25)
try! traktManager.scrobbleStart(scrobble) { result in
if case .success(let response) = result {
XCTAssertEqual(response.action, "start")
XCTAssertEqual(response.progress, 1.25)
XCTAssertNotNil(response.movie)
expectation.fulfill()
}
}
let result = XCTWaiter().wait(for: [expectation], timeout: 1)
XCTAssertEqual(session.lastURL?.absoluteString, "https://api.trakt.tv/scrobble/start")
switch result {
case .timedOut:
XCTFail("Something isn't working")
default:
break
}
}
// MARK: - Pause
func test_pause_watching_in_media_center() {
session.nextData = jsonData(named: "test_pause_watching_in_media_center")
session.nextStatusCode = StatusCodes.SuccessNewResourceCreated
let expectation = XCTestExpectation(description: "Pause watching in media center")
let scrobble = TraktScrobble(movie: SyncId(trakt: 12345), progress: 75)
try! traktManager.scrobblePause(scrobble) { result in
if case .success(let response) = result {
XCTAssertEqual(response.action, "pause")
XCTAssertEqual(response.progress, 75)
XCTAssertNotNil(response.movie)
expectation.fulfill()
}
}
let result = XCTWaiter().wait(for: [expectation], timeout: 1)
XCTAssertEqual(session.lastURL?.absoluteString, "https://api.trakt.tv/scrobble/pause")
switch result {
case .timedOut:
XCTFail("Something isn't working")
default:
break
}
}
// MARK: - Stop
func test_stop_watching_in_media_center() {
session.nextData = jsonData(named: "test_stop_watching_in_media_center")
session.nextStatusCode = StatusCodes.SuccessNewResourceCreated
let expectation = XCTestExpectation(description: "Stop watching in media center")
let scrobble = TraktScrobble(movie: SyncId(trakt: 12345), progress: 99.9)
try! traktManager.scrobbleStop(scrobble) { result in
if case .success(let response) = result {
XCTAssertEqual(response.action, "scrobble")
XCTAssertEqual(response.progress, 99.9)
XCTAssertNotNil(response.movie)
expectation.fulfill()
}
}
let result = XCTWaiter().wait(for: [expectation], timeout: 1)
XCTAssertEqual(session.lastURL?.absoluteString, "https://api.trakt.tv/scrobble/stop")
switch result {
case .timedOut:
XCTFail("Something isn't working")
default:
break
}
}
}
| mit |
ben-ng/swift | validation-test/compiler_crashers/28368-swift-expr-propagatelvalueaccesskind.swift | 1 | 427 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not --crash %target-swift-frontend %s -typecheck
guard let f=.h.a=[]{
| apache-2.0 |
andreyvit/ATCocoaLabs | CommonTests/PrecisionReductionTests.swift | 1 | 2211 | import Foundation
import XCTest
import ATCocoaLabs
class PrecisionReductionTests: XCTestCase {
func test0_1() {
XCTAssertEqual(ReducedPrecisionRange(value: 0).description, "0", "Pass")
XCTAssertEqual(ReducedPrecisionRange(value: 1).description, "1", "Pass")
}
func test2_9() {
XCTAssertEqual(ReducedPrecisionRange(value: 2).description, "2-9", "Pass")
XCTAssertEqual(ReducedPrecisionRange(value: 3).description, "2-9", "Pass")
XCTAssertEqual(ReducedPrecisionRange(value: 8).description, "2-9", "Pass")
XCTAssertEqual(ReducedPrecisionRange(value: 9).description, "2-9", "Pass")
}
func test10_29() {
XCTAssertEqual(ReducedPrecisionRange(value: 10).description, "10-29", "Pass")
XCTAssertEqual(ReducedPrecisionRange(value: 11).description, "10-29", "Pass")
XCTAssertEqual(ReducedPrecisionRange(value: 28).description, "10-29", "Pass")
XCTAssertEqual(ReducedPrecisionRange(value: 29).description, "10-29", "Pass")
}
func test30_99() {
XCTAssertEqual(ReducedPrecisionRange(value: 30).description, "30-99", "Pass")
XCTAssertEqual(ReducedPrecisionRange(value: 31).description, "30-99", "Pass")
XCTAssertEqual(ReducedPrecisionRange(value: 98).description, "30-99", "Pass")
XCTAssertEqual(ReducedPrecisionRange(value: 99).description, "30-99", "Pass")
}
func test100_999() {
XCTAssertEqual(ReducedPrecisionRange(value: 100).description, "100-999", "Pass")
XCTAssertEqual(ReducedPrecisionRange(value: 101).description, "100-999", "Pass")
XCTAssertEqual(ReducedPrecisionRange(value: 998).description, "100-999", "Pass")
XCTAssertEqual(ReducedPrecisionRange(value: 999).description, "100-999", "Pass")
}
func test1000_9999() {
XCTAssertEqual(ReducedPrecisionRange(value: 1000).description, "1000-9999", "Pass")
XCTAssertEqual(ReducedPrecisionRange(value: 1001).description, "1000-9999", "Pass")
XCTAssertEqual(ReducedPrecisionRange(value: 9998).description, "1000-9999", "Pass")
XCTAssertEqual(ReducedPrecisionRange(value: 9999).description, "1000-9999", "Pass")
}
}
| mit |
ben-ng/swift | validation-test/compiler_crashers_fixed/26650-swift-protocoltype-canonicalizeprotocols.swift | 1 | 477 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
{
struct a{struct a{func a{{{
func a{
{{
struct B{
class b{deinit{
class
case,
| apache-2.0 |
abdullah-chhatra/iDispatch | iDispatch/iDispatch/DispatchGroup.swift | 1 | 3450 | //
// DispatchGroup.swift
// DispatchQueue
//
// Created by Abdulmunaf Chhatra on 4/3/15.
// Copyright (c) 2015 Abdulmunaf Chhatra. All rights reserved.
//
import Foundation
/**
Represents a dispatch group.
*/
public class DispatchGroup {
let group: dispatch_group_t
var asyncQueue: DispatchQueue?
/**
Designated initializer that creates a new GCD dispatch group.
*/
public init() {
group = dispatch_group_create()
}
/**
Designated initializer that creates a new GCD dispatch group. The queue passed to it
will be used to executes async block for this group.
:param: asyncQueue This queue will be used to execute async blocks for this group.
*/
public init(asyncQueue: DispatchQueue) {
group = dispatch_group_create()
self.asyncQueue = asyncQueue
}
public func enter() {
dispatch_group_enter(group)
}
public func leave() {
dispatch_group_leave(group)
}
/**
Executes the block synchronously on the current thread. It will enter group before executing
the block and leave group after the block is finished.
:param: block Block to be executed.
*/
public func dispatchSync(block: dispatch_block_t) {
enter()
block()
leave()
}
/**
Dispatches the block asynchronously on its designated async queue.
:param: block Block to be executed.
*/
public func dispatchAsync(block: dispatch_block_t) {
if let queue = asyncQueue {
dispatch_group_async(group, queue.queue, block)
} else {
assertionFailure("No async queue is set for this group")
}
}
/**
Dispatches the block asynchronously on specified queue.
:param: block Block to be executed.
*/
public func dispatchAsyncOnQueue(queue: DispatchQueue, block: dispatch_block_t) {
dispatch_group_async(group, queue.queue, block)
}
/**
Waits for number of seconds for the group to finish.
:param: seconds Nubmer of seconds to wait for the group to finish.
:returns: True if group returns before specified seconds, false otherwise.
*/
public func waitForSeconds(seconds: UInt) -> Bool {
return dispatch_group_wait(group, SecondsFromNow(seconds)) == 0
}
/**
Waits forever for the group to finish.
*/
public func waitForever() -> Bool {
return dispatch_group_wait(group, DISPATCH_TIME_FOREVER) == 0
}
/**
Schedules a block to be submitted to specified queue when the group finishes.
:param: queue Queue on wich the block is to be submitted.
:param: block Completion block that is to be called.
*/
public func notifyOnQueue(queue: DispatchQueue, block: dispatch_block_t) {
dispatch_group_notify(group, queue.queue, block)
}
/**
Schedules a block to be submitted to designated async queue when the group finishes.
:param: block Completion block that is to be called.
*/
public func notify(block: dispatch_block_t) {
if let queue = asyncQueue {
dispatch_group_notify(group, queue.queue, block)
} else {
assertionFailure("No async queue is set for this group")
}
}
} | mit |
josve05a/wikipedia-ios | Wikipedia/Code/PageIssuesTableViewController.swift | 2 | 2710 | import UIKit
@objc(WMFPageIssuesTableViewController)
class PageIssuesTableViewController: UITableViewController {
static let defaultViewCellReuseIdentifier = "org.wikimedia.default"
fileprivate var theme = Theme.standard
@objc var issues = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.title = WMFLocalizedString("page-issues", value: "Page issues", comment: "Label for the button that shows the \"Page issues\" dialog, where information about the imperfections of the current page is provided (by displaying the warning/cleanup templates). {{Identical|Page issue}}")
self.tableView.estimatedRowHeight = 90.0
self.tableView.rowHeight = UITableView.automaticDimension
self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: PageIssuesTableViewController.defaultViewCellReuseIdentifier)
let xButton = UIBarButtonItem.wmf_buttonType(WMFButtonType.X, target: self, action: #selector(closeButtonPressed))
self.navigationItem.leftBarButtonItem = xButton
apply(theme: self.theme)
}
@objc func closeButtonPressed() {
self.presentingViewController?.dismiss(animated: true, completion: nil)
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: PageIssuesTableViewController.defaultViewCellReuseIdentifier, for: indexPath)
cell.textLabel?.numberOfLines = 0
cell.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
cell.textLabel?.text = issues[indexPath.row]
cell.isUserInteractionEnabled = false
cell.backgroundColor = self.theme.colors.paperBackground
cell.selectedBackgroundView = UIView()
cell.selectedBackgroundView?.backgroundColor = self.theme.colors.midBackground
cell.textLabel?.textColor = self.theme.colors.primaryText
return cell
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return issues.count
}
}
extension PageIssuesTableViewController: Themeable {
public func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
self.tableView.backgroundColor = theme.colors.baseBackground
self.tableView.reloadData()
}
}
| mit |
iOS-mamu/SS | P/Library/Eureka/Tests/OperatorsTest.swift | 1 | 2893 | // OperatorsTest.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2015 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
@testable import Eureka
class OperatorsTest: BaseEurekaTests {
func testOperators() {
// test the operators
var form = Form()
form +++ TextRow("textrow1_ctx")
<<< TextRow("textrow2_ctx")
form = form + (TextRow("textrow3_ctx")
<<< TextRow("textrow4_ctx")
+++ TextRow("textrow5_ctx")
<<< TextRow("textrow6_ctx"))
+ (TextRow("textrow7_ctx")
+++ TextRow("textrow8_ctx"))
XCTAssertEqual(form.count, 5)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 2)
XCTAssertEqual(form[2].count, 2)
form +++ IntRow("introw1_ctx")
form +++ IntRow("introw2_ctx")
<<< IntRow("introw3_ctx")
<<< IntRow("introw4_ctx")
// form:
// text1
// text2
// -----
// text3
// text4
// -----
// text5
// text6
// -----
// text7
// -----
// text8
// -----
// int1
// ----
// int2
// int3
// int4
XCTAssertEqual(form.count, 7)
XCTAssertEqual(form[0].count, 2)
XCTAssertEqual(form[1].count, 2)
XCTAssertEqual(form[2].count, 2)
XCTAssertEqual(form[3].count, 1)
XCTAssertEqual(form[4].count, 1)
XCTAssertEqual(form[5].count, 1)
XCTAssertEqual(form[6].count, 3)
}
}
| mit |
adrfer/swift | validation-test/compiler_crashers_fixed/26605-swift-parser-diagnose.swift | 13 | 255 | // RUN: not %target-swift-frontend %s -parse
// 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 a{var:{protocol A}var b={class
case,
| apache-2.0 |
mrdepth/Neocom | Legacy/Neocom/Neocom/InvMarketGroupsViewController.swift | 2 | 716 | //
// InvMarketGroupsViewController.swift
// Neocom
//
// Created by Artem Shimanski on 11/5/18.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import Foundation
import TreeController
class InvMarketGroupsViewController: TreeViewController<InvMarketGroupsPresenter, SDEInvMarketGroup>, TreeView, SearchableViewController {
override func treeController<T>(_ treeController: TreeController, didSelectRowFor item: T) where T : TreeItem {
super.treeController(treeController, didSelectRowFor: item)
presenter.didSelect(item: item)
}
func searchResultsController() -> UIViewController & UISearchResultsUpdating {
return try! InvTypes.default.instantiate(.marketGroup(input)).get()
}
}
| lgpl-2.1 |
swift365/CFWebView | Example/CFWebView/ViewController.swift | 1 | 661 | //
// ViewController.swift
// CFWebView
//
// Created by chengfei.heng on 11/22/2016.
// Copyright (c) 2016 chengfei.heng. All rights reserved.
//
import UIKit
import CFWebView
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func didClickGotoWebView(){
let webView = CFWebViewController.init(url: "https://www.baidu.com", swiped: false, callbackHandlerName: nil, callbackHandler: nil)
webView.backImage = UIImage(named: "h5_back")
self.navigationController?.pushViewController(webView, animated: true)
}
}
| mit |
AnyPresence/justapis-swift-sdk | Source/CompositedGateway.swift | 1 | 15898 | //
// CompositedGateway.swift
// JustApisSwiftSDK
//
// Created by Andrew Palumbo on 12/9/15.
// Copyright © 2015 AnyPresence. All rights reserved.
//
import Foundation
///
/// Invoked by the CompositedGateway to prepare a request before sending.
///
/// Common use cases of a RequestPreparer might be to:
/// - add default headers
/// - add default query parameters
/// - rewrite a path
/// - serialize data as JSON or XML
///
public protocol RequestPreparer
{
func prepareRequest(request:Request) -> Request
}
///
/// Invoked by the CompositedGateway to process a request after its received
///
/// Common use cases of a ResponseProcessor might be to:
/// - validate the type of a response
/// - interpret application-level error messages
/// - deserialize JSON or XML responses
///
public protocol ResponseProcessor
{
func processResponse(response:Response, callback:ResponseProcessorCallback)
}
public typealias ResponseProcessorCallback = ((response:Response, error:ErrorType?) -> Void)
///
/// Invoked by the CompositedGateway to send the request along the wire
///
/// Common use cases of a NetworkAdapter might be to:
/// - Use a specific network library (Foundation, AFNetworking, etc)
/// - Mock responses
/// - Reference a cache before using network resources
///
public protocol NetworkAdapter
{
func submitRequest(request:Request, gateway:CompositedGateway)
}
///
/// Invoked by the CompositedGateway to save and retrieve responses locally cached responses
///
public protocol CacheProvider
{
/// Called to retrieve a Response from the cache. Should call the callback with nil or the retrieved response
func cachedResponseForIdentifier(identifier:String, callback:CacheProviderCallback)
/// Called to save a Response to the cache. The expiration should be considered a preference, not a guarantee.
func setCachedResponseForIdentifier(identifier:String, response:ResponseProperties, expirationSeconds:UInt)
}
public typealias CacheProviderCallback = ((ResponseProperties?) -> Void)
///
/// A Cache Provider implementation that does nothing. Useful to disable caching without changing your request logic
///
public class NullCacheProvider : CacheProvider
{
public func cachedResponseForIdentifier(identifier: String, callback: CacheProviderCallback) {
return callback(nil)
}
public func setCachedResponseForIdentifier(identifier: String, response: ResponseProperties, expirationSeconds: UInt) {
return
}
}
///
/// Convenience object for configuring a composited gateway. Can be passed into Gateway initializer
///
public struct CompositedGatewayConfiguration
{
var baseUrl:NSURL
var sslCertificate:SSLCertificate? = nil
var defaultRequestProperties:DefaultRequestPropertySet? = nil
var networkAdapter:NetworkAdapter? = nil
var cacheProvider:CacheProvider? = nil
var requestPreparer:RequestPreparer? = nil
var responseProcessor:ResponseProcessor? = nil
public init(baseUrl:NSURL,
sslCertificate:SSLCertificate? = nil,
defaultRequestProperties:DefaultRequestPropertySet? = nil,
requestPreparer:RequestPreparer? = nil,
responseProcessor:ResponseProcessor? = nil,
cacheProvider:CacheProvider? = nil,
networkAdapter:NetworkAdapter? = nil)
{
self.baseUrl = baseUrl
self.sslCertificate = sslCertificate
self.defaultRequestProperties = defaultRequestProperties
self.requestPreparer = requestPreparer
self.responseProcessor = responseProcessor
self.cacheProvider = cacheProvider
self.networkAdapter = networkAdapter
}
}
///
/// Implementation of Gateway protocol that dispatches most details to
/// helper classes.
///
public class CompositedGateway : Gateway
{
public let baseUrl:NSURL
public let sslCertificate:SSLCertificate?
public let defaultRequestProperties:DefaultRequestPropertySet
private let networkAdapter:NetworkAdapter
private let cacheProvider:CacheProvider
private let requestPreparer:RequestPreparer?
private let responseProcessor:ResponseProcessor?
private let contentTypeParser:ContentTypeParser
private var requests:InternalRequestQueue = InternalRequestQueue()
public var pendingRequests:[Request] { return self.requests.pendingRequests }
public var isPaused:Bool { return _isPaused }
private var _isPaused:Bool = true
/// TODO: Make this configurable?
public var maxActiveRequests:Int = 2
///
/// Designated initializer
///
public init(
baseUrl:NSURL,
sslCertificate:SSLCertificate? = nil,
defaultRequestProperties:DefaultRequestPropertySet? = nil,
requestPreparer:RequestPreparer? = nil,
responseProcessor:ResponseProcessor? = nil,
cacheProvider:CacheProvider? = nil,
networkAdapter:NetworkAdapter? = nil
)
{
self.baseUrl = baseUrl
self.sslCertificate = sslCertificate
// Use the GatewayDefaultRequestProperties if none were provided
self.defaultRequestProperties = defaultRequestProperties ?? GatewayDefaultRequestProperties()
self.requestPreparer = requestPreparer
self.responseProcessor = responseProcessor
self.contentTypeParser = ContentTypeParser()
// Use the InMemory Cache Provider if none was provided
self.cacheProvider = cacheProvider ?? InMemoryCacheProvider()
// Use the Foundation Network Adapter if none was provided
self.networkAdapter = networkAdapter ?? FoundationNetworkAdapter(sslCertificate: sslCertificate)
self.resume()
}
///
/// Convenience initializer for use with CompositedGatewayConfiguration
///
public convenience init(configuration:CompositedGatewayConfiguration)
{
self.init(
baseUrl:configuration.baseUrl,
sslCertificate:configuration.sslCertificate,
defaultRequestProperties:configuration.defaultRequestProperties,
requestPreparer:configuration.requestPreparer,
responseProcessor:configuration.responseProcessor,
cacheProvider:configuration.cacheProvider,
networkAdapter:configuration.networkAdapter
)
}
///
/// Pauses the gateway. No more pending requests will be processed until resume() is called.
///
public func pause()
{
self._isPaused = true
// Now that the
}
///
/// Unpauses the gateway. Pending requests will continue being processed.
///
public func resume()
{
self._isPaused = false
self.conditionallyProcessRequestQueue()
}
///
/// Removes a request from this gateway's pending request queue
///
public func cancelRequest(request: Request) -> Bool {
guard let internalRequest = request as? InternalRequest where internalRequest.gateway === self else
{
/// Do nothing. This request wasn't associated with this gateway.
return false
}
return self.requests.cancelPendingRequest(internalRequest)
}
///
/// Takes a Request from the queue and begins processing it if conditions are met
//
private func conditionallyProcessRequestQueue()
{
// If not paused, not already at max active requests, and if there are requests pending
if (false == self._isPaused
&& self.requests.numberActive < self.maxActiveRequests
&& self.requests.numberPending > 0)
{
self.processNextInternalRequest()
}
}
///
/// Sets a ResponseProcessor to run when the given contentType is encountered in a response
///
public func setParser(parser:ResponseProcessor?, contentType:String)
{
if (parser != nil)
{
self.contentTypeParser.contentTypes[contentType] = parser
}
else
{
self.contentTypeParser.contentTypes.removeValueForKey(contentType)
}
}
public func submitRequest(request:RequestProperties, callback:RequestCallback?)
{
let request = self.internalizeRequest(request)
self.submitInternalRequest(request, callback: callback)
}
///
/// Called by CacheProvider or NetworkAdapter once a response is ready
///
public func fulfillRequest(request:Request, response:ResponseProperties?, error:ErrorType?, fromCache:Bool = false)
{
guard let request = request as? InternalRequest else
{
// TODO: THROW serious error. The Request was corrupted!
return
}
// Build the result object
let response:InternalResponse? = (response != nil) ? self.internalizeResponse(response!) : nil
var result:RequestResult = (request:request,
response:response?.retreivedFromCache(fromCache),
error:error)
// Check if there was an error
guard error == nil else
{
self.requests.fulfillRequest(request, result: result)
return
}
// Check if there was no response; that's an error itself!
guard response != nil else
{
// TODO: create meaningful error
result.error = createError(0, context:nil, description:"")
self.requests.fulfillRequest(request, result: result)
return
}
// Compound 0+ response processors for this response
let compoundResponseProcessor = CompoundResponseProcessor()
// Add the content type parser
if request.applyContentTypeParsing
{
compoundResponseProcessor.responseProcessors.append(contentTypeParser)
}
// Add any all-response processor
if let responseProcessor = self.responseProcessor
{
compoundResponseProcessor.responseProcessors.append(responseProcessor)
}
// Run the compound processor in a dispatch group
let responseProcessingDispatchGroup = dispatch_group_create()
dispatch_group_enter(responseProcessingDispatchGroup)
compoundResponseProcessor.processResponse(result.response!,
callback:
{
(response:Response, error:ErrorType?) in
result = (request:request, response:response, error:error)
dispatch_group_leave(responseProcessingDispatchGroup)
}
)
// When the dispatch group is emptied, cache the response and run the callback
dispatch_group_notify(responseProcessingDispatchGroup, dispatch_get_main_queue(), {
if result.error == nil // There's no error
&& result.response != nil // And there is a response
&& !fromCache // And the response isn't already from the cache
&& request.cacheResponseWithExpiration > 0 // And we're supposed to cache it
{
// Cache the response
self.cacheProvider.setCachedResponseForIdentifier(request.cacheIdentifier, response: result.response!, expirationSeconds:request.cacheResponseWithExpiration)
}
// Pass result back to caller
self.requests.fulfillRequest(request, result: result)
// Keep the processor running, if appropriate
self.conditionallyProcessRequestQueue()
})
}
///
/// Wraps raw ResponseProperties as an InternalResponse
///
internal func internalizeResponse(response:ResponseProperties) -> InternalResponse
{
// Downcast to an InternalResponse, or wrap externally prepared properties
var internalResponse:InternalResponse = (response as? InternalResponse) ?? InternalResponse(self, response:response)
if (internalResponse.gateway !== self)
{
// response was prepared for another gateway. Associate it with this one!
internalResponse = internalResponse.gateway(self)
}
return internalResponse
}
///
/// Prepares RequestProperties as an InteralRequest and performs preflight prep
///
internal func internalizeRequest(request:RequestProperties) -> InternalRequest
{
// Downcast to an InternalRequest, or wrap externally prepared properties
var internalRequest:InternalRequest = (request as? InternalRequest) ?? InternalRequest(self, request:request)
if (internalRequest.gateway !== self)
{
// request was prepared for another gateway. Associate it with this one!
internalRequest = internalRequest.gateway(self)
}
return internalRequest
}
///
/// Checks CacheProvider for matching Response or submits InternalRequest to NetworkAdapter
///
private func submitInternalRequest(request:InternalRequest, callback:RequestCallback?)
{
var request = request
// Prepare the request if a preparer is available
if let requestPreparer = self.requestPreparer
{
// TODO?: change interface to something async; may need to do something complex
request = requestPreparer.prepareRequest(request) as! InternalRequest
}
// Add the request to the queue
self.requests.appendRequest(request, callback: callback)
// Keep the queue moving, if appropriate
self.conditionallyProcessRequestQueue()
}
///
/// [Background] Starts processing the next request from the queue
///
private func processNextInternalRequest()
{
guard let request = self.requests.nextRequest() else
{
// No request to process
return
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
if request.allowCachedResponse
{
// Check the cache
self.cacheProvider.cachedResponseForIdentifier(request.cacheIdentifier, callback: {
(response:ResponseProperties?) in
if let response = response
{
// There was a subitably fresh response in the cache. Use it
self.fulfillRequest(request, response: response, error: nil, fromCache:true)
}
else
{
// Otherwise, send the request to the network adapter
self.networkAdapter.submitRequest(request, gateway:self)
}
})
}
else
{
// Ignore anything in the cache, and send the request to the network adapter immediately
self.networkAdapter.submitRequest(request, gateway:self)
}
})
}
}
///
/// Convenience subclass of CompositedGateway that uses the JsonResponseProcessor.
///
public class JsonGateway : CompositedGateway
{
public override init(baseUrl: NSURL, sslCertificate:SSLCertificate? = nil, defaultRequestProperties:DefaultRequestPropertySet? = nil, requestPreparer: RequestPreparer? = nil, responseProcessor:ResponseProcessor? = nil, cacheProvider:CacheProvider? = nil, networkAdapter: NetworkAdapter? = nil)
{
super.init(baseUrl: baseUrl, defaultRequestProperties: defaultRequestProperties, requestPreparer:requestPreparer, responseProcessor:responseProcessor, networkAdapter:networkAdapter)
super.setParser(JsonResponseProcessor(), contentType: "application/json")
}
} | mit |
CombineCommunity/CombineExt | Tests/PrefixDurationTests.swift | 1 | 4720 | //
// PrefixDurationTests.swift
// CombineExtTests
//
// Created by David Ohayon and Jasdev Singh on 24/04/2020.
// Copyright © 2020 Combine Community. All rights reserved.
//
#if !os(watchOS)
import Combine
import CombineExt
import CombineSchedulers
import XCTest
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
final class PrefixDurationTests: XCTestCase {
private var cancellable: AnyCancellable!
func testValueEventInWindow() {
let scheduler = DispatchQueue.test
let subject = PassthroughSubject<Int, Never>()
var results = [Int]()
var completions = [Subscribers.Completion<Never>]()
cancellable = subject
.prefix(duration: 0.5, on: scheduler)
.sink(receiveCompletion: { completions.append($0) },
receiveValue: { results.append($0) })
scheduler.schedule(after: scheduler.now.advanced(by: 0.25)) {
subject.send(1)
}
scheduler.schedule(after: scheduler.now.advanced(by: 1.5)) {
subject.send(2)
}
scheduler.advance(by: 2)
XCTAssertEqual(results, [1])
XCTAssertEqual(completions, [.finished])
}
func testMultipleEventsInAndOutOfWindow() {
let subject = PassthroughSubject<Int, Never>()
let scheduler = DispatchQueue.test
var results = [Int]()
var completions = [Subscribers.Completion<Never>]()
cancellable = subject
.prefix(duration: 0.8, on: scheduler)
.sink(receiveCompletion: { completions.append($0) },
receiveValue: { results.append($0) })
subject.send(1)
scheduler.schedule(after: scheduler.now.advanced(by: 0.25)) {
subject.send(2)
}
scheduler.schedule(after: scheduler.now.advanced(by: 0.4)) {
subject.send(3)
}
scheduler.schedule(after: scheduler.now.advanced(by: 1)) {
subject.send(4)
subject.send(5)
subject.send(completion: .finished)
}
scheduler.advance(by: 2)
XCTAssertEqual(results, [1, 2, 3])
XCTAssertEqual(completions, [.finished])
}
func testNoValueEventsInWindow() {
let subject = PassthroughSubject<Int, Never>()
let scheduler = DispatchQueue.test
var results = [Int]()
var completions = [Subscribers.Completion<Never>]()
cancellable = subject
.prefix(duration: 0.5, on: scheduler)
.sink(receiveCompletion: { completions.append($0 ) },
receiveValue: { results.append($0) })
scheduler.schedule(after: scheduler.now.advanced(by: 1.5)) {
subject.send(1)
}
scheduler.advance(by: 2)
XCTAssertTrue(results.isEmpty)
}
func testFinishedInWindow() {
let subject = PassthroughSubject<Int, Never>()
let scheduler = DispatchQueue.test
var results = [Subscribers.Completion<Never>]()
cancellable = subject
.prefix(duration: 0.5, on: scheduler)
.sink(receiveCompletion: { results.append($0) },
receiveValue: { _ in })
scheduler.schedule(after: scheduler.now.advanced(by: 0.25)) {
subject.send(completion: .finished)
}
scheduler.advance(by: 2)
XCTAssertEqual(results, [.finished])
}
private enum AnError: Error {
case someError
}
func testErrorInWindow() {
let subject = PassthroughSubject<Int, AnError>()
let scheduler = DispatchQueue.test
var results = [Subscribers.Completion<AnError>]()
cancellable = subject
.prefix(duration: 0.5, on: scheduler)
.sink(receiveCompletion: { results.append($0) },
receiveValue: { _ in })
scheduler.schedule(after: scheduler.now.advanced(by: 0.25)) {
subject.send(completion: .failure(.someError))
}
scheduler.advance(by: 2)
XCTAssertEqual(results, [.failure(.someError)])
}
func testErrorEventOutsideWindowDoesntAffectFinishEvent() {
let subject = PassthroughSubject<Int, AnError>()
let scheduler = DispatchQueue.test
var results = [Subscribers.Completion<AnError>]()
cancellable = subject
.prefix(duration: 0.5, on: scheduler)
.sink(receiveCompletion: { results.append($0) },
receiveValue: { _ in })
scheduler.schedule(after: scheduler.now.advanced(by: 0.75)) {
subject.send(completion: .failure(.someError))
}
scheduler.advance(by: 2)
XCTAssertEqual(results, [.finished])
}
}
#endif
| mit |
taka0125/CustomHttpHeadersURLProtocol | Example/CustomHttpHeadersURLProtocolSample/AppDelegate.swift | 1 | 468 | //
// AppDelegate.swift
// CustomHttpHeadersURLProtocolSample
//
// Created by Takahiro Ooishi on 2015/11/21.
// Copyright © 2015年 Takahiro Ooishi. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
return true
}
}
| mit |
SwiftKit/Cuckoo | Source/Matching/Matchable.swift | 2 | 4478 | //
// Matchable.swift
// Cuckoo
//
// Created by Tadeas Kriz on 16/01/16.
// Copyright © 2016 Brightify. All rights reserved.
//
/**
Matchable can be anything that can produce its own parameter matcher.
It is used instead of concrete value for stubbing and verification.
*/
public protocol Matchable {
associatedtype MatchedType
/// Matcher for this instance. This should be an equalTo type of a matcher, but it is not required.
var matcher: ParameterMatcher<MatchedType> { get }
}
public protocol OptionalMatchable {
associatedtype OptionalMatchedType
var optionalMatcher: ParameterMatcher<OptionalMatchedType?> { get }
}
public extension Matchable {
func or<M>(_ otherMatchable: M) -> ParameterMatcher<MatchedType> where M: Matchable, M.MatchedType == MatchedType {
return ParameterMatcher {
return self.matcher.matches($0) || otherMatchable.matcher.matches($0)
}
}
func and<M>(_ otherMatchable: M) -> ParameterMatcher<MatchedType> where M: Matchable, M.MatchedType == MatchedType {
return ParameterMatcher {
return self.matcher.matches($0) && otherMatchable.matcher.matches($0)
}
}
}
extension Optional: Matchable where Wrapped: Matchable, Wrapped.MatchedType == Wrapped {
public typealias MatchedType = Wrapped?
public var matcher: ParameterMatcher<Wrapped?> {
return ParameterMatcher<Wrapped?> { other in
switch (self, other) {
case (.none, .none):
return true
case (.some(let lhs), .some(let rhs)):
return lhs.matcher.matches(rhs)
default:
return false
}
}
}
}
extension Optional: OptionalMatchable where Wrapped: OptionalMatchable, Wrapped.OptionalMatchedType == Wrapped {
public typealias OptionalMatchedType = Wrapped
public var optionalMatcher: ParameterMatcher<Wrapped?> {
return ParameterMatcher<Wrapped?> { other in
switch (self, other) {
case (.none, .none):
return true
case (.some(let lhs), .some(let rhs)):
return lhs.optionalMatcher.matches(rhs)
default:
return false
}
}
}
}
extension Matchable where Self: Equatable {
public var matcher: ParameterMatcher<Self> {
return equal(to: self)
}
}
extension OptionalMatchable where OptionalMatchedType == Self, Self: Equatable {
public var optionalMatcher: ParameterMatcher<OptionalMatchedType?> {
return ParameterMatcher { other in
return Optional(self) == other
}
}
}
extension Bool: Matchable {}
extension Bool: OptionalMatchable {
public typealias OptionalMatchedType = Bool
}
extension String: Matchable {}
extension String: OptionalMatchable {
public typealias OptionalMatchedType = String
}
extension Float: Matchable {}
extension Float: OptionalMatchable {
public typealias OptionalMatchedType = Float
}
extension Double: Matchable {}
extension Double: OptionalMatchable {
public typealias OptionalMatchedType = Double
}
extension Character: Matchable {}
extension Character: OptionalMatchable {
public typealias OptionalMatchedType = Character
}
extension Int: Matchable {}
extension Int: OptionalMatchable {
public typealias OptionalMatchedType = Int
}
extension Int8: Matchable {}
extension Int8: OptionalMatchable {
public typealias OptionalMatchedType = Int8
}
extension Int16: Matchable {}
extension Int16: OptionalMatchable {
public typealias OptionalMatchedType = Int16
}
extension Int32: Matchable {}
extension Int32: OptionalMatchable {
public typealias OptionalMatchedType = Int32
}
extension Int64: Matchable {}
extension Int64: OptionalMatchable {
public typealias OptionalMatchedType = Int64
}
extension UInt: Matchable {}
extension UInt: OptionalMatchable {
public typealias OptionalMatchedType = UInt
}
extension UInt8: Matchable {}
extension UInt8: OptionalMatchable {
public typealias OptionalMatchedType = UInt8
}
extension UInt16: Matchable {}
extension UInt16: OptionalMatchable {
public typealias OptionalMatchedType = UInt16
}
extension UInt32: Matchable {}
extension UInt32: OptionalMatchable {
public typealias OptionalMatchedType = UInt32
}
extension UInt64: Matchable {}
extension UInt64: OptionalMatchable {
public typealias OptionalMatchedType = UInt64
}
| mit |
mcrollin/safecaster | safecaster/SCRSafecastAPIRouter.swift | 1 | 3406 | //
// SCRSafecastAPIRouter.swift
// safecaster
//
// Created by Marc Rollin on 3/24/15.
// Copyright (c) 2015 safecast. All rights reserved.
//
import Foundation
import Alamofire
enum SCRSafecastAPIRouter: URLRequestConvertible {
static let baseURLString = "https://api.safecast.org/en-US"
case Dashboard()
case SignIn(String, String)
case SignOut()
case User(Int)
case Imports(Int, Int)
case Import(Int)
case CreateImport(String)
case EditImportMetadata(Int, String, String, String)
case SubmitImport(Int, String)
var method: Alamofire.Method {
switch self {
case .Dashboard:
return .GET
case .SignIn:
return .POST
case .SignOut:
return .GET
case .User:
return .GET
case .Imports:
return .GET
case .Import:
return .GET
case .CreateImport:
return .POST
case .EditImportMetadata:
return .PUT
case .SubmitImport:
return .PUT
}
}
var path: String {
switch self {
case .Dashboard:
return ""
case .SignIn:
return "/users/sign_in"
case .SignOut:
return "/logout"
case .User(let id):
return "/users/\(id).json"
case .Imports:
return "/bgeigie_imports.json"
case .Import(let id):
return "/bgeigie_imports/\(id).json"
case .CreateImport:
return "/bgeigie_imports.json"
case .EditImportMetadata(let id, _, _, _):
return "/bgeigie_imports/\(id)"
case .SubmitImport(let id, _):
return "/bgeigie_imports/\(id)/submit"
}
}
var parameters: [String: AnyObject] {
switch self {
case .Dashboard:
return [:]
case .SignIn(let email, let password):
return ["user[email]": email, "user[password]": password]
case .SignOut:
return [:]
case .User:
return [:]
case .Imports(let id, let page):
return ["by_user_id": id, "page": page, "order": "created_at"]
case .Import:
return [:]
case .CreateImport:
return [:]
case .EditImportMetadata(_, let key, let credits, let cities):
return ["api_key": key, "bgeigie_import[credits]": credits, "bgeigie_import[cities]": cities]
case .SubmitImport(_, let key):
return ["api_key": key]
}
}
var URLRequest: NSMutableURLRequest {
let mutableURLRequest:NSMutableURLRequest!
let URL = NSURL(string: SCRSafecastAPIRouter.baseURLString)!
let encoding = Alamofire.ParameterEncoding.URL
mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path))
mutableURLRequest.HTTPMethod = method.rawValue
switch self {
case .CreateImport(let boundaryConstant):
let contentType = "multipart/form-data; boundary=" + boundaryConstant
mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
return encoding.encode(mutableURLRequest, parameters: parameters).0
default:
return encoding.encode(mutableURLRequest, parameters: parameters).0
}
}
}
| cc0-1.0 |
raptorxcz/Rubicon | GeneratorTests/Generator/CreateDummyInteractorTests.swift | 1 | 20890 | //
// CreateDummyInteractorTests.swift
// GeneratorTests
//
// Created by Kryštof Matěj on 15/02/2019.
// Copyright © 2019 Kryštof Matěj. All rights reserved.
//
import Generator
import XCTest
class CreateDummyInteractorTests: XCTestCase {
private var generator: CreateDummyInteractor!
private let type = Type(name: "Color", isOptional: false)
func test_givenprotocolType_whenGenerate_thenGenerateEmptyDummy() {
let protocolType = ProtocolType(name: "Test", parents: [], variables: [], functions: [])
equal(protocolType: protocolType, rows: [
"final class TestDummy: Test {",
"}",
"",
])
}
func test_givenprotocolTypeWithLongName_whenGenerate_thenGenerateEmptyDummy() {
let protocolType = ProtocolType(name: "TestTestTestTestTest", parents: [], variables: [], functions: [])
equal(protocolType: protocolType, rows: [
"final class TestTestTestTestTestDummy: TestTestTestTestTest {",
"}",
"",
])
}
func test_givenProtocolWithVariable_whenGenerate_thenGenerateDummy() {
let variable = VarDeclarationType(isConstant: false, identifier: "color", type: type)
let protocolType = ProtocolType(name: "Car", parents: [], variables: [variable], functions: [])
equal(protocolType: protocolType, rows: [
"final class CarDummy: Car {",
"",
"\tvar color: Color {",
"\t\tget {",
"\t\t\tfatalError()",
"\t\t}",
"\t\tset {",
"\t\t\tfatalError()",
"\t\t}",
"\t}",
"}",
"",
])
}
func test_givenProtocolWithEscapingClosureVariable_whenGenerate_thenGenerateDummy() {
let type = Type(name: "(() -> Void)", isOptional: false, isClosure: true)
let variable = VarDeclarationType(isConstant: false, identifier: "closeBlock", type: type)
let protocolType = ProtocolType(name: "Door", parents: [], variables: [variable], functions: [])
equal(protocolType: protocolType, rows: [
"final class DoorDummy: Door {",
"",
"\tvar closeBlock: (() -> Void) {",
"\t\tget {",
"\t\t\tfatalError()",
"\t\t}",
"\t\tset {",
"\t\t\tfatalError()",
"\t\t}",
"\t}",
"}",
"",
])
}
func test_givenProtocolWithConstant_whenGenerate_thenGenerateDummy() {
let type = Type(name: "Color", isOptional: false)
let variable = VarDeclarationType(isConstant: true, identifier: "color", type: type)
let protocolType = ProtocolType(name: "Car", parents: [], variables: [variable], functions: [])
equal(protocolType: protocolType, rows: [
"final class CarDummy: Car {",
"",
"\tvar color: Color {",
"\t\tfatalError()",
"\t}",
"}",
"",
])
}
func test_givenProtocolWithOptional_whenGenerate_thenGenerateDummy() {
let type = Type(name: "Color", isOptional: true)
let variable = VarDeclarationType(isConstant: true, identifier: "color", type: type)
let protocolType = ProtocolType(name: "Car", parents: [], variables: [variable], functions: [])
equal(protocolType: protocolType, rows: [
"final class CarDummy: Car {",
"",
"\tvar color: Color? {",
"\t\tfatalError()",
"\t}",
"}",
"",
])
}
func test_givenProtocolWithTwoVariables_whenGenerate_thenGenerateDummy() {
let variable1 = VarDeclarationType(isConstant: false, identifier: "color1", type: type)
let variable2 = VarDeclarationType(isConstant: false, identifier: "color2", type: type)
let protocolType = ProtocolType(name: "Car", parents: [], variables: [variable1, variable2], functions: [])
equal(protocolType: protocolType, rows: [
"final class CarDummy: Car {",
"",
"\tvar color1: Color {",
"\t\tget {",
"\t\t\tfatalError()",
"\t\t}",
"\t\tset {",
"\t\t\tfatalError()",
"\t\t}",
"\t}",
"\tvar color2: Color {",
"\t\tget {",
"\t\t\tfatalError()",
"\t\t}",
"\t\tset {",
"\t\t\tfatalError()",
"\t\t}",
"\t}",
"}",
"",
])
}
func test_givenProtocolWithSimpleFunction_whenGenerate_thenGenerateDummy() {
let function = FunctionDeclarationType(name: "start")
let protocolType = ProtocolType(name: "Car", parents: [], variables: [], functions: [function])
equal(protocolType: protocolType, rows: [
"final class CarDummy: Car {",
"",
"\tfunc start() {",
"\t\tfatalError()",
"\t}",
"}",
"",
])
}
func test_givenProtocolWithFunctionWithReturn_whenGenerate_thenGenerateDummy() {
let function = FunctionDeclarationType(name: "start", returnType: Type(name: "Int", isOptional: false))
let protocolType = ProtocolType(name: "Car", parents: [], variables: [], functions: [function])
equal(protocolType: protocolType, rows: [
"final class CarDummy: Car {",
"",
"\tfunc start() -> Int {",
"\t\tfatalError()",
"\t}",
"}",
"",
])
}
func test_givenProtocolWithAsyncFunction_whenGenerate_thenGenerateDummy() {
let function = FunctionDeclarationType(name: "start", isAsync: true, returnType: Type(name: "Int", isOptional: false))
let protocolType = ProtocolType(name: "Car", parents: [], variables: [], functions: [function])
equal(protocolType: protocolType, rows: [
"final class CarDummy: Car {",
"",
"\tfunc start() async -> Int {",
"\t\tfatalError()",
"\t}",
"}",
"",
])
}
func test_givenProtocolWithThrowingFunction_whenGenerate_thenGenerateDummy() {
let function = FunctionDeclarationType(name: "start", isThrowing: true, returnType: Type(name: "Int", isOptional: false))
let protocolType = ProtocolType(name: "Car", parents: [], variables: [], functions: [function])
equal(protocolType: protocolType, rows: [
"final class CarDummy: Car {",
"",
"\tfunc start() throws -> Int {",
"\t\tfatalError()",
"\t}",
"}",
"",
])
}
func test_givenProtocolWithThrowingAndAsyncFunction_whenGenerate_thenGenerateDummy() {
let function = FunctionDeclarationType(name: "start", isThrowing: true, isAsync: true, returnType: Type(name: "Int", isOptional: false))
let protocolType = ProtocolType(name: "Car", parents: [], variables: [], functions: [function])
equal(protocolType: protocolType, rows: [
"final class CarDummy: Car {",
"",
"\tfunc start() async throws -> Int {",
"\t\tfatalError()",
"\t}",
"}",
"",
])
}
func test_givenProtocolWithThrowingFunctionWithArguments_whenGenerate_thenGenerateDummy() {
let argument = ArgumentType(label: "with", name: "label", type: type)
let function = FunctionDeclarationType(name: "start", arguments: [argument], isThrowing: true, returnType: Type(name: "Int", isOptional: false))
let protocolType = ProtocolType(name: "Car", parents: [], variables: [], functions: [function])
equal(protocolType: protocolType, rows: [
"final class CarDummy: Car {",
"",
"\tfunc start(with label: Color) throws -> Int {",
"\t\tfatalError()",
"\t}",
"}",
"",
])
}
func test_givenProtocolWithMultipleReturnFunctions_whenGenerate_thenGenerateDummy() {
let function = FunctionDeclarationType(name: "start", returnType: Type(name: "Int", isOptional: false))
let function2 = FunctionDeclarationType(name: "stop", returnType: Type(name: "Int", isOptional: false))
let protocolType = ProtocolType(name: "Car", parents: [], variables: [], functions: [function, function2])
equal(protocolType: protocolType, rows: [
"final class CarDummy: Car {",
"",
"\tfunc start() -> Int {",
"\t\tfatalError()",
"\t}",
"",
"\tfunc stop() -> Int {",
"\t\tfatalError()",
"\t}",
"}",
"",
])
}
func test_givenProtocolWithFunctionWithEscapingType_whenGenerate_thenGenerateDummy() {
let argumentType = Type(name: "ActionBlock", isOptional: false, isClosure: true, prefix: .escaping)
let argument = ArgumentType(label: "with", name: "action", type: argumentType)
let function = FunctionDeclarationType(name: "start", arguments: [argument], returnType: nil)
let protocolType = ProtocolType(name: "Car", parents: [], variables: [], functions: [function])
equal(protocolType: protocolType, rows: [
"final class CarDummy: Car {",
"",
"\tfunc start(with action: @escaping ActionBlock) {",
"\t\tfatalError()",
"\t}",
"}",
"",
])
}
func test_givenProtocolWithFunctionWithClosureParameterAndReturnClosure_whenGenerate_thenGenerateDummy() {
let argumentType = Type(name: "(String) -> Int", isOptional: false, isClosure: true, prefix: .escaping)
let argument = ArgumentType(label: "with", name: "mapping", type: argumentType)
let returnType = Type(name: "(Data) -> Void", isOptional: false, isClosure: true)
let function = FunctionDeclarationType(name: "start", arguments: [argument], returnType: returnType)
let protocolType = ProtocolType(name: "Car", parents: [], variables: [], functions: [function])
equal(protocolType: protocolType, rows: [
"final class CarDummy: Car {",
"",
"\tfunc start(with mapping: @escaping (String) -> Int) -> (Data) -> Void {",
"\t\tfatalError()",
"\t}",
"}",
"",
])
}
func test_givenProtocolWithFunctionWithThrowingAutoclosureArgument_whenGenerate_thenGenerateDummy() {
let type = Type(name: "(Window) throws -> Air", isOptional: false, isClosure: true)
let function = FunctionDeclarationType(name: "rollDown", arguments: [], returnType: type)
let protocolType = ProtocolType(name: "Car", parents: [], variables: [], functions: [function])
equal(protocolType: protocolType, rows: [
"final class CarDummy: Car {",
"",
"\tfunc rollDown() -> (Window) throws -> Air {",
"\t\tfatalError()",
"\t}",
"}",
"",
])
}
func test_givenProtocolWithFunctionWithClosureAndIntParameterAndOptionalReturnClosure_whenGenerate_thenGenerateDummy() {
let closureArgumentType = Type(name: "(String) -> Int", isOptional: false, isClosure: true, prefix: .escaping)
let closureArgument = ArgumentType(label: "with", name: "mapping", type: closureArgumentType)
let intType = Type(name: "Int", isOptional: false, isClosure: false)
let intArgument = ArgumentType(label: nil, name: "count", type: intType)
let returnType = Type(name: "((Data) -> Void)", isOptional: true, isClosure: true)
let function = FunctionDeclarationType(name: "start", arguments: [closureArgument, intArgument], returnType: returnType)
let protocolType = ProtocolType(name: "Car", parents: [], variables: [], functions: [function])
equal(protocolType: protocolType, rows: [
"final class CarDummy: Car {",
"",
"\tfunc start(with mapping: @escaping (String) -> Int, count: Int) -> ((Data) -> Void)? {",
"\t\tfatalError()",
"\t}",
"}",
"",
])
}
func test_givenProtocolWithFunctionWithArgument_whenGenerate_thenGenerateDummy() {
let argument = ArgumentType(label: "a", name: "b", type: type)
let function = FunctionDeclarationType(name: "start", arguments: [argument])
let protocolType = ProtocolType(name: "Car", parents: [], variables: [], functions: [function])
equal(protocolType: protocolType, rows: [
"final class CarDummy: Car {",
"",
"\tfunc start(a b: Color) {",
"\t\tfatalError()",
"\t}",
"}",
"",
])
}
func test_givenProtocolWithFunctionWithNoLabelAndArgument_whenGenerate_thenGenerateDummy() {
let argument = ArgumentType(label: "_", name: "b", type: type)
let function = FunctionDeclarationType(name: "start", arguments: [argument])
let protocolType = ProtocolType(name: "Car", parents: [], variables: [], functions: [function])
equal(protocolType: protocolType, rows: [
"final class CarDummy: Car {",
"",
"\tfunc start(_ b: Color) {",
"\t\tfatalError()",
"\t}",
"}",
"",
])
}
func test_givenProtocolWithFunctionWithTwoArguments_whenGenerate_thenGenerateDummy() {
let argument = ArgumentType(label: "a", name: "b", type: type)
let type2 = Type(name: "Color", isOptional: true)
let argument2 = ArgumentType(label: nil, name: "d", type: type2)
let function = FunctionDeclarationType(name: "start", arguments: [argument, argument2])
let protocolType = ProtocolType(name: "Car", parents: [], variables: [], functions: [function])
equal(protocolType: protocolType, rows: [
"final class CarDummy: Car {",
"",
"\tfunc start(a b: Color, d: Color?) {",
"\t\tfatalError()",
"\t}",
"}",
"",
])
}
func test_givenProtocolWithTwoFunctionWithArgument_whenGenerate_thenGenerateDummy() {
let argument = ArgumentType(label: "a", name: "b", type: type)
let function = FunctionDeclarationType(name: "start", arguments: [argument])
let function2 = FunctionDeclarationType(name: "stop", arguments: [argument])
let protocolType = ProtocolType(name: "Car", parents: [], variables: [], functions: [function, function2])
equal(protocolType: protocolType, rows: [
"final class CarDummy: Car {",
"",
"\tfunc start(a b: Color) {",
"\t\tfatalError()",
"\t}",
"",
"\tfunc stop(a b: Color) {",
"\t\tfatalError()",
"\t}",
"}",
"",
])
}
func test_givenProtocolWithFunctionAndVarible_whenGenerate_thenGenerateDummy() {
let variable = VarDeclarationType(isConstant: false, identifier: "color", type: type)
let argument = ArgumentType(label: "a", name: "b", type: type)
let function = FunctionDeclarationType(name: "start", arguments: [argument])
let protocolType = ProtocolType(name: "Car", parents: [], variables: [variable], functions: [function])
equal(protocolType: protocolType, rows: [
"final class CarDummy: Car {",
"",
"\tvar color: Color {",
"\t\tget {",
"\t\t\tfatalError()",
"\t\t}",
"\t\tset {",
"\t\t\tfatalError()",
"\t\t}",
"\t}",
"",
"\tfunc start(a b: Color) {",
"\t\tfatalError()",
"\t}",
"}",
"",
])
}
func test_givenProtocolWithLongNames_whenGenerate_thenDummyIsGenerated() {
let argument = ArgumentType(label: nil, name: "productId", type: type)
let function = FunctionDeclarationType(name: "startGenerating", arguments: [argument])
let protocolType = ProtocolType(name: "Car", parents: [], variables: [], functions: [function])
equal(protocolType: protocolType, rows: [
"final class CarDummy: Car {",
"",
"\tfunc startGenerating(productId: Color) {",
"\t\tfatalError()",
"\t}",
"}",
"",
])
}
func test_givenProtocolWithSameFunctionNames_whenGenerate_thenGenerateDummy() {
let argument = ArgumentType(label: "a", name: "b", type: type)
let argument2 = ArgumentType(label: "c", name: "d", type: type)
let function = FunctionDeclarationType(name: "start", arguments: [argument])
let function2 = FunctionDeclarationType(name: "start", arguments: [argument2])
let protocolType = ProtocolType(name: "Car", parents: [], variables: [], functions: [function, function2])
equal(protocolType: protocolType, rows: [
"final class CarDummy: Car {",
"",
"\tfunc start(a b: Color) {",
"\t\tfatalError()",
"\t}",
"",
"\tfunc start(c d: Color) {",
"\t\tfatalError()",
"\t}",
"}",
"",
])
}
func test_givenProtocolWithNoArgumentLabelAndReturnValue_whenGenerate_thenGenerateDummy() {
let argumentType = Type(name: "Int", isOptional: true)
let argument = ArgumentType(label: "_", name: "value", type: argumentType)
let returnType = Type(name: "String", isOptional: true)
let function = FunctionDeclarationType(name: "formattedString", arguments: [argument], returnType: returnType)
let protocolType = ProtocolType(name: "Formatter", parents: [], variables: [], functions: [function])
equal(protocolType: protocolType, rows: [
"final class FormatterDummy: Formatter {",
"",
"\tfunc formattedString(_ value: Int?) -> String? {",
"\t\tfatalError()",
"\t}",
"}",
"",
])
}
func test_givenEmptyProtocolAndPrivate_whenGenerate_thenGenerateDummy() {
let protocolType = ProtocolType(name: "TestTestTestTestTest", parents: [], variables: [], functions: [])
equal(protocolType: protocolType, accessLevel: .private, rows: [
"private final class TestTestTestTestTestDummy: TestTestTestTestTest {",
"}",
"",
])
}
func test_givenProtocolWithArgumentAndThrowingFunctionWithReturnValue_whenGeneratePublic_thenGenerateDummy() {
let variable = VarDeclarationType(isConstant: false, identifier: "color", type: type)
let variable2 = VarDeclarationType(isConstant: true, identifier: "color", type: type)
let argumentType = Type(name: "Int", isOptional: true)
let argument = ArgumentType(label: "_", name: "value", type: argumentType)
let returnType = Type(name: "String", isOptional: true)
let function = FunctionDeclarationType(name: "formattedString", arguments: [argument], isThrowing: true, returnType: returnType)
let protocolType = ProtocolType(name: "Formatter", parents: [], variables: [variable, variable2], functions: [function])
equal(protocolType: protocolType, accessLevel: .public, rows: [
"public final class FormatterDummy: Formatter {",
"",
"\tpublic var color: Color {",
"\t\tget {",
"\t\t\tfatalError()",
"\t\t}",
"\t\tset {",
"\t\t\tfatalError()",
"\t\t}",
"\t}",
"\tpublic var color: Color {",
"\t\tfatalError()",
"\t}",
"",
"\tpublic init() {",
"\t}",
"",
"\tpublic func formattedString(_ value: Int?) throws -> String? {",
"\t\tfatalError()",
"\t}",
"}",
"",
])
}
private func equal(protocolType: ProtocolType, accessLevel: AccessLevel = .internal, rows: [String], line: UInt = #line) {
generator = CreateDummyInteractor(accessLevel: accessLevel)
let generatedRows = generator.generate(from: protocolType).components(separatedBy: "\n")
XCTAssertEqual(generatedRows.count, rows.count, line: line)
var index: UInt = 1
for (line1, line2) in zip(generatedRows, rows) {
XCTAssertEqual(line1, line2, line: line + index)
index += 1
}
}
}
| mit |
tkremenek/swift | test/PrintAsObjC/async.swift | 1 | 2114 | // REQUIRES: objc_interop
// RUN: %empty-directory(%t)
// FIXME: BEGIN -enable-source-import hackaround
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift -disable-objc-attr-requires-foundation-module -disable-availability-checking
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/CoreGraphics.swift -disable-availability-checking
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/Foundation.swift -disable-availability-checking
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/AppKit.swift -disable-availability-checking
// FIXME: END -enable-source-import hackaround
// REQUIRES: concurrency
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -parse-as-library %s -typecheck -I %S/Inputs/custom-modules -emit-objc-header-path %t/async.h -import-objc-header %S/../Inputs/empty.h -enable-experimental-concurrency -typecheck -disable-availability-checking
// RUN: %FileCheck %s < %t/async.h
// RUN: %check-in-clang -I %S/Inputs/custom-modules/ %t/async.h
import Foundation
// CHECK-LABEL: @interface BarClass : NSObject
@objc @objcMembers class BarClass: NSObject {
// CHECK: (void)doSomethingBigWithCompletionHandler:(void (^)(NSInteger))completionHandler;
func doSomethingBig() async -> Int { 0 }
// CHECK: - (void)longRunningWithString:(NSString * _Nonnull)string completionHandler:(void (^)(BarClass * _Nullable, NSError * _Nullable))completionHandler;
func longRunning(string: String) async throws -> BarClass { return self }
// CHECK: - (void)magicTupleReturnWithCompletionHandler:(void (^)(BarClass * _Nonnull, NSInteger))completionHandler;
func magicTupleReturn() async -> (BarClass, Int) { return (self, 0) }
}
// CHECK: @end
| apache-2.0 |
functionaldude/XLPagerTabStrip | Sources/BaseButtonBarPagerTabStripViewController.swift | 3 | 18195 | // BaseButtonBarPagerTabStripViewController.swift
// XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip )
//
// Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
open class BaseButtonBarPagerTabStripViewController<ButtonBarCellType: UICollectionViewCell>: PagerTabStripViewController, PagerTabStripDataSource, PagerTabStripIsProgressiveDelegate, UICollectionViewDelegate, UICollectionViewDataSource {
public var settings = ButtonBarPagerTabStripSettings()
public var buttonBarItemSpec: ButtonBarItemSpec<ButtonBarCellType>!
public var changeCurrentIndex: ((_ oldCell: ButtonBarCellType?, _ newCell: ButtonBarCellType?, _ animated: Bool) -> Void)?
public var changeCurrentIndexProgressive: ((_ oldCell: ButtonBarCellType?, _ newCell: ButtonBarCellType?, _ progressPercentage: CGFloat, _ changeCurrentIndex: Bool, _ animated: Bool) -> Void)?
@IBOutlet public weak var buttonBarView: ButtonBarView!
lazy private var cachedCellWidths: [CGFloat]? = { [unowned self] in
return self.calculateWidths()
}()
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
delegate = self
datasource = self
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
delegate = self
datasource = self
}
open override func viewDidLoad() {
super.viewDidLoad()
let buttonBarViewAux = buttonBarView ?? {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .horizontal
flowLayout.sectionInset = UIEdgeInsets(top: 0, left: settings.style.buttonBarLeftContentInset ?? 35, bottom: 0, right: settings.style.buttonBarRightContentInset ?? 35)
let buttonBarHeight = settings.style.buttonBarHeight ?? 44
let buttonBar = ButtonBarView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: buttonBarHeight), collectionViewLayout: flowLayout)
buttonBar.backgroundColor = .orange
buttonBar.selectedBar.backgroundColor = .black
buttonBar.autoresizingMask = .flexibleWidth
var newContainerViewFrame = containerView.frame
newContainerViewFrame.origin.y = buttonBarHeight
newContainerViewFrame.size.height = containerView.frame.size.height - (buttonBarHeight - containerView.frame.origin.y)
containerView.frame = newContainerViewFrame
return buttonBar
}()
buttonBarView = buttonBarViewAux
if buttonBarView.superview == nil {
view.addSubview(buttonBarView)
}
if buttonBarView.delegate == nil {
buttonBarView.delegate = self
}
if buttonBarView.dataSource == nil {
buttonBarView.dataSource = self
}
buttonBarView.scrollsToTop = false
let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout // swiftlint:disable:this force_cast
flowLayout.scrollDirection = .horizontal
flowLayout.minimumInteritemSpacing = settings.style.buttonBarMinimumInteritemSpacing ?? flowLayout.minimumInteritemSpacing
flowLayout.minimumLineSpacing = settings.style.buttonBarMinimumLineSpacing ?? flowLayout.minimumLineSpacing
let sectionInset = flowLayout.sectionInset
flowLayout.sectionInset = UIEdgeInsets(top: sectionInset.top, left: settings.style.buttonBarLeftContentInset ?? sectionInset.left, bottom: sectionInset.bottom, right: settings.style.buttonBarRightContentInset ?? sectionInset.right)
buttonBarView.showsHorizontalScrollIndicator = false
buttonBarView.backgroundColor = settings.style.buttonBarBackgroundColor ?? buttonBarView.backgroundColor
buttonBarView.selectedBar.backgroundColor = settings.style.selectedBarBackgroundColor
buttonBarView.selectedBarHeight = settings.style.selectedBarHeight
// register button bar item cell
switch buttonBarItemSpec! {
case .nibFile(let nibName, let bundle, _):
buttonBarView.register(UINib(nibName: nibName, bundle: bundle), forCellWithReuseIdentifier:"Cell")
case .cellClass:
buttonBarView.register(ButtonBarCellType.self, forCellWithReuseIdentifier:"Cell")
}
//-
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
buttonBarView.layoutIfNeeded()
isViewAppearing = true
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
isViewAppearing = false
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
guard isViewAppearing || isViewRotating else { return }
// Force the UICollectionViewFlowLayout to get laid out again with the new size if
// a) The view is appearing. This ensures that
// collectionView:layout:sizeForItemAtIndexPath: is called for a second time
// when the view is shown and when the view *frame(s)* are actually set
// (we need the view frame's to have been set to work out the size's and on the
// first call to collectionView:layout:sizeForItemAtIndexPath: the view frame(s)
// aren't set correctly)
// b) The view is rotating. This ensures that
// collectionView:layout:sizeForItemAtIndexPath: is called again and can use the views
// *new* frame so that the buttonBarView cell's actually get resized correctly
cachedCellWidths = calculateWidths()
buttonBarView.collectionViewLayout.invalidateLayout()
// When the view first appears or is rotated we also need to ensure that the barButtonView's
// selectedBar is resized and its contentOffset/scroll is set correctly (the selected
// tab/cell may end up either skewed or off screen after a rotation otherwise)
buttonBarView.moveTo(index: currentIndex, animated: false, swipeDirection: .none, pagerScroll: .scrollOnlyIfOutOfScreen)
buttonBarView.selectItem(at: IndexPath(item: currentIndex, section: 0), animated: false, scrollPosition: [])
}
// MARK: - View Rotation
open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
}
// MARK: - Public Methods
open override func reloadPagerTabStripView() {
super.reloadPagerTabStripView()
guard isViewLoaded else { return }
buttonBarView.reloadData()
cachedCellWidths = calculateWidths()
buttonBarView.moveTo(index: currentIndex, animated: false, swipeDirection: .none, pagerScroll: .yes)
}
open func calculateStretchedCellWidths(_ minimumCellWidths: [CGFloat], suggestedStretchedCellWidth: CGFloat, previousNumberOfLargeCells: Int) -> CGFloat {
var numberOfLargeCells = 0
var totalWidthOfLargeCells: CGFloat = 0
for minimumCellWidthValue in minimumCellWidths where minimumCellWidthValue > suggestedStretchedCellWidth {
totalWidthOfLargeCells += minimumCellWidthValue
numberOfLargeCells += 1
}
guard numberOfLargeCells > previousNumberOfLargeCells else { return suggestedStretchedCellWidth }
let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout // swiftlint:disable:this force_cast
let collectionViewAvailiableWidth = buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right
let numberOfCells = minimumCellWidths.count
let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing
let numberOfSmallCells = numberOfCells - numberOfLargeCells
let newSuggestedStretchedCellWidth = (collectionViewAvailiableWidth - totalWidthOfLargeCells - cellSpacingTotal) / CGFloat(numberOfSmallCells)
return calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: newSuggestedStretchedCellWidth, previousNumberOfLargeCells: numberOfLargeCells)
}
open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int) {
guard shouldUpdateButtonBarView else { return }
buttonBarView.moveTo(index: toIndex, animated: true, swipeDirection: toIndex < fromIndex ? .right : .left, pagerScroll: .yes)
if let changeCurrentIndex = changeCurrentIndex {
let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex != fromIndex ? fromIndex : toIndex, section: 0)) as? ButtonBarCellType
let newCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarCellType
changeCurrentIndex(oldCell, newCell, true)
}
}
open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool) {
guard shouldUpdateButtonBarView else { return }
buttonBarView.move(fromIndex: fromIndex, toIndex: toIndex, progressPercentage: progressPercentage, pagerScroll: .yes)
if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex != fromIndex ? fromIndex : toIndex, section: 0)) as? ButtonBarCellType
let newCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarCellType
changeCurrentIndexProgressive(oldCell, newCell, progressPercentage, indexWasChanged, true)
}
}
// MARK: - UICollectionViewDelegateFlowLayut
@objc open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
guard let cellWidthValue = cachedCellWidths?[indexPath.row] else {
fatalError("cachedCellWidths for \(indexPath.row) must not be nil")
}
return CGSize(width: cellWidthValue, height: collectionView.frame.size.height)
}
open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard indexPath.item != currentIndex else { return }
buttonBarView.moveTo(index: indexPath.item, animated: true, swipeDirection: .none, pagerScroll: .yes)
shouldUpdateButtonBarView = false
let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarCellType
let newCell = buttonBarView.cellForItem(at: IndexPath(item: indexPath.item, section: 0)) as? ButtonBarCellType
if pagerBehaviour.isProgressiveIndicator {
if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
changeCurrentIndexProgressive(oldCell, newCell, 1, true, true)
}
} else {
if let changeCurrentIndex = changeCurrentIndex {
changeCurrentIndex(oldCell, newCell, true)
}
}
moveToViewController(at: indexPath.item)
}
// MARK: - UICollectionViewDataSource
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewControllers.count
}
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? ButtonBarCellType else {
fatalError("UICollectionViewCell should be or extend from ButtonBarViewCell")
}
let childController = viewControllers[indexPath.item] as! IndicatorInfoProvider // swiftlint:disable:this force_cast
let indicatorInfo = childController.indicatorInfo(for: self)
configure(cell: cell, for: indicatorInfo)
if pagerBehaviour.isProgressiveIndicator {
if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
changeCurrentIndexProgressive(currentIndex == indexPath.item ? nil : cell, currentIndex == indexPath.item ? cell : nil, 1, true, false)
}
} else {
if let changeCurrentIndex = changeCurrentIndex {
changeCurrentIndex(currentIndex == indexPath.item ? nil : cell, currentIndex == indexPath.item ? cell : nil, false)
}
}
return cell
}
// MARK: - UIScrollViewDelegate
open override func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
super.scrollViewDidEndScrollingAnimation(scrollView)
guard scrollView == containerView else { return }
shouldUpdateButtonBarView = true
}
open func configure(cell: ButtonBarCellType, for indicatorInfo: IndicatorInfo) {
fatalError("You must override this method to set up ButtonBarView cell accordingly")
}
private func calculateWidths() -> [CGFloat] {
let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout // swiftlint:disable:this force_cast
let numberOfCells = viewControllers.count
var minimumCellWidths = [CGFloat]()
var collectionViewContentWidth: CGFloat = 0
for viewController in viewControllers {
let childController = viewController as! IndicatorInfoProvider // swiftlint:disable:this force_cast
let indicatorInfo = childController.indicatorInfo(for: self)
switch buttonBarItemSpec! {
case .cellClass(let widthCallback):
let width = widthCallback(indicatorInfo)
minimumCellWidths.append(width)
collectionViewContentWidth += width
case .nibFile(_, _, let widthCallback):
let width = widthCallback(indicatorInfo)
minimumCellWidths.append(width)
collectionViewContentWidth += width
}
}
let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing
collectionViewContentWidth += cellSpacingTotal
let collectionViewAvailableVisibleWidth = buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right
if !settings.style.buttonBarItemsShouldFillAvailableWidth || collectionViewAvailableVisibleWidth < collectionViewContentWidth {
return minimumCellWidths
} else {
let stretchedCellWidthIfAllEqual = (collectionViewAvailableVisibleWidth - cellSpacingTotal) / CGFloat(numberOfCells)
let generalMinimumCellWidth = calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: stretchedCellWidthIfAllEqual, previousNumberOfLargeCells: 0)
var stretchedCellWidths = [CGFloat]()
for minimumCellWidthValue in minimumCellWidths {
let cellWidth = (minimumCellWidthValue > generalMinimumCellWidth) ? minimumCellWidthValue : generalMinimumCellWidth
stretchedCellWidths.append(cellWidth)
}
return stretchedCellWidths
}
}
private var shouldUpdateButtonBarView = true
}
open class ExampleBaseButtonBarPagerTabStripViewController: BaseButtonBarPagerTabStripViewController<ButtonBarViewCell> {
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
initialize()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
open func initialize() {
var bundle = Bundle(for: ButtonBarViewCell.self)
if let resourcePath = bundle.path(forResource: "XLPagerTabStrip", ofType: "bundle") {
if let resourcesBundle = Bundle(path: resourcePath) {
bundle = resourcesBundle
}
}
buttonBarItemSpec = .nibFile(nibName: "ButtonCell", bundle: bundle, width: { [weak self] (childItemInfo) -> CGFloat in
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = self?.settings.style.buttonBarItemFont ?? label.font
label.text = childItemInfo.title
let labelSize = label.intrinsicContentSize
return labelSize.width + CGFloat(self?.settings.style.buttonBarItemLeftRightMargin ?? 8 * 2)
})
}
open override func configure(cell: ButtonBarViewCell, for indicatorInfo: IndicatorInfo) {
cell.label.text = indicatorInfo.title
cell.accessibilityLabel = indicatorInfo.accessibilityLabel
if let image = indicatorInfo.image {
cell.imageView.image = image
}
if let highlightedImage = indicatorInfo.highlightedImage {
cell.imageView.highlightedImage = highlightedImage
}
}
}
| mit |
ChoingHyun/iPhone2015 | 21551197姚文豪/work1_ywh/work1_ywhUITests/work1_ywhUITests.swift | 5 | 1238 | //
// work1_ywhUITests.swift
// work1_ywhUITests
//
// Created by ywh on 15/10/24.
// Copyright © 2015年 ywh. All rights reserved.
//
import XCTest
class work1_ywhUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// 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.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
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.
}
}
| mit |
ReactiveKit/ReactiveGitter | Networking/Client.swift | 1 | 1760 | //
// Client.swift
// ReactiveGitter
//
// Created by Srdan Rasic on 14/01/2017.
// Copyright © 2017 ReactiveKit. All rights reserved.
//
import Entities
import Client
import ReactiveKit
private let GitterAPIBaseURL = "https://api.gitter.im/v1"
private let GitterAPIBaseStreamURL = "https://stream.gitter.im/v1"
private let GitterAuthorizationBaseURL = "https://gitter.im/login/oauth/authorize"
private let GitterAuthenticationAPIBaseURL = "https://gitter.im/login/oauth"
public class APIClient: Client {
public init(token: Token) {
super.init(baseURL: GitterAPIBaseURL)
defaultHeaders = ["Authorization": "Bearer \(token.accessToken)"]
}
}
public class AuthenticationAPIClient: Client {
public init() {
super.init(baseURL: GitterAuthenticationAPIBaseURL)
}
public static func authorizationURL(clientID: String, redirectURI: String) -> URL {
return URL(string: "\(GitterAuthorizationBaseURL)?client_id=\(clientID)&response_type=code&redirect_uri=\(redirectURI)")!
}
}
extension Client {
public func response<Resource, Error: Swift.Error>(for request: Request<Resource, Error>) -> Signal<Resource, Client.Error> {
return Signal { observer in
let task = self.perform(request) { (result) in
switch result {
case .success(let resource):
observer.completed(with: resource)
case .failure(let error):
observer.failed(error)
}
}
return BlockDisposable {
task.cancel()
}
}
}
}
extension Request {
public func response(using client: Client) -> Signal<Resource, Client.Error> {
return client.response(for: self)
}
}
| mit |
acort3255/Emby.ApiClient.Swift | Emby.ApiClient/model/querying/ItemFields.swift | 4 | 1201 | //
// File.swift
// Emby.ApiClient
//
import Foundation
public enum ItemFields: String {
case AirTime
case AlternateEpisodeNumbers
case AwardsSummary
case Budget
case CanDelete
case CanDownload
case Chapters
case CriticRatingSummary
case CumulativeRunTimeTicks
case CustomRating
case DateCreated
case DateLastModified
case DisplayPreferencesId
case DisplayMediaType
case Etag
case ExternalUrls
case Genres
case HomePageUrl
case IndexOptions
case ItemCounts
case Keywords
case MediaSourceCount
case MediaSources
case Metascore
case Overview
case ParentId
case Path
case People
case ProductionLocations
case ProviderIds
case PrimaryImageAspectRatio
case OriginalPrimaryImageAspectRatio
case Revenue
case SeasonName
case Settings
case ShortOverview
case ScreenshotImageTags
case SeriesGenres
case SeriesStudio
case SortName
case SpecialEpisodeNumbers
case Studios
case SyncInfo
case Taglines
case Tags
case VoteCount
case TmdbCollectionName
case RemoteTrailers
case MediaStreams
case SeasonUserData
} | mit |
radex/swift-compiler-crashes | crashes-duplicates/19714-swift-constraints-constraintsystem-gettypeofmemberreference.swift | 11 | 330 | // 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 b {
{
}
class b<T {
{
{
{
}
}
}
{
}
class A {
var d { class B {
func b
{
}
enum S {
func a
let a = b<T
}
}
struct Q {
func f {
{
}
var d { class B {
enum {
| mit |
radex/swift-compiler-crashes | crashes-duplicates/22676-swift-diagnosticengine-flushactivediagnostic.swift | 11 | 349 | // 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 {
let a {
struct B< < {
class A {
protocol c {
A )
}
func b<I : b {
{
}
}
func a
{
protocol A {
{
let {
}
protocol A {
}
c {
}
}
{
: {
}
}
class A {
let a {
protocol b : {
| mit |
radex/swift-compiler-crashes | crashes-fuzzing/19271-void.swift | 1 | 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
struct c<T where h: SequenceType
var b {
class b: SequenceType
{
}
for c {
| mit |
radex/swift-compiler-crashes | crashes-fuzzing/22626-swift-constraints-constraint-create.swift | 11 | 261 | // 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 < {
{
}
func a
let end = a
class B<T where g : NSObject {
let c {
class d {
func f : N
| mit |
qualaroo/QualarooSDKiOS | Qualaroo/Network/SimpleRequest/SimpleRequestScheduler.swift | 1 | 5853 | //
// SimpleRequestScheduler.swift
// QualarooSDKiOS
//
// Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved.
//
// Please refer to the LICENSE.md file for the terms and conditions
// under which redistribution and use of this file is permitted.
//
import Foundation
class SimpleRequestScheduler {
/// Queue that is used to execute operations which send responses.
var privateQueue: OperationQueue
/// Reachability object that contain logic for checking internet availability.
private let reachability: Reachability?
/// Saves and loades data.
private let storage: ReportRequestMemoryProtocol
init(reachability: Reachability?, storage: ReportRequestMemoryProtocol) {
self.storage = storage
self.reachability = reachability
privateQueue = OperationQueue()
privateQueue.name = "com.qualaroo.sendresponsequeue"
privateQueue.maxConcurrentOperationCount = 4
privateQueue.qualityOfService = .background
addObservers()
retryStoredAnswers()
}
deinit {
removeObservers()
}
/// Resume executing requests.
private func resumeQueue() {
privateQueue.isSuspended = false
}
/// Stops executing requests.
private func pauseQueue() {
privateQueue.isSuspended = true
}
private func cleanQueue() {
privateQueue.cancelAllOperations()
}
// MARK: - Notifications
func addObservers() {
observeForEnteringBackground()
observeForEnteringForeground()
observeForInternetAvailability()
}
func removeObservers() {
stopObservingForEnteringBackground()
stopObservingForEnteringForeground()
stopObservingInternetAvailability()
}
// MARK: - Saving answers
private func observeForEnteringBackground() {
NotificationCenter.default.addObserver(self,
selector: #selector(handleEnteredBackground),
name: UIApplication.didEnterBackgroundNotification,
object: nil)
}
private func stopObservingForEnteringBackground() {
NotificationCenter.default.removeObserver(self,
name: UIApplication.didEnterBackgroundNotification,
object: nil)
}
private func observeForEnteringForeground() {
NotificationCenter.default.addObserver(self,
selector: #selector(handleEnteringForeground),
name: UIApplication.willEnterForegroundNotification,
object: nil)
}
private func stopObservingForEnteringForeground() {
NotificationCenter.default.removeObserver(self,
name: UIApplication.willEnterForegroundNotification,
object: nil)
}
@objc func handleEnteredBackground() {
pauseQueue()
cleanQueue()
}
@objc func handleEnteringForeground() {
retryStoredAnswers()
if isInternetAvailable() {
resumeQueue()
}
}
func retryStoredAnswers() {
let requests = storage.getAllRequests()
for url in requests {
scheduleRequest(URL(string: url)!)
}
}
private class ReportRequestOperation: Operation {
let maxRetryCount = 3
let url: URL
let storage: ReportRequestMemoryProtocol
init(url: URL, storage: ReportRequestMemoryProtocol) {
self.url = url
self.storage = storage
}
override func main() {
var success: Bool = false
var tries = 0
repeat {
success = call(url, tries)
tries += 1
} while tries <= maxRetryCount && !success
if success {
storage.remove(reportRequest: url.absoluteString)
}
}
private func call(_ url: URL, _ retryNum: Int) -> Bool {
let timeToWait = pow(2, retryNum) - 1
sleep(NSDecimalNumber(decimal: timeToWait).uint32Value)
let request = ReportRequest(url)
let result = request.call()
return result.isSuccessful()
}
}
}
// MARK: - Internet
extension SimpleRequestScheduler {
/// Call it to start observing internet status.
private func observeForInternetAvailability() {
NotificationCenter.default.addObserver(self,
selector: #selector(reachabilityChanged(_:)),
name: reachabilityModified,
object: reachability)
do {
try reachability?.startNotifier()
} catch {
pauseQueue()
}
}
/// Use it to stop observing internet status. Should be used when class is being deallocated.
private func stopObservingInternetAvailability() {
NotificationCenter.default.removeObserver(self, name: reachabilityModified, object: reachability)
}
/// Function called when access to internet status changed while it's observed.
///
/// - Parameter notification: notification that contain new reachability status.
@objc func reachabilityChanged(_ notification: Notification) {
guard (notification.object as? Reachability) != nil else { return }
if isInternetAvailable() {
resumeQueue()
} else {
pauseQueue()
}
}
/// Check if devise have access to internet.
///
/// - Returns: True if there is access of false if there isn't.
private func isInternetAvailable() -> Bool {
guard let reachability = reachability else { return false }
return reachability.currentReachabilityStatus != .notReachable
}
}
extension SimpleRequestScheduler: ReportRequestProtocol {
func scheduleRequest(_ url: URL) {
let operation = ReportRequestOperation(url: url, storage: storage)
privateQueue.addOperation(operation)
}
}
| mit |
ronaldho/visionproject | EMIT/EMIT/AGImageView.swift | 1 | 223 | //
// AGImageView.swift
// AG Pregnancy
//
// Created by Andrew on 13/12/15.
// Copyright © 2015 Andrew. All rights reserved.
//
import UIKit
class AGImageView: UIImageView {
var fullImage: UIImage?;
}
| mit |
freesuraj/Bulldog | Package.swift | 1 | 70 | import PackageDescription
let package = Package(
name: "Bulldog"
)
| mit |
hoseking/Peak | Tests/PeakTests.swift | 1 | 2794 | // Copyright © 2015 Venture Media Labs. All rights reserved.
//
// This file is part of Peak. The full Peak copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
import XCTest
@testable import Peak
class PeakTests: XCTestCase {
func testLoadWave() {
let bundlePath = Bundle(for: PeakTests.self).path(forResource: "sin_1000Hz_-3dBFS_1s", ofType: "wav")
guard let path = bundlePath else {
XCTFail("Could not find wave file")
return
}
guard let audioFile = AudioFile.open(path) else {
XCTFail("Failed to open wave file")
return
}
XCTAssertEqual(audioFile.sampleRate, 44100)
let audioLengthInSeconds = 1.0
let expextedFrameCount = Int64(audioLengthInSeconds * audioFile.sampleRate)
XCTAssert(abs(audioFile.frameCount - expextedFrameCount) < 5)
XCTAssertEqual(audioFile.currentFrame, 0)
let readLength = 1024
var data = [Double](repeating: 0.0, count: readLength)
let actualLength = audioFile.readFrames(&data, count: readLength)
XCTAssertEqual(actualLength, readLength)
XCTAssertEqual(audioFile.currentFrame, readLength)
}
func testCreateLossless() {
let fileName = ProcessInfo.processInfo.globallyUniqueString + ".m4a"
let path = NSTemporaryDirectory() + "/" + fileName
guard let audioFile = AudioFile.createLossless(path, sampleRate: 44100, overwrite: true) else {
XCTFail("Failed to create lossless audio file")
return
}
XCTAssertEqual(audioFile.sampleRate, 44100)
let data = [Double](repeating: 0.0, count: 1024)
XCTAssert(audioFile.writeFrames(data, count: 1024))
}
func testReadMIDI() {
let bundlePath = Bundle(for: PeakTests.self).path(forResource: "alb_esp1", ofType: "mid")
guard let path = bundlePath else {
XCTFail("Could not find midi file")
return
}
guard let midi = MIDIFile(filePath: path) else {
XCTFail("Could not open midi file")
return
}
let events = midi.noteEvents
XCTAssertEqual(events.count, 634)
XCTAssertEqual(events[0].timeStamp, 0.5)
XCTAssertEqual(events[0].note, 81)
XCTAssertEqual(events[1].timeStamp, 0.5)
XCTAssertEqual(events[1].note, 57)
XCTAssertEqual(events[2].timeStamp, 1.0)
XCTAssertEqual(events[2].note, 88)
XCTAssertEqual(events[3].timeStamp, 1.0)
XCTAssertEqual(events[3].note, 64)
let tempoEvents = midi.tempoEvents
XCTAssertEqual(tempoEvents.count, 556)
}
}
| mit |
JornWu/ZhiBo_Swift | ZhiBo_Swift/Class/BaseVC/LiveRoom/LiveRoomCollectionViewCell.swift | 1 | 987 | //
// LiveRoomCollectionViewCell.swift
// ZhiBo_Swift
//
// Created by JornWu on 2017/4/26.
// Copyright © 2017年 Jorn.Wu(jorn_wza@sina.com). All rights reserved.
//
import UIKit
class LiveRoomCollectionViewCell: UICollectionViewCell {
public var contentImage: UIImage! {
didSet{
contentImageView.image = contentImage
}
}
public var flvLink: String!
private var contentImageView: UIImageView = {
return UIImageView()
}()
public func setupCell(withImageURLString urlString: String, flvLinkString: String) {
self.contentView.addSubview(self.contentImageView)
self.contentImageView.sd_setImage(with: URL(string: urlString),
placeholderImage: #imageLiteral(resourceName: "placeholder_head"))
contentImageView.snp.makeConstraints { (make) in
make.edges.height.equalToSuperview()
}
flvLink = flvLinkString
}
}
| mit |
Raizlabs/ios-template | PRODUCTNAME/app/PRODUCTNAME/Components/Protocols/Actionable.swift | 1 | 741 | //
// Actionable.swift
// PRODUCTNAME
//
// Created by LEADDEVELOPER on TODAYSDATE.
// Copyright © THISYEAR ORGANIZATION. All rights reserved.
//
protocol Actionable: class {
associatedtype ActionType
associatedtype Delegate
func notify(_ action: ActionType)
}
extension Actionable {
func notify(_ action: ActionType) -> () -> Void {
return { [weak self] in
self?.notify(action)
}
}
func notify(_ action: ActionType) -> (UIControl) -> Void {
return { [weak self] _ in
self?.notify(action)
}
}
func notify(_ action: ActionType) -> (UIAlertAction) -> Void {
return { [weak self] _ in
self?.notify(action)
}
}
}
| mit |
mattjgalloway/emoncms-ios | EmonCMSiOS/ViewModel/FeedListViewModel.swift | 1 | 2757 | //
// FeedListViewModel.swift
// EmonCMSiOS
//
// Created by Matt Galloway on 12/09/2016.
// Copyright © 2016 Matt Galloway. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import RxDataSources
import Realm
import RealmSwift
import RxRealm
final class FeedListViewModel {
struct ListItem {
let feedId: String
let name: String
let value: String
}
typealias Section = SectionModel<String, ListItem>
private let account: Account
private let api: EmonCMSAPI
private let realm: Realm
private let feedUpdateHelper: FeedUpdateHelper
private let disposeBag = DisposeBag()
// Inputs
let active = Variable<Bool>(false)
let refresh = ReplaySubject<()>.create(bufferSize: 1)
// Outputs
private(set) var feeds: Driver<[Section]>
private(set) var isRefreshing: Driver<Bool>
init(account: Account, api: EmonCMSAPI) {
self.account = account
self.api = api
self.realm = account.createRealm()
self.feedUpdateHelper = FeedUpdateHelper(account: account, api: api)
self.feeds = Driver.never()
self.isRefreshing = Driver.never()
self.feeds = Observable.arrayFrom(self.realm.objects(Feed.self))
.map(self.feedsToSections)
.asDriver(onErrorJustReturn: [])
let isRefreshing = ActivityIndicator()
self.isRefreshing = isRefreshing.asDriver()
let becameActive = self.active.asObservable()
.distinctUntilChanged()
.filter { $0 == true }
.becomeVoid()
Observable.of(self.refresh, becameActive)
.merge()
.flatMapLatest { [weak self] () -> Observable<()> in
guard let strongSelf = self else { return Observable.empty() }
return strongSelf.feedUpdateHelper.updateFeeds()
.catchErrorJustReturn(())
.trackActivity(isRefreshing)
}
.subscribe()
.addDisposableTo(self.disposeBag)
}
private func feedsToSections(_ feeds: [Feed]) -> [Section] {
var sectionBuilder: [String:[Feed]] = [:]
for feed in feeds {
let sectionFeeds: [Feed]
if let existingFeeds = sectionBuilder[feed.tag] {
sectionFeeds = existingFeeds
} else {
sectionFeeds = []
}
sectionBuilder[feed.tag] = sectionFeeds + [feed]
}
var sections: [Section] = []
for section in sectionBuilder.keys.sorted() {
let items = sectionBuilder[section]!
.map { feed in
return ListItem(feedId: feed.id, name: feed.name, value: feed.value.prettyFormat())
}
sections.append(Section(model: section, items: items))
}
return sections
}
func feedChartViewModel(forItem item: ListItem) -> FeedChartViewModel {
return FeedChartViewModel(account: self.account, api: self.api, feedId: item.feedId)
}
}
| mit |
mattwelborn/HSTracker | HSTracker/Core/Categories/Int.swift | 1 | 356 | //
// Int.swift
// HSTracker
//
// Created by Benjamin Michotte on 21/03/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
extension Int {
var boolValue: Bool? {
switch self {
case 0: return false
case 1: return true
default: return nil
}
}
}
| mit |
NextFaze/FazeKit | Example/Tests/CodableAdditionsTests.swift | 1 | 4672 | //
// CodableAdditionsTests.swift
// FazeKit_Example
//
// Created by Shane Woolcock on 11/10/19.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import Foundation
import FazeKit
import XCTest
class CodableAdditionsTests: XCTestCase {
func testDecodeDict() {
let source: [String: Any] = ["dict": ["string": "value",
"double": 1.5,
"bool": true,
"dict": ["Foo": "Bar"],
"array": [1, "a", true, [1, 2]]],
"array": [1, ["foo": "bar"]]]
guard let data = try? JSONSerialization.data(withJSONObject: source, options: []) else {
XCTFail("Couldn't serialise test data")
return
}
let decoder = JSONDecoder()
guard let decoded = try? decoder.decode(TestStruct.self, from: data) else {
XCTFail("Couldn't decode test data")
return
}
XCTAssertEqual(decoded.dict.count, 5, "Expected 5 key/value pairs in dict")
XCTAssertEqual(decoded.array.count, 2, "Expected 2 values in array")
XCTAssertEqual(decoded.dict["string"] as? String, "value", "Didn't read the string value from dict")
XCTAssertEqual(decoded.dict["double"] as? Double, 1.5, "Didn't read the double value from dict")
XCTAssertEqual(decoded.dict["bool"] as? Bool, true, "Didn't read the bool value from dict")
XCTAssertEqual(decoded.dict["dict"] as? [String: String], ["Foo": "Bar"], "Didn't read the dict value from dict")
guard let array = decoded.dict["array"] as? [Any], array.count == 4 else {
XCTFail("Didn't read the array value from dict")
return
}
XCTAssertEqual(array[0] as? Double, 1, "Didn't read the double value from subarray")
XCTAssertEqual(array[1] as? String, "a", "Didn't read the string value from subarray")
XCTAssertEqual(array[2] as? Bool, true, "Didn't read the bool value from subarray")
XCTAssertEqual(array[3] as? [Double], [1, 2], "Didn't read the array value from subarray")
XCTAssertEqual(decoded.array[0] as? Double, 1, "Didn't read the double value from array")
XCTAssertEqual(decoded.array[1] as? [String: String], ["foo": "bar"], "Didn't read the dict value from array")
}
@available(iOS 11.0, *)
func testEncodeDict() {
let target: [String: Any] = ["dict": ["string": "value",
"double": 1.5,
"bool": true,
"dict": ["Foo": "Bar"],
"array": [1, "a", true, [1, 2]]],
"array": [1, ["foo": "bar"]]]
guard let data = try? JSONSerialization.data(withJSONObject: target, options: JSONSerialization.WritingOptions.sortedKeys) else {
XCTFail("Couldn't serialise test data")
return
}
let source = TestStruct(all: target)
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
guard let encoded = try? encoder.encode(source) else {
XCTFail("Couldn't encode test data")
return
}
guard let output = String(data: encoded, encoding: .utf8), let expected = String(data: data, encoding: .utf8) else {
XCTFail("Couldn't convert data to string")
return
}
XCTAssertEqual(output, expected, "Encoded data did not match source")
}
}
private struct TestStruct: Codable {
enum CodingKeys: String, CodingKey {
case dict
case array
}
var dict: [String: Any]
var array: [Any]
init(all: [String: Any]) {
self.dict = all["dict"] as? [String: Any] ?? [:]
self.array = all["array"] as? [Any] ?? []
}
init(dict: [String: Any], array: [Any]) {
self.dict = dict
self.array = array
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.dict = try values.decode([String: Any].self, forKey: .dict)
self.array = try values.decode([Any].self, forKey: .array)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.dict, forKey: .dict)
try container.encode(self.array, forKey: .array)
}
}
| apache-2.0 |
icapps/ios_objective_c_workshop | Teacher/ObjcTextInput/Pods/Faro/Sources/Request/URLComponentsSerialization.swift | 5 | 1004 | //
// Query.swift
// Monizze
//
// Created by Stijn Willems on 21/04/2017.
// Copyright © 2017 iCapps. All rights reserved.
//
import Foundation
public protocol URLQueryParameterStringConvertible {
var queryParameters: String {get}
}
extension Dictionary : URLQueryParameterStringConvertible {
/**
This computed property returns a query parameters string from the given NSDictionary. For
example, if the input is @{@"day":@"Tuesday", @"month":@"January"}, the output
string will be @"day=Tuesday&month=January".
@return The computed parameters string.
*/
public var queryParameters: String {
var parts: [String] = []
for (key, value) in self {
let part = String(format: "%@=%@",
String(describing: key).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!,
String(describing: value).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
parts.append(part as String)
}
return parts.joined(separator: "&")
}
}
| mit |
kickstarter/ios-oss | KsApi/mutations/templates/mutation/CreateSetupIntentMutationTemplate.swift | 1 | 823 | import Apollo
@testable import KsApi
public enum CreateSetupIntentMutationTemplate {
case valid
case errored
var data: GraphAPI.CreateSetupIntentMutation.Data {
switch self {
case .valid:
return GraphAPI.CreateSetupIntentMutation
.Data(unsafeResultMap: self.createSetupIntentMutationResultMap)
case .errored:
return GraphAPI.CreateSetupIntentMutation
.Data(unsafeResultMap: self.createSetupIntentMutationErroredResultMap)
}
}
// MARK: Private Properties
private var createSetupIntentMutationResultMap: [String: Any?] {
[
"createSetupIntent": [
"clientSecret": "seti_1LO1Om4VvJ2PtfhKrNizQefl_secret_M6DqtRtur5tF3z0LRyh15x5VuHjFPQK"
]
]
}
private var createSetupIntentMutationErroredResultMap: [String: Any?] {
return [:]
}
}
| apache-2.0 |
mathcamp/Carlos | Tests/Fakes/CacheLevelFake.swift | 1 | 2127 | import Foundation
import Carlos
import PiedPiper
class CacheLevelFake<A, B>: CacheLevel {
typealias KeyType = A
typealias OutputType = B
init() {}
var queueUsedForTheLastCall: UnsafeMutablePointer<Void>!
var numberOfTimesCalledGet = 0
var didGetKey: KeyType?
var cacheRequestToReturn: Future<OutputType>?
var promisesReturned: [Promise<OutputType>] = []
func get(key: KeyType) -> Future<OutputType> {
numberOfTimesCalledGet++
didGetKey = key
queueUsedForTheLastCall = currentQueueSpecific()
let returningPromise: Promise<OutputType>
let returningFuture: Future<OutputType>
if let requestToReturn = cacheRequestToReturn {
returningFuture = requestToReturn
returningPromise = Promise<OutputType>().mimic(requestToReturn)
} else {
returningPromise = Promise<OutputType>()
returningFuture = returningPromise.future
}
promisesReturned.append(returningPromise)
return returningFuture
}
var numberOfTimesCalledSet = 0
var didSetValue: OutputType?
var didSetKey: KeyType?
func set(value: OutputType, forKey key: KeyType) {
numberOfTimesCalledSet++
didSetKey = key
didSetValue = value
queueUsedForTheLastCall = currentQueueSpecific()
}
var numberOfTimesCalledClear = 0
func clear() {
numberOfTimesCalledClear++
queueUsedForTheLastCall = currentQueueSpecific()
}
var numberOfTimesCalledOnMemoryWarning = 0
func onMemoryWarning() {
numberOfTimesCalledOnMemoryWarning++
queueUsedForTheLastCall = currentQueueSpecific()
}
}
class FetcherFake<A, B>: Fetcher {
typealias KeyType = A
typealias OutputType = B
var queueUsedForTheLastCall: UnsafeMutablePointer<Void>!
init() {}
var numberOfTimesCalledGet = 0
var didGetKey: KeyType?
var cacheRequestToReturn: Future<OutputType>?
func get(key: KeyType) -> Future<OutputType> {
numberOfTimesCalledGet++
didGetKey = key
queueUsedForTheLastCall = currentQueueSpecific()
return cacheRequestToReturn ?? Promise<OutputType>().future
}
} | mit |
CoderST/STScrolPlay | STScrolPlay/STScrolPlay/Class/Model/STPlayerToolModel.swift | 1 | 3022 | //
// STPlayerToolModel.swift
// STPlayerExample
//
// Created by xiudou on 2017/7/26.
// Copyright © 2017年 CoderST. All rights reserved.
// 画虚线
import UIKit
fileprivate let navHeight : CGFloat = NavAndStatusTotalHei
fileprivate let tabHeight : CGFloat = TabbarHei
class STPlayerToolModel: NSObject {
// 虚线区域View
lazy var tableViewRange : UIView = self.generateTableViewRange()
let generateTableViewRange = { () -> UIView in
let tableViewRange = UIView(frame: CGRect(x: 0, y: navHeight, width: screenSize.width, height: screenSize.height-navHeight-tabHeight))
tableViewRange.isUserInteractionEnabled = false
tableViewRange.backgroundColor = UIColor.clear
tableViewRange.isHidden = true
return tableViewRange
}
lazy var dictOfVisiableAndNotPlayCells : Dictionary<String, Int> = {
return ["4" : 1, "3" : 1, "2" : 0]
}()
// The number of cells cannot stop in screen center.
var maxNumCannotPlayVideoCells: Int {
let radius = screenSize.height / RowHei
let maxNumOfVisiableCells = Int(ceilf(Float(radius)))
if maxNumOfVisiableCells >= 3 {
return dictOfVisiableAndNotPlayCells["\(maxNumOfVisiableCells)"]!
}
return 0
}
func displayCollectionViewRange(centerView : UIView, view : UIView){
view.insertSubview(tableViewRange, aboveSubview: centerView)
addDashLineToTableViewRange()
}
func addDashLineToTableViewRange() {
let linePath1 = UIBezierPath()
linePath1.move(to: CGPoint(x: 1, y: 1))
linePath1.addLine(to: CGPoint(x: screenSize.width-1, y: 1))
linePath1.addLine(to: CGPoint(x: screenSize.width-1, y: screenSize.height-navHeight-1-tabHeight))
linePath1.addLine(to: CGPoint(x: 1, y: screenSize.height-navHeight-1-tabHeight))
linePath1.addLine(to: CGPoint(x: 1, y: 1))
let layer1 = CAShapeLayer()
let drawColor1 = UIColor(colorLiteralRed: 1, green: 0, blue: 0, alpha: 1)
layer1.path = linePath1.cgPath
layer1.strokeColor = drawColor1.cgColor
layer1.fillColor = UIColor.clear.cgColor
layer1.lineWidth = 1
layer1.lineDashPattern = [6, 3]
layer1.lineCap = "round"
tableViewRange.layer.addSublayer(layer1)
let linePath2 = UIBezierPath()
linePath2.move(to: CGPoint(x: 1, y: 0.5*(screenSize.height-navHeight-1-tabHeight)))
linePath2.addLine(to: CGPoint(x: screenSize.width-1, y: 0.5*(screenSize.height-navHeight-1-tabHeight)))
let layer2 = CAShapeLayer()
let drawColor2 = UIColor(colorLiteralRed: 0, green: 0.98, blue: 0, alpha: 1)
layer2.path = linePath2.cgPath
layer2.strokeColor = drawColor2.cgColor
layer2.fillColor = UIColor.clear.cgColor
layer2.lineWidth = 1
layer2.lineDashPattern = [6, 3]
layer2.lineCap = "round"
tableViewRange.layer.addSublayer(layer2)
}
}
| mit |
ChrisXu1221/accountTest | Demo/Demo/Configurable.swift | 1 | 238 | //
// Configurable.swift
// Demo
//
// Created by Chris Xu on 08/08/2016.
// Copyright © 2016 CXCreation. All rights reserved.
//
import Foundation
protocol Configurable {
func configure(withViewModel viewModel: ViewModeling)
} | mit |
zom/Zom-iOS | Zom/Zom/Classes/View Controllers/ZomComposeViewController.swift | 1 | 12063 | //
// ZomComposeViewController.swift
// Zom
//
// Created by N-Pex on 2015-11-24.
//
//
import UIKit
import ChatSecureCore
open class ZomComposeViewController: OTRComposeViewController {
typealias ObjcYapDatabaseViewSortingWithObjectBlock = @convention(block) (YapDatabaseReadTransaction, String, String, String, Any, String, String, Any) -> ComparisonResult
typealias ObjcYapDatabaseViewGroupingWithObjectBlock = @convention(block)
(YapDatabaseReadTransaction, String, String, Any) -> String?
static var extensionName:String = "Zom" + OTRAllBuddiesDatabaseViewExtensionName
static var filteredExtensionName:String = "Zom" + OTRArchiveFilteredBuddiesName
open static var openInGroupMode:Bool = false
var wasOpenedInGroupMode = false
static let imageActionButtonCellIdentifier = "imageActionCell"
static let imageActionCreateGroupIdentifier = "imageActionCellCreateGroup"
static let imageActionAddFriendIdentifier = "imageActionCellAddFriend"
open override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(OTRBuddyApprovalCell.self, forCellReuseIdentifier: OTRBuddyApprovalCell.reuseIdentifier())
if (ZomComposeViewController.openInGroupMode) {
ZomComposeViewController.openInGroupMode = false
self.wasOpenedInGroupMode = true
self.groupButtonPressed(self)
navigationItem.title = ""
} else {
navigationItem.title = NSLocalizedString("Choose a Friend", comment: "When selecting friend")
let nib = UINib(nibName: "ImageActionButtonCell", bundle: OTRAssets.resourcesBundle)
self.tableView.register(nib, forCellReuseIdentifier: ZomComposeViewController.imageActionButtonCellIdentifier)
if let cell = self.tableView.dequeueReusableCell(withIdentifier: ZomComposeViewController.imageActionButtonCellIdentifier) as? ZomImageActionButtonCell {
cell.actionLabel.text = NSLocalizedString("Create a Group", comment: "Cell text for creating a group")
cell.iconLabel.backgroundColor = UIColor(netHex: 0xff7ed321)
self.tableViewHeader.addStackedSubview(cell, identifier: ZomComposeViewController.imageActionCreateGroupIdentifier, gravity: .bottom, height: OTRBuddyInfoCellHeight, callback: {
self.groupButtonPressed(cell)
})
cell.translatesAutoresizingMaskIntoConstraints = true
cell.contentView.translatesAutoresizingMaskIntoConstraints = true
}
if let cell = self.tableView.dequeueReusableCell(withIdentifier: ZomComposeViewController.imageActionButtonCellIdentifier) as? ZomImageActionButtonCell {
cell.actionLabel.text = ADD_BUDDY_STRING()
cell.iconLabel.text = ""
cell.iconLabel.backgroundColor = GlobalTheme.shared.mainThemeColor
self.tableViewHeader.addStackedSubview(cell, identifier: ZomComposeViewController.imageActionAddFriendIdentifier, gravity: .bottom, height: OTRBuddyInfoCellHeight, callback: {
let accounts = OTRAccountsManager.allAccounts()
self.addBuddy(accounts)
})
cell.translatesAutoresizingMaskIntoConstraints = true
cell.contentView.translatesAutoresizingMaskIntoConstraints = true
}
// Remove the "create group" option from navigation bar
self.navigationItem.rightBarButtonItems = nil
}
}
override open func didSetupMappings(_ handler: OTRYapViewHandler) {
super.didSetupMappings(handler)
if (handler == self.viewHandler) {
// If we have not done so, register our extension and change the viewHandler to our own.
if registerZomSortedView() {
useZomSortedView()
}
}
}
override open func viewDidLayoutSubviews() {
// Hide the upstream add friends option
let hideAddFriends = !(parent is UINavigationController)
self.tableViewHeader.setView(ADD_BUDDY_STRING(), hidden: true)
self.tableViewHeader.setView(JOIN_GROUP_STRING(), hidden: true)
self.tableViewHeader.setView(ZomComposeViewController.imageActionCreateGroupIdentifier, hidden: hideAddFriends)
self.tableViewHeader.setView(ZomComposeViewController.imageActionAddFriendIdentifier, hidden: hideAddFriends)
}
override open func updateInboxArchiveFilteringAndShowArchived(_ showArchived: Bool) {
super.updateInboxArchiveFilteringAndShowArchived(showArchived)
OTRDatabaseManager.shared.writeConnection?.asyncReadWrite({ (transaction) in
if let fvt = transaction.ext(ZomComposeViewController.filteredExtensionName) as? YapDatabaseFilteredViewTransaction {
fvt.setFiltering(self.getFilteringBlock(showArchived), versionTag:NSUUID().uuidString)
}
})
self.view.setNeedsLayout()
}
func registerZomSortedView() -> Bool {
// This sets up a database view that is identical to the original "OTRAllBuddiesDatabaseView" but
// with the difference that XMPPBuddies that are avaiting approval are ordered to the top of the list.
//
if OTRDatabaseManager.shared.database?.registeredExtension(ZomComposeViewController.extensionName) == nil {
if let originalView:YapDatabaseAutoView = OTRDatabaseManager.sharedInstance().database?.registeredExtension(OTRAllBuddiesDatabaseViewExtensionName) as? YapDatabaseAutoView {
let sorting = YapDatabaseViewSorting.withObjectBlock({ (transaction, group, collection1, group1, object1, collection2, group2, object2) -> ComparisonResult in
let askingApproval1 = (object1 as? OTRXMPPBuddy)?.askingForApproval ?? false
let askingApproval2 = (object2 as? OTRXMPPBuddy)?.askingForApproval ?? false
if (askingApproval1 && !askingApproval2) {
return .orderedAscending
} else if (!askingApproval1 && askingApproval2) {
return .orderedDescending
}
let pendingApproval1 = (object1 as? OTRXMPPBuddy)?.pendingApproval ?? false
let pendingApproval2 = (object2 as? OTRXMPPBuddy)?.pendingApproval ?? false
if (pendingApproval1 && !pendingApproval2) {
return .orderedAscending
} else if (!pendingApproval1 && pendingApproval2) {
return .orderedDescending
}
if let buddy1 = (object1 as? OTRXMPPBuddy), let buddy2 = (object2 as? OTRXMPPBuddy) {
let name1 = (buddy1.displayName.count > 0) ? buddy1.displayName : buddy1.username
let name2 = (buddy2.displayName.count > 0) ? buddy2.displayName : buddy2.username
return name1.caseInsensitiveCompare(name2)
}
let blockObject:AnyObject = originalView.sorting.block as AnyObject
let originalBlock = unsafeBitCast(blockObject, to: ObjcYapDatabaseViewSortingWithObjectBlock.self)
return originalBlock(transaction, group, collection1, group1, object1, collection2, group2, object2)
})
let grouping = YapDatabaseViewGrouping.withObjectBlock({ (transaction, collection, key, object) -> String? in
let blockObject:AnyObject = originalView.grouping.block as AnyObject
let originalBlock = unsafeBitCast(blockObject, to: ObjcYapDatabaseViewGroupingWithObjectBlock.self)
var group = originalBlock(transaction, collection, key, object)
if group == nil, let buddy = object as? OTRXMPPBuddy, buddy.askingForApproval {
group = OTRBuddyGroup
}
return group
})
let options = YapDatabaseViewOptions()
options.isPersistent = false
let newView = YapDatabaseAutoView(grouping: grouping, sorting: sorting, versionTag: NSUUID().uuidString, options: options)
OTRDatabaseManager.sharedInstance().database?.register(newView, withName: ZomComposeViewController.extensionName)
}
}
if OTRDatabaseManager.shared.database?.registeredExtension(ZomComposeViewController.filteredExtensionName) == nil, OTRDatabaseManager.shared.database?.registeredExtension(OTRArchiveFilteredBuddiesName) != nil {
let options = YapDatabaseViewOptions()
options.isPersistent = false
let filtering = getFilteringBlock(false)
let filteredView = YapDatabaseFilteredView(parentViewName: ZomComposeViewController.extensionName, filtering: filtering, versionTag: NSUUID().uuidString, options: options)
OTRDatabaseManager.sharedInstance().database?.register(filteredView, withName: ZomComposeViewController.filteredExtensionName)
return true
}
return false
}
func useZomSortedView() {
self.viewHandler = OTRYapViewHandler(databaseConnection: OTRDatabaseManager.shared.longLivedReadOnlyConnection!, databaseChangeNotificationName: DatabaseNotificationName.LongLivedTransactionChanges)
if let viewHandler = self.viewHandler {
viewHandler.delegate = self as? OTRYapViewHandlerDelegateProtocol
viewHandler.setup(ZomComposeViewController.filteredExtensionName, groups: [OTRBuddyGroup])
}
}
open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let threadOwner = super.threadOwner(at: indexPath, with: tableView) as? OTRXMPPBuddy, threadOwner.askingForApproval {
let cell = tableView.dequeueReusableCell(withIdentifier: OTRBuddyApprovalCell.reuseIdentifier(), for: indexPath)
if let cell = cell as? OTRBuddyApprovalCell {
cell.actionBlock = { (cell:OTRBuddyApprovalCell?, approved:Bool) -> Void in
//TODO Fixme: quick hack to get going
if let tabController = self.tabBarController as? ZomMainTabbedViewController {
if let conversationController = tabController.viewControllers?[0] as? OTRConversationViewController {
conversationController.handleSubscriptionRequest(threadOwner, approved: approved)
}
}
}
cell.selectionStyle = .none
cell.avatarImageView.layer.cornerRadius = (80.0-2.0*OTRBuddyImageCellPadding)/2.0
cell.setThread(threadOwner)
}
return cell
}
return super.tableView(tableView, cellForRowAt: indexPath)
}
open override func addBuddy(_ accountsAbleToAddBuddies: [OTRAccount]?) {
if let accounts = accountsAbleToAddBuddies {
if (accounts.count > 0)
{
ZomNewBuddyViewController.addBuddyToDefaultAccount(self.navigationController)
}
}
}
open override func groupButtonPressed(_ sender: Any!) {
let storyboard = UIStoryboard(name: "OTRComposeGroup", bundle: OTRAssets.resourcesBundle)
if let vc = storyboard.instantiateInitialViewController() as? OTRComposeGroupViewController {
vc.delegate = self as? OTRComposeGroupViewControllerDelegate
self.navigationController?.pushViewController(vc, animated: (sender as? UIViewController != self))
}
}
override open func groupSelectionCancelled(_ composeViewController: OTRComposeGroupViewController!) {
if composeViewController != nil && wasOpenedInGroupMode {
dismiss(animated: true, completion: nil)
}
}
}
| mpl-2.0 |
xdliu002/TAC_communication | 20160407/LoginAndRegister/LoginAndRegister/LoginViewController.swift | 1 | 6715 | //
// LoginViewController.swift
// LoginAndRegister
//
// Created by FOWAFOLO on 16/4/7.
// Copyright © 2016年 TAC. All rights reserved.
//
import UIKit
import SnapKit
class LoginViewController: UIViewController {
//MARK: - UI Components
var superView = UIView()
let backgroundImage = UIImageView()
let logoImage = UIImageView()
let logoLabel = UILabel()
let userIcon = UIImageView()
let userText = UITextField()
let passIcon = UIImageView()
let passText = UITextField()
let loginButton = UIButton()
let wechatButton = UIButton()
let weboButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
superView = self.view
//TODO: configure UI
configeUI()
}
//MARK: - Functions
func configeUI() {
//MARK: backgroundImage
backgroundImage.image = UIImage(named: "loginBack")
superView.addSubview(backgroundImage)
backgroundImage.snp_makeConstraints { (make) in
// make.left.right.top.bottom.equalTo(superView)
make.size.equalTo(superView)
make.center.equalTo(superView)
}
//MARK: logoImage
logoImage.image = UIImage(named: "Logo-LoginView")
superView.addSubview(logoImage)
logoImage.snp_makeConstraints { (make) in
make.top.equalTo(superView).offset(61)
make.width.height.equalTo(140)
make.centerX.equalTo(superView)
}
// superView.bringSubviewToFront(logoImage)
//MARK: logoLabel
logoLabel.text = "Carols"
logoLabel.textColor = UIColor.GlobalRedColor()
logoLabel.font = UIFont.systemFontOfSize(30)
superView.addSubview(logoLabel)
logoLabel.snp_makeConstraints { (make) in
make.top.equalTo(logoImage.snp_bottom).offset(3)
make.centerX.equalTo(superView)
}
userIcon.image = UIImage(named: "user")
passIcon.image = UIImage(named: "lock")
// userText.placeholder = "Phone Number"
userText.attributedPlaceholder = NSAttributedString(string: "Phone Number", attributes: [NSForegroundColorAttributeName: UIColor.GlobalGray()])
userText.textAlignment = .Center
superView.addSubview(userText)
userText.snp_makeConstraints { (make) in
make.top.equalTo(logoLabel.snp_bottom).offset(51)
make.centerX.equalTo(superView)
make.left.equalTo(superView).offset(100)
make.right.equalTo(superView).offset(-100)
}
superView.addSubview(userIcon)
userIcon.snp_makeConstraints { (make) in
make.width.height.equalTo(24)
make.right.equalTo(userText.snp_left).offset(-5)
make.centerY.equalTo(userText)
}
let line1 = UIView()
line1.backgroundColor = UIColor.GlobalRedColor()
superView.addSubview(line1)
line1.snp_makeConstraints { (make) in
make.height.equalTo(1.5)
make.left.equalTo(userIcon).offset(-5)
make.right.equalTo(userText).offset(5)
make.top.equalTo(userIcon.snp_bottom).offset(5)
}
// passText.placeholder = "Password"
passText.attributedPlaceholder = NSAttributedString(string: "Password", attributes: [NSForegroundColorAttributeName: UIColor.GlobalGray()])
passText.textAlignment = .Center
superView.addSubview(passText)
passText.snp_makeConstraints { (make) in
make.top.equalTo(line1.snp_bottom).offset(26)
make.centerX.equalTo(superView)
make.left.equalTo(superView).offset(100)
make.right.equalTo(superView).offset(-100)
}
superView.addSubview(passIcon)
passIcon.snp_makeConstraints { (make) in
make.width.height.equalTo(24)
make.right.equalTo(userText.snp_left).offset(-5)
make.centerY.equalTo(passText)
}
let line2 = UIView()
line2.backgroundColor = UIColor.GlobalRedColor()
superView.addSubview(line2)
line2.snp_makeConstraints { (make) in
make.height.width.centerX.equalTo(line1)
make.top.equalTo(passIcon.snp_bottom).offset(5)
}
loginButton.setTitle("Login", forState: .Normal)
loginButton.layer.cornerRadius = 20
loginButton.backgroundColor = UIColor.GlobalRedColor()
loginButton.addTarget(self, action: #selector(LoginViewController.loginButtonClicked), forControlEvents: .TouchUpInside)
superView.addSubview(loginButton)
loginButton.snp_makeConstraints { (make) in
make.top.equalTo(line2.snp_bottom).offset(70)
make.centerX.equalTo(superView)
make.height.equalTo(35)
make.width.equalTo(119)
}
let jumpButton = UIButton()
jumpButton.setTitle("Jump to Register", forState: .Normal)
jumpButton.addTarget(self, action: #selector(LoginViewController.jumpButtonClicked), forControlEvents: .TouchUpInside)
superView.addSubview(jumpButton)
jumpButton.snp_makeConstraints { (make) in
make.top.equalTo(line2.snp_bottom).offset(5)
make.centerX.equalTo(superView)
}
let loginDescription = UILabel()
loginDescription.text = "Login By"
loginDescription.textColor = UIColor.grayColor()
superView.addSubview(loginDescription)
loginDescription.snp_makeConstraints { (make) in
make.top.equalTo(loginButton.snp_bottom).offset(44)
make.centerX.equalTo(superView)
}
wechatButton.setImage(UIImage(named: "wechat"), forState: .Normal)
superView.addSubview(wechatButton)
wechatButton.snp_makeConstraints { (make) in
make.right.equalTo(superView.snp_centerX).offset(-7.5)
make.top.equalTo(loginDescription.snp_bottom).offset(36)
make.height.equalTo(44)
make.width.equalTo(55)
}
weboButton.setImage(UIImage(named: "weibo"), forState: .Normal)
superView.addSubview(weboButton)
weboButton.snp_makeConstraints { (make) in
make.height.width.top.equalTo(wechatButton)
make.left.equalTo(superView.snp_centerX).offset(7.5)
}
}
func loginButtonClicked() {
print("loginButtonClicked")
}
func jumpButtonClicked() {
let destination = SingUpViewController()
self.presentViewController(destination, animated: true, completion: nil)
}
}
| mit |
bmichotte/HSTracker | HSTracker/Utility/Algorithm.swift | 2 | 4018 | //
// Algorithm.swift
// HSTracker
//
// Created by Istvan Fehervari on 20/03/2017.
// Copyright © 2017 Benjamin Michotte. All rights reserved.
//
import Foundation
/// integer power function operator
precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ^^ : PowerPrecedence
func ^^ (radix: Int, power: Int) -> Int {
return Int(pow(Double(radix), Double(power)))
}
// MARK: - Data structures
/// Data structure that handles element in a LIFO way
public class Stack<T> {
private var data = [T]()
public var count: Int {
return data.count
}
public func push(_ element: T) {
data.append(element)
}
public func peek() -> T? {
return data.last
}
public func pop() -> T? {
if self.count == 0 {
return nil
}
return data.removeLast()
}
}
/// Node for linked list containers
public class Node<T> {
var value: T
var next: Node<T>?
weak var previous: Node<T>?
init(value: T) {
self.value = value
}
}
/// Data structure that stores element in a linked list
public class LinkedList<T> {
fileprivate var head: Node<T>?
private var tail: Node<T>?
private var _count: Int = 0
public var isEmpty: Bool {
return head == nil
}
public var first: Node<T>? {
return head
}
public var last: Node<T>? {
return tail
}
public func append(_ value: T) {
let newNode = Node(value: value)
if let tailNode = tail {
newNode.previous = tailNode
tailNode.next = newNode
} else {
head = newNode
}
tail = newNode
_count += 1
}
public func appendAll(_ collection: [T]) {
for i in collection {
self.append(i)
}
}
public func nodeAt(index: Int) -> Node<T>? {
if self._count <= index {
return nil
}
if index >= 0 {
var node = head
var i = index
while node != nil {
if i == 0 { return node }
i -= 1
node = node!.next
}
}
return nil
}
public func clear() {
head = nil
tail = nil
_count = 0
}
public func remove(node: Node<T>) -> T {
let prev = node.previous
let next = node.next
if let prev = prev {
prev.next = next
} else {
head = next
}
next?.previous = prev
if next == nil {
tail = prev
}
self._count -= 1
node.previous = nil
node.next = nil
return node.value
}
public func remove(at: Int) {
if let node = nodeAt(index: at) {
_ = remove(node: node)
}
}
public var count: Int {
return self._count
}
}
/**
* Thread-safe queue implementation
*/
public class ConcurrentQueue<T> {
private var elements = LinkedList<T>()
private let accessQueue = DispatchQueue(label: "be.michotte.hstracker.concurrentQueue")
public func enqueue(value: T) {
self.accessQueue.sync {
self.elements.append(value)
}
}
public func enqueueAll(collection: [T]) {
self.accessQueue.sync {
self.elements.appendAll(collection)
}
}
public func dequeue() -> T? {
var result: T?
self.accessQueue.sync {
if let head = self.elements.first {
result = self.elements.remove(node: head)
}
}
return result
}
public var count: Int {
var result = 0
self.accessQueue.sync {
result = self.elements.count
}
return result
}
public func clear() {
self.accessQueue.sync {
self.elements.clear()
}
}
}
| mit |
LKY769215561/KYHandMade | KYHandMade/Pods/DynamicColor/Sources/DynamicColor+Mixing.swift | 1 | 5654 | /*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
// MARK: Mixing Colors
public extension DynamicColor {
/**
Mixes the given color object with the receiver.
Specifically, takes the average of each of the RGB components, optionally weighted by the given percentage.
- Parameter color: A color object to mix with the receiver.
- Parameter weight: The weight specifies the amount of the given color object (between 0 and 1).
The default value is 0.5, which means that half the given color and half the receiver color object should be used.
0.25 means that a quarter of the given color object and three quarters of the receiver color object should be used.
- Parameter colorspace: The color space used to mix the colors. By default it uses the RBG color space.
- Returns: A color object corresponding to the two colors object mixed together.
*/
public final func mixed(withColor color: DynamicColor, weight: CGFloat = 0.5, inColorSpace colorspace: DynamicColorSpace = .rgb) -> DynamicColor {
let normalizedWeight = clip(weight, 0, 1)
switch colorspace {
case .lab:
return mixedLab(withColor: color, weight: normalizedWeight)
case .hsl:
return mixedHSL(withColor: color, weight: normalizedWeight)
case .hsb:
return mixedHSB(withColor: color, weight: normalizedWeight)
case .rgb:
return mixedRGB(withColor: color, weight: normalizedWeight)
}
}
/**
Creates and returns a color object corresponding to the mix of the receiver and an amount of white color, which increases lightness.
- Parameter amount: Float between 0.0 and 1.0. The default amount is equal to 0.2.
- Returns: A lighter DynamicColor.
*/
public final func tinted(amount: CGFloat = 0.2) -> DynamicColor {
return mixed(withColor: .white, weight: amount)
}
/**
Creates and returns a color object corresponding to the mix of the receiver and an amount of black color, which reduces lightness.
- Parameter amount: Float between 0.0 and 1.0. The default amount is equal to 0.2.
- Returns: A darker DynamicColor.
*/
public final func shaded(amount: CGFloat = 0.2) -> DynamicColor {
return mixed(withColor: DynamicColor(red:0, green:0, blue: 0, alpha:1), weight: amount)
}
// MARK: - Convenient Internal Methods
func mixedLab(withColor color: DynamicColor, weight: CGFloat) -> DynamicColor {
let c1 = toLabComponents()
let c2 = color.toLabComponents()
let L = c1.L + weight * (c2.L - c1.L)
let a = c1.a + weight * (c2.a - c1.a)
let b = c1.b + weight * (c2.b - c1.b)
let alpha = alphaComponent + weight * (color.alphaComponent - alphaComponent)
return DynamicColor(L: L, a: a, b: b, alpha: alpha)
}
func mixedHSL(withColor color: DynamicColor, weight: CGFloat) -> DynamicColor {
let c1 = toHSLComponents()
let c2 = color.toHSLComponents()
let h = c1.h + weight * mixedHue(source: c1.h, target: c2.h)
let s = c1.s + weight * (c2.s - c1.s)
let l = c1.l + weight * (c2.l - c1.l)
let alpha = alphaComponent + weight * (color.alphaComponent - alphaComponent)
return DynamicColor(hue: h, saturation: s, lightness: l, alpha: alpha)
}
func mixedHSB(withColor color: DynamicColor, weight: CGFloat) -> DynamicColor {
let c1 = toHSBComponents()
let c2 = color.toHSBComponents()
let h = c1.h + weight * mixedHue(source: c1.h, target: c2.h)
let s = c1.s + weight * (c2.s - c1.s)
let b = c1.b + weight * (c2.b - c1.b)
let alpha = alphaComponent + weight * (color.alphaComponent - alphaComponent)
return DynamicColor(hue: h, saturation: s, brightness: b, alpha: alpha)
}
func mixedRGB(withColor color: DynamicColor, weight: CGFloat) -> DynamicColor {
let c1 = toRGBAComponents()
let c2 = color.toRGBAComponents()
let red = c1.r + weight * (c2.r - c1.r)
let green = c1.g + weight * (c2.g - c1.g)
let blue = c1.b + weight * (c2.b - c1.b)
let alpha = alphaComponent + weight * (color.alphaComponent - alphaComponent)
return DynamicColor(red: red, green: green, blue: blue, alpha: alpha)
}
func mixedHue(source: CGFloat, target: CGFloat) -> CGFloat {
if target > source && target - source > 180 {
return target - source + 360
}
else if target < source && source - target > 180 {
return target + 360 - source
}
return target - source
}
}
| apache-2.0 |
koroff/Charts | ChartsRealm/Classes/Data/RealmPieData.swift | 4 | 744 | //
// RealmPieData.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import Charts
import Realm
import Realm.Dynamic
public class RealmPieData: PieChartData
{
public init(results: RLMResults?, xValueField: String, dataSets: [IChartDataSet]?)
{
if results == nil
{
super.init(xVals: [String](), dataSets: dataSets)
}
else
{
super.init(xVals: RealmChartUtils.toXVals(results: results!, xValueField: xValueField), dataSets: dataSets)
}
}
} | apache-2.0 |
OneBestWay/EasyCode | Example/touchMeIn-completed/TouchMeIn/MasterViewController.swift | 1 | 7358 | /*
* Copyright (c) 2017 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
import CoreData
class MasterViewController: UIViewController, UITableViewDelegate {
@IBOutlet var tableView: UITableView!
var isAuthenticated = false
var managedObjectContext: NSManagedObjectContext!
var didReturnFromBackground = false
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = editButtonItem
view.alpha = 0
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(insertNewObject(_:)))
navigationItem.rightBarButtonItem = addButton
NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActive(_:)), name: .UIApplicationWillResignActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive(_:)), name: .UIApplicationDidBecomeActive, object: nil)
}
@IBAction func unwindSegue(_ segue: UIStoryboardSegue) {
isAuthenticated = true
view.alpha = 1.0
}
func appWillResignActive(_ notification : Notification) {
view.alpha = 0
isAuthenticated = false
didReturnFromBackground = true
}
func appDidBecomeActive(_ notification : Notification) {
if didReturnFromBackground {
showLoginView()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
showLoginView()
}
func showLoginView() {
if !isAuthenticated {
performSegue(withIdentifier: "loginView", sender: self)
}
}
func insertNewObject(_ sender: AnyObject) {
let context = fetchedResultsController.managedObjectContext
guard let entityName = fetchedResultsController.fetchRequest.entity?.name else {
return
}
let newNote = NSEntityDescription.insertNewObject(forEntityName: entityName, into: context) as! Note
newNote.date = Date()
newNote.noteText = "New Note"
do {
try context.save()
} catch {
print("Error inserting data \(error)")
}
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
guard let indexPath = tableView.indexPathForSelectedRow else {
return
}
let note = fetchedResultsController.object(at: indexPath)
(segue.destination as! DetailViewController).note = note
}
}
// MARK: - Table View
@IBAction func logoutAction(_ sender: AnyObject) {
isAuthenticated = false
performSegue(withIdentifier: "loginView", sender: self)
}
// MARK: - Fetched results controller
lazy var fetchedResultsController: NSFetchedResultsController<Note> = {
let fetchRequest = Note.fetchRequest() as! NSFetchRequest<Note>
fetchRequest.fetchBatchSize = 20
let sortDescriptor = NSSortDescriptor(key: "date", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master")
fetchedResultsController.delegate = self
do {
try fetchedResultsController.performFetch()
} catch let error {
print(error)
}
return fetchedResultsController
}()
}
// MARK: - UITableViewDelegate
extension MasterViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return self.fetchedResultsController.sections?.count ?? 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections![section] as NSFetchedResultsSectionInfo
return sectionInfo.numberOfObjects
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell
let note = self.fetchedResultsController.object(at: indexPath)
configure(cell, with: note)
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let context = self.fetchedResultsController.managedObjectContext
context.delete(self.fetchedResultsController.object(at: indexPath))
do {
try context.save()
} catch let error1 as NSError {
print("Error editing the table \(error1)")
abort()
}
}
}
func configure(_ cell: UITableViewCell, with note: Note) {
cell.textLabel!.text = note.noteText.description
}
}
extension MasterViewController: NSFetchedResultsControllerDelegate {
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
switch type {
case .insert:
tableView.insertSections([sectionIndex], with: .fade)
case .delete:
tableView.deleteSections([sectionIndex], with: .fade)
default:
return
}
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .insert:
tableView.insertRows(at: [newIndexPath!], with: .fade)
case .delete:
tableView.deleteRows(at: [indexPath!], with: .fade)
case .update:
guard let cell = tableView.cellForRow(at: indexPath!), let note = anObject as? Note else {
return
}
configure(cell, with: note)
case .move:
tableView.deleteRows(at: [indexPath!], with: .fade)
tableView.insertRows(at: [newIndexPath!], with: .fade)
}
}
}
| mit |
hughbe/swift | stdlib/public/core/Mirror.swift | 4 | 34763 | //===--- Mirror.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
//
//===----------------------------------------------------------------------===//
// FIXME: ExistentialCollection needs to be supported before this will work
// without the ObjC Runtime.
/// Representation of the sub-structure and optional "display style"
/// of any arbitrary subject instance.
///
/// Describes the parts---such as stored properties, collection
/// elements, tuple elements, or the active enumeration case---that
/// make up a particular instance. May also supply a "display style"
/// property that suggests how this structure might be rendered.
///
/// Mirrors are used by playgrounds and the debugger.
public struct Mirror {
/// Representation of descendant classes that don't override
/// `customMirror`.
///
/// Note that the effect of this setting goes no deeper than the
/// nearest descendant class that overrides `customMirror`, which
/// in turn can determine representation of *its* descendants.
internal enum _DefaultDescendantRepresentation {
/// Generate a default mirror for descendant classes that don't
/// override `customMirror`.
///
/// This case is the default.
case generated
/// Suppress the representation of descendant classes that don't
/// override `customMirror`.
///
/// This option may be useful at the root of a class cluster, where
/// implementation details of descendants should generally not be
/// visible to clients.
case suppressed
}
/// Representation of ancestor classes.
///
/// A `CustomReflectable` class can control how its mirror will
/// represent ancestor classes by initializing the mirror with a
/// `AncestorRepresentation`. This setting has no effect on mirrors
/// reflecting value type instances.
public enum AncestorRepresentation {
/// Generate a default mirror for all ancestor classes.
///
/// This case is the default.
///
/// - Note: This option generates default mirrors even for
/// ancestor classes that may implement `CustomReflectable`'s
/// `customMirror` requirement. To avoid dropping an ancestor class
/// customization, an override of `customMirror` should pass
/// `ancestorRepresentation: .Customized(super.customMirror)` when
/// initializing its `Mirror`.
case generated
/// Use the nearest ancestor's implementation of `customMirror` to
/// create a mirror for that ancestor. Other classes derived from
/// such an ancestor are given a default mirror.
///
/// The payload for this option should always be
/// "`{ super.customMirror }`":
///
/// var customMirror: Mirror {
/// return Mirror(
/// self,
/// children: ["someProperty": self.someProperty],
/// ancestorRepresentation: .Customized({ super.customMirror })) // <==
/// }
case customized(() -> Mirror)
/// Suppress the representation of all ancestor classes. The
/// resulting `Mirror`'s `superclassMirror` is `nil`.
case suppressed
}
/// Reflect upon the given `subject`.
///
/// If the dynamic type of `subject` conforms to `CustomReflectable`,
/// the resulting mirror is determined by its `customMirror` property.
/// Otherwise, the result is generated by the language.
///
/// - Note: If the dynamic type of `subject` has value semantics,
/// subsequent mutations of `subject` will not observable in
/// `Mirror`. In general, though, the observability of such
/// mutations is unspecified.
public init(reflecting subject: Any) {
if case let customized as CustomReflectable = subject {
self = customized.customMirror
} else {
self = Mirror(
legacy: _reflect(subject),
subjectType: type(of: subject))
}
}
/// An element of the reflected instance's structure. The optional
/// `label` may be used when appropriate, e.g. to represent the name
/// of a stored property or of an active `enum` case, and will be
/// used for lookup when `String`s are passed to the `descendant`
/// method.
public typealias Child = (label: String?, value: Any)
/// The type used to represent sub-structure.
///
/// Depending on your needs, you may find it useful to "upgrade"
/// instances of this type to `AnyBidirectionalCollection` or
/// `AnyRandomAccessCollection`. For example, to display the last
/// 20 children of a mirror if they can be accessed efficiently, you
/// might write:
///
/// if let b = AnyBidirectionalCollection(someMirror.children) {
/// var i = xs.index(b.endIndex, offsetBy: -20,
/// limitedBy: b.startIndex) ?? b.startIndex
/// while i != xs.endIndex {
/// print(b[i])
/// b.formIndex(after: &i)
/// }
/// }
public typealias Children = AnyCollection<Child>
/// A suggestion of how a `Mirror`'s `subject` is to be interpreted.
///
/// Playgrounds and the debugger will show a representation similar
/// to the one used for instances of the kind indicated by the
/// `DisplayStyle` case name when the `Mirror` is used for display.
public enum DisplayStyle {
case `struct`, `class`, `enum`, tuple, optional, collection
case dictionary, `set`
}
static func _noSuperclassMirror() -> Mirror? { return nil }
/// Returns the legacy mirror representing the part of `subject`
/// corresponding to the superclass of `staticSubclass`.
internal static func _legacyMirror(
_ subject: AnyObject, asClass targetSuperclass: AnyClass) -> _Mirror? {
// get a legacy mirror and the most-derived type
var cls: AnyClass = type(of: subject)
var clsMirror = _reflect(subject)
// Walk up the chain of mirrors/classes until we find staticSubclass
while let superclass: AnyClass = _getSuperclass(cls) {
guard let superclassMirror = clsMirror._superMirror() else { break }
if superclass == targetSuperclass { return superclassMirror }
clsMirror = superclassMirror
cls = superclass
}
return nil
}
@_semantics("optimize.sil.specialize.generic.never")
@inline(never)
@_versioned
internal static func _superclassIterator<Subject>(
_ subject: Subject, _ ancestorRepresentation: AncestorRepresentation
) -> () -> Mirror? {
if let subjectClass = Subject.self as? AnyClass,
let superclass = _getSuperclass(subjectClass) {
switch ancestorRepresentation {
case .generated:
return {
self._legacyMirror(_unsafeDowncastToAnyObject(fromAny: subject), asClass: superclass).map {
Mirror(legacy: $0, subjectType: superclass)
}
}
case .customized(let makeAncestor):
return {
Mirror(_unsafeDowncastToAnyObject(fromAny: subject), subjectClass: superclass,
ancestor: makeAncestor())
}
case .suppressed:
break
}
}
return Mirror._noSuperclassMirror
}
/// Represent `subject` with structure described by `children`,
/// using an optional `displayStyle`.
///
/// If `subject` is not a class instance, `ancestorRepresentation`
/// is ignored. Otherwise, `ancestorRepresentation` determines
/// whether ancestor classes will be represented and whether their
/// `customMirror` implementations will be used. By default, a
/// representation is automatically generated and any `customMirror`
/// implementation is bypassed. To prevent bypassing customized
/// ancestors, `customMirror` overrides should initialize the
/// `Mirror` with:
///
/// ancestorRepresentation: .customized({ super.customMirror })
///
/// - Note: The traversal protocol modeled by `children`'s indices
/// (`ForwardIndex`, `BidirectionalIndex`, or
/// `RandomAccessIndex`) is captured so that the resulting
/// `Mirror`'s `children` may be upgraded later. See the failable
/// initializers of `AnyBidirectionalCollection` and
/// `AnyRandomAccessCollection` for details.
public init<Subject, C : Collection>(
_ subject: Subject,
children: C,
displayStyle: DisplayStyle? = nil,
ancestorRepresentation: AncestorRepresentation = .generated
) where C.Element == Child
// FIXME(ABI) (Revert Where Clauses): Remove these
, C.SubSequence : Collection, C.SubSequence.Indices : Collection, C.Indices : Collection
{
self.subjectType = Subject.self
self._makeSuperclassMirror = Mirror._superclassIterator(
subject, ancestorRepresentation)
self.children = Children(children)
self.displayStyle = displayStyle
self._defaultDescendantRepresentation
= subject is CustomLeafReflectable ? .suppressed : .generated
}
/// Represent `subject` with child values given by
/// `unlabeledChildren`, using an optional `displayStyle`. The
/// result's child labels will all be `nil`.
///
/// This initializer is especially useful for the mirrors of
/// collections, e.g.:
///
/// extension MyArray : CustomReflectable {
/// var customMirror: Mirror {
/// return Mirror(self, unlabeledChildren: self, displayStyle: .collection)
/// }
/// }
///
/// If `subject` is not a class instance, `ancestorRepresentation`
/// is ignored. Otherwise, `ancestorRepresentation` determines
/// whether ancestor classes will be represented and whether their
/// `customMirror` implementations will be used. By default, a
/// representation is automatically generated and any `customMirror`
/// implementation is bypassed. To prevent bypassing customized
/// ancestors, `customMirror` overrides should initialize the
/// `Mirror` with:
///
/// ancestorRepresentation: .Customized({ super.customMirror })
///
/// - Note: The traversal protocol modeled by `children`'s indices
/// (`ForwardIndex`, `BidirectionalIndex`, or
/// `RandomAccessIndex`) is captured so that the resulting
/// `Mirror`'s `children` may be upgraded later. See the failable
/// initializers of `AnyBidirectionalCollection` and
/// `AnyRandomAccessCollection` for details.
public init<Subject, C : Collection>(
_ subject: Subject,
unlabeledChildren: C,
displayStyle: DisplayStyle? = nil,
ancestorRepresentation: AncestorRepresentation = .generated
)
// FIXME(ABI) (Revert Where Clauses): Remove these two clauses
where C.SubSequence : Collection, C.Indices : Collection
{
self.subjectType = Subject.self
self._makeSuperclassMirror = Mirror._superclassIterator(
subject, ancestorRepresentation)
let lazyChildren =
unlabeledChildren.lazy.map { Child(label: nil, value: $0) }
self.children = Children(lazyChildren)
self.displayStyle = displayStyle
self._defaultDescendantRepresentation
= subject is CustomLeafReflectable ? .suppressed : .generated
}
/// Represent `subject` with labeled structure described by
/// `children`, using an optional `displayStyle`.
///
/// Pass a dictionary literal with `String` keys as `children`. Be
/// aware that although an *actual* `Dictionary` is
/// arbitrarily-ordered, the ordering of the `Mirror`'s `children`
/// will exactly match that of the literal you pass.
///
/// If `subject` is not a class instance, `ancestorRepresentation`
/// is ignored. Otherwise, `ancestorRepresentation` determines
/// whether ancestor classes will be represented and whether their
/// `customMirror` implementations will be used. By default, a
/// representation is automatically generated and any `customMirror`
/// implementation is bypassed. To prevent bypassing customized
/// ancestors, `customMirror` overrides should initialize the
/// `Mirror` with:
///
/// ancestorRepresentation: .customized({ super.customMirror })
///
/// - Note: The resulting `Mirror`'s `children` may be upgraded to
/// `AnyRandomAccessCollection` later. See the failable
/// initializers of `AnyBidirectionalCollection` and
/// `AnyRandomAccessCollection` for details.
public init<Subject>(
_ subject: Subject,
children: DictionaryLiteral<String, Any>,
displayStyle: DisplayStyle? = nil,
ancestorRepresentation: AncestorRepresentation = .generated
) {
self.subjectType = Subject.self
self._makeSuperclassMirror = Mirror._superclassIterator(
subject, ancestorRepresentation)
let lazyChildren = children.lazy.map { Child(label: $0.0, value: $0.1) }
self.children = Children(lazyChildren)
self.displayStyle = displayStyle
self._defaultDescendantRepresentation
= subject is CustomLeafReflectable ? .suppressed : .generated
}
/// The static type of the subject being reflected.
///
/// This type may differ from the subject's dynamic type when `self`
/// is the `superclassMirror` of another mirror.
public let subjectType: Any.Type
/// A collection of `Child` elements describing the structure of the
/// reflected subject.
public let children: Children
/// Suggests a display style for the reflected subject.
public let displayStyle: DisplayStyle?
public var superclassMirror: Mirror? {
return _makeSuperclassMirror()
}
internal let _makeSuperclassMirror: () -> Mirror?
internal let _defaultDescendantRepresentation: _DefaultDescendantRepresentation
}
/// A type that explicitly supplies its own mirror.
///
/// You can create a mirror for any type using the `Mirror(reflect:)`
/// initializer, but if you are not satisfied with the mirror supplied for
/// your type by default, you can make it conform to `CustomReflectable` and
/// return a custom `Mirror` instance.
public protocol CustomReflectable {
/// The custom mirror for this instance.
///
/// If this type has value semantics, the mirror should be unaffected by
/// subsequent mutations of the instance.
var customMirror: Mirror { get }
}
/// A type that explicitly supplies its own mirror, but whose
/// descendant classes are not represented in the mirror unless they
/// also override `customMirror`.
public protocol CustomLeafReflectable : CustomReflectable {}
//===--- Addressing -------------------------------------------------------===//
/// A protocol for legitimate arguments to `Mirror`'s `descendant`
/// method.
///
/// Do not declare new conformances to this protocol; they will not
/// work as expected.
// FIXME(ABI)#49 (Sealed Protocols): this protocol should be "non-open" and you shouldn't be able to
// create conformances.
public protocol MirrorPath {}
extension Int : MirrorPath {}
extension String : MirrorPath {}
extension Mirror {
internal struct _Dummy : CustomReflectable {
var mirror: Mirror
var customMirror: Mirror { return mirror }
}
/// Return a specific descendant of the reflected subject, or `nil`
/// Returns a specific descendant of the reflected subject, or `nil`
/// if no such descendant exists.
///
/// A `String` argument selects the first `Child` with a matching label.
/// An integer argument *n* select the *n*th `Child`. For example:
///
/// var d = Mirror(reflecting: x).descendant(1, "two", 3)
///
/// is equivalent to:
///
/// var d = nil
/// let children = Mirror(reflecting: x).children
/// if let p0 = children.index(children.startIndex,
/// offsetBy: 1, limitedBy: children.endIndex) {
/// let grandChildren = Mirror(reflecting: children[p0].value).children
/// SeekTwo: for g in grandChildren {
/// if g.label == "two" {
/// let greatGrandChildren = Mirror(reflecting: g.value).children
/// if let p1 = greatGrandChildren.index(
/// greatGrandChildren.startIndex,
/// offsetBy: 3, limitedBy: greatGrandChildren.endIndex) {
/// d = greatGrandChildren[p1].value
/// }
/// break SeekTwo
/// }
/// }
/// }
///
/// As you can see, complexity for each element of the argument list
/// depends on the argument type and capabilities of the collection
/// used to initialize the corresponding subject's parent's mirror.
/// Each `String` argument results in a linear search. In short,
/// this function is suitable for exploring the structure of a
/// `Mirror` in a REPL or playground, but don't expect it to be
/// efficient.
public func descendant(
_ first: MirrorPath, _ rest: MirrorPath...
) -> Any? {
var result: Any = _Dummy(mirror: self)
for e in [first] + rest {
let children = Mirror(reflecting: result).children
let position: Children.Index
if case let label as String = e {
position = children.index { $0.label == label } ?? children.endIndex
}
else if let offset = (e as? Int).map({ IntMax($0) }) ?? (e as? IntMax) {
position = children.index(children.startIndex,
offsetBy: offset,
limitedBy: children.endIndex) ?? children.endIndex
}
else {
_preconditionFailure(
"Someone added a conformance to MirrorPath; that privilege is reserved to the standard library")
}
if position == children.endIndex { return nil }
result = children[position].value
}
return result
}
}
//===--- Legacy _Mirror Support -------------------------------------------===//
extension Mirror.DisplayStyle {
/// Construct from a legacy `_MirrorDisposition`
internal init?(legacy: _MirrorDisposition) {
switch legacy {
case .`struct`: self = .`struct`
case .`class`: self = .`class`
case .`enum`: self = .`enum`
case .tuple: self = .tuple
case .aggregate: return nil
case .indexContainer: self = .collection
case .keyContainer: self = .dictionary
case .membershipContainer: self = .`set`
case .container: preconditionFailure("unused!")
case .optional: self = .optional
case .objCObject: self = .`class`
}
}
}
internal func _isClassSuperMirror(_ t: Any.Type) -> Bool {
#if _runtime(_ObjC)
return t == _ClassSuperMirror.self || t == _ObjCSuperMirror.self
#else
return t == _ClassSuperMirror.self
#endif
}
extension _Mirror {
internal func _superMirror() -> _Mirror? {
if self.count > 0 {
let childMirror = self[0].1
if _isClassSuperMirror(type(of: childMirror)) {
return childMirror
}
}
return nil
}
}
/// When constructed using the legacy reflection infrastructure, the
/// resulting `Mirror`'s `children` collection will always be
/// upgradable to `AnyRandomAccessCollection` even if it doesn't
/// exhibit appropriate performance. To avoid this pitfall, convert
/// mirrors to use the new style, which only present forward
/// traversal in general.
internal extension Mirror {
/// An adapter that represents a legacy `_Mirror`'s children as
/// a `Collection` with integer `Index`. Note that the performance
/// characteristics of the underlying `_Mirror` may not be
/// appropriate for random access! To avoid this pitfall, convert
/// mirrors to use the new style, which only present forward
/// traversal in general.
internal struct LegacyChildren : RandomAccessCollection {
typealias Indices = CountableRange<Int>
init(_ oldMirror: _Mirror) {
self._oldMirror = oldMirror
}
var startIndex: Int {
return _oldMirror._superMirror() == nil ? 0 : 1
}
var endIndex: Int { return _oldMirror.count }
subscript(position: Int) -> Child {
let (label, childMirror) = _oldMirror[position]
return (label: label, value: childMirror.value)
}
internal let _oldMirror: _Mirror
}
/// Initialize for a view of `subject` as `subjectClass`.
///
/// - parameter ancestor: A Mirror for a (non-strict) ancestor of
/// `subjectClass`, to be injected into the resulting hierarchy.
///
/// - parameter legacy: Either `nil`, or a legacy mirror for `subject`
/// as `subjectClass`.
internal init(
_ subject: AnyObject,
subjectClass: AnyClass,
ancestor: Mirror,
legacy legacyMirror: _Mirror? = nil
) {
if ancestor.subjectType == subjectClass
|| ancestor._defaultDescendantRepresentation == .suppressed {
self = ancestor
}
else {
let legacyMirror = legacyMirror ?? Mirror._legacyMirror(
subject, asClass: subjectClass)!
self = Mirror(
legacy: legacyMirror,
subjectType: subjectClass,
makeSuperclassMirror: {
_getSuperclass(subjectClass).map {
Mirror(
subject,
subjectClass: $0,
ancestor: ancestor,
legacy: legacyMirror._superMirror())
}
})
}
}
internal init(
legacy legacyMirror: _Mirror,
subjectType: Any.Type,
makeSuperclassMirror: (() -> Mirror?)? = nil
) {
if let makeSuperclassMirror = makeSuperclassMirror {
self._makeSuperclassMirror = makeSuperclassMirror
}
else if let subjectSuperclass = _getSuperclass(subjectType) {
self._makeSuperclassMirror = {
legacyMirror._superMirror().map {
Mirror(legacy: $0, subjectType: subjectSuperclass) }
}
}
else {
self._makeSuperclassMirror = Mirror._noSuperclassMirror
}
self.subjectType = subjectType
self.children = Children(LegacyChildren(legacyMirror))
self.displayStyle = DisplayStyle(legacy: legacyMirror.disposition)
self._defaultDescendantRepresentation = .generated
}
}
//===--- QuickLooks -------------------------------------------------------===//
/// The sum of types that can be used as a Quick Look representation.
public enum PlaygroundQuickLook {
/// Plain text.
case text(String)
/// An integer numeric value.
case int(Int64)
/// An unsigned integer numeric value.
case uInt(UInt64)
/// A single precision floating-point numeric value.
case float(Float32)
/// A double precision floating-point numeric value.
case double(Float64)
// FIXME: Uses an Any to avoid coupling a particular Cocoa type.
/// An image.
case image(Any)
// FIXME: Uses an Any to avoid coupling a particular Cocoa type.
/// A sound.
case sound(Any)
// FIXME: Uses an Any to avoid coupling a particular Cocoa type.
/// A color.
case color(Any)
// FIXME: Uses an Any to avoid coupling a particular Cocoa type.
/// A bezier path.
case bezierPath(Any)
// FIXME: Uses an Any to avoid coupling a particular Cocoa type.
/// An attributed string.
case attributedString(Any)
// FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type.
/// A rectangle.
case rectangle(Float64, Float64, Float64, Float64)
// FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type.
/// A point.
case point(Float64, Float64)
// FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type.
/// A size.
case size(Float64, Float64)
/// A boolean value.
case bool(Bool)
// FIXME: Uses explicit values to avoid coupling a particular Cocoa type.
/// A range.
case range(Int64, Int64)
// FIXME: Uses an Any to avoid coupling a particular Cocoa type.
/// A GUI view.
case view(Any)
// FIXME: Uses an Any to avoid coupling a particular Cocoa type.
/// A graphical sprite.
case sprite(Any)
/// A Uniform Resource Locator.
case url(String)
/// Raw data that has already been encoded in a format the IDE understands.
case _raw([UInt8], String)
}
extension PlaygroundQuickLook {
/// Initialize for the given `subject`.
///
/// If the dynamic type of `subject` conforms to
/// `CustomPlaygroundQuickLookable`, returns the result of calling
/// its `customPlaygroundQuickLook` property. Otherwise, returns
/// a `PlaygroundQuickLook` synthesized for `subject` by the
/// language. Note that in some cases the result may be
/// `.Text(String(reflecting: subject))`.
///
/// - Note: If the dynamic type of `subject` has value semantics,
/// subsequent mutations of `subject` will not observable in
/// `Mirror`. In general, though, the observability of such
/// mutations is unspecified.
public init(reflecting subject: Any) {
if let customized = subject as? CustomPlaygroundQuickLookable {
self = customized.customPlaygroundQuickLook
}
else if let customized = subject as? _DefaultCustomPlaygroundQuickLookable {
self = customized._defaultCustomPlaygroundQuickLook
}
else {
if let q = _reflect(subject).quickLookObject {
self = q
}
else {
self = .text(String(reflecting: subject))
}
}
}
}
/// A type that explicitly supplies its own playground Quick Look.
///
/// A Quick Look can be created for an instance of any type by using the
/// `PlaygroundQuickLook(reflecting:)` initializer. If you are not satisfied
/// with the representation supplied for your type by default, you can make it
/// conform to the `CustomPlaygroundQuickLookable` protocol and provide a
/// custom `PlaygroundQuickLook` instance.
public protocol CustomPlaygroundQuickLookable {
/// A custom playground Quick Look for this instance.
///
/// If this type has value semantics, the `PlaygroundQuickLook` instance
/// should be unaffected by subsequent mutations.
var customPlaygroundQuickLook: PlaygroundQuickLook { get }
}
// A workaround for <rdar://problem/26182650>
// FIXME(ABI)#50 (Dynamic Dispatch for Class Extensions) though not if it moves out of stdlib.
public protocol _DefaultCustomPlaygroundQuickLookable {
var _defaultCustomPlaygroundQuickLook: PlaygroundQuickLook { get }
}
//===--- General Utilities ------------------------------------------------===//
// This component could stand alone, but is used in Mirror's public interface.
/// A lightweight collection of key-value pairs.
///
/// Use a `DictionaryLiteral` instance when you need an ordered collection of
/// key-value pairs and don't require the fast key lookup that the
/// `Dictionary` type provides. Unlike key-value pairs in a true dictionary,
/// neither the key nor the value of a `DictionaryLiteral` instance must
/// conform to the `Hashable` protocol.
///
/// You initialize a `DictionaryLiteral` instance using a Swift dictionary
/// literal. Besides maintaining the order of the original dictionary literal,
/// `DictionaryLiteral` also allows duplicates keys. For example:
///
/// let recordTimes: DictionaryLiteral = ["Florence Griffith-Joyner": 10.49,
/// "Evelyn Ashford": 10.76,
/// "Evelyn Ashford": 10.79,
/// "Marlies Gohr": 10.81]
/// print(recordTimes.first!)
/// // Prints "("Florence Griffith-Joyner", 10.49)"
///
/// Some operations that are efficient on a dictionary are slower when using
/// `DictionaryLiteral`. In particular, to find the value matching a key, you
/// must search through every element of the collection. The call to
/// `index(where:)` in the following example must traverse the whole
/// collection to find the element that matches the predicate:
///
/// let runner = "Marlies Gohr"
/// if let index = recordTimes.index(where: { $0.0 == runner }) {
/// let time = recordTimes[index].1
/// print("\(runner) set a 100m record of \(time) seconds.")
/// } else {
/// print("\(runner) couldn't be found in the records.")
/// }
/// // Prints "Marlies Gohr set a 100m record of 10.81 seconds."
///
/// Dictionary Literals as Function Parameters
/// ------------------------------------------
///
/// When calling a function with a `DictionaryLiteral` parameter, you can pass
/// a Swift dictionary literal without causing a `Dictionary` to be created.
/// This capability can be especially important when the order of elements in
/// the literal is significant.
///
/// For example, you could create an `IntPairs` structure that holds a list of
/// two-integer tuples and use an initializer that accepts a
/// `DictionaryLiteral` instance.
///
/// struct IntPairs {
/// var elements: [(Int, Int)]
///
/// init(_ elements: DictionaryLiteral<Int, Int>) {
/// self.elements = Array(elements)
/// }
/// }
///
/// When you're ready to create a new `IntPairs` instance, use a dictionary
/// literal as the parameter to the `IntPairs` initializer. The
/// `DictionaryLiteral` instance preserves the order of the elements as
/// passed.
///
/// let pairs = IntPairs([1: 2, 1: 1, 3: 4, 2: 1])
/// print(pairs.elements)
/// // Prints "[(1, 2), (1, 1), (3, 4), (2, 1)]"
public struct DictionaryLiteral<Key, Value> : ExpressibleByDictionaryLiteral {
/// Creates a new `DictionaryLiteral` instance from the given dictionary
/// literal.
///
/// The order of the key-value pairs is kept intact in the resulting
/// `DictionaryLiteral` instance.
public init(dictionaryLiteral elements: (Key, Value)...) {
self._elements = elements
}
internal let _elements: [(Key, Value)]
}
/// `Collection` conformance that allows `DictionaryLiteral` to
/// interoperate with the rest of the standard library.
extension DictionaryLiteral : RandomAccessCollection {
public typealias Indices = CountableRange<Int>
/// The position of the first element in a nonempty collection.
///
/// If the `DictionaryLiteral` instance is empty, `startIndex` is equal to
/// `endIndex`.
public var startIndex: Int { return 0 }
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// If the `DictionaryLiteral` instance is empty, `endIndex` is equal to
/// `startIndex`.
public var endIndex: Int { return _elements.endIndex }
// FIXME(ABI)#174 (Type checker): a typealias is needed to prevent <rdar://20248032>
/// The element type of a `DictionaryLiteral`: a tuple containing an
/// individual key-value pair.
public typealias Element = (key: Key, value: Value)
/// Accesses the element at the specified position.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
/// - Returns: The key-value pair at position `position`.
public subscript(position: Int) -> Element {
return _elements[position]
}
}
extension String {
/// Creates a string representing the given value.
///
/// Use this initializer to convert an instance of any type to its preferred
/// representation as a `String` instance. The initializer creates the
/// string representation of `instance` in one of the following ways,
/// depending on its protocol conformance:
///
/// - If `instance` conforms to the `TextOutputStreamable` protocol, the
/// result is obtained by calling `instance.write(to: s)` on an empty
/// string `s`.
/// - If `instance` conforms to the `CustomStringConvertible` protocol, the
/// result is `instance.description`.
/// - If `instance` conforms to the `CustomDebugStringConvertible` protocol,
/// the result is `instance.debugDescription`.
/// - An unspecified result is supplied automatically by the Swift standard
/// library.
///
/// For example, this custom `Point` struct uses the default representation
/// supplied by the standard library.
///
/// struct Point {
/// let x: Int, y: Int
/// }
///
/// let p = Point(x: 21, y: 30)
/// print(String(describing: p))
/// // Prints "Point(x: 21, y: 30)"
///
/// After adding `CustomStringConvertible` conformance by implementing the
/// `description` property, `Point` provides its own custom representation.
///
/// extension Point: CustomStringConvertible {
/// var description: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// print(String(describing: p))
/// // Prints "(21, 30)"
public init<Subject>(describing instance: Subject) {
self.init()
_print_unlocked(instance, &self)
}
/// Creates a string with a detailed representation of the given value,
/// suitable for debugging.
///
/// Use this initializer to convert an instance of any type to its custom
/// debugging representation. The initializer creates the string
/// representation of `instance` in one of the following ways, depending on
/// its protocol conformance:
///
/// - If `subject` conforms to the `CustomDebugStringConvertible` protocol,
/// the result is `subject.debugDescription`.
/// - If `subject` conforms to the `CustomStringConvertible` protocol, the
/// result is `subject.description`.
/// - If `subject` conforms to the `TextOutputStreamable` protocol, the
/// result is obtained by calling `subject.write(to: s)` on an empty
/// string `s`.
/// - An unspecified result is supplied automatically by the Swift standard
/// library.
///
/// For example, this custom `Point` struct uses the default representation
/// supplied by the standard library.
///
/// struct Point {
/// let x: Int, y: Int
/// }
///
/// let p = Point(x: 21, y: 30)
/// print(String(reflecting: p))
/// // Prints "p: Point = {
/// // x = 21
/// // y = 30
/// // }"
///
/// After adding `CustomDebugStringConvertible` conformance by implementing
/// the `debugDescription` property, `Point` provides its own custom
/// debugging representation.
///
/// extension Point: CustomDebugStringConvertible {
/// var debugDescription: String {
/// return "Point(x: \(x), y: \(y))"
/// }
/// }
///
/// print(String(reflecting: p))
/// // Prints "Point(x: 21, y: 30)"
public init<Subject>(reflecting subject: Subject) {
self.init()
_debugPrint_unlocked(subject, &self)
}
}
/// Reflection for `Mirror` itself.
extension Mirror : CustomStringConvertible {
public var description: String {
return "Mirror for \(self.subjectType)"
}
}
extension Mirror : CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [:])
}
}
@available(*, unavailable, renamed: "MirrorPath")
public typealias MirrorPathType = MirrorPath
| apache-2.0 |
ryanglobus/Augustus | Augustus/Augustus/AppDelegate.swift | 1 | 2883 | //
// AppDelegate.swift
// Augustus
//
// Created by Ryan Globus on 6/22/15.
// Copyright (c) 2015 Ryan Globus. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
let log = AULog.instance
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
// TODO make below queue proper UI queue/execute in UI queue
// TODO test below
// TODO is below even needed?
self.alertIfEventStorePermissionDenied()
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: AUModel.notificationName), object: nil, queue: nil, using: { (notification: Notification) -> Void in
DispatchQueue.main.async {
self.alertIfEventStorePermissionDenied()
}
})
log.info("did finish launching")
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
log.info("will terminate")
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
}
fileprivate func alertIfEventStorePermissionDenied() {
if AUModel.eventStore.permission == .denied {
let alert = NSAlert()
alert.addButton(withTitle: "Go to System Preferences...")
alert.addButton(withTitle: "Quit")
alert.messageText = "Please grant Augustus access to your calendars."
alert.informativeText = "You must grant Augustus access to your calendars in order to see or create events. To do so, go to System Preferences. Select Calendars in the left pane. Then, in the center pane, click the checkbox next to Augustus. Then restart Augustus."
alert.alertStyle = NSAlertStyle.warning
let response = alert.runModal()
if response == NSAlertFirstButtonReturn {
let scriptSource = "tell application \"System Preferences\"\n" +
"set securityPane to pane id \"com.apple.preference.security\"\n" +
"tell securityPane to reveal anchor \"Privacy\"\n" +
"set the current pane to securityPane\n" +
"activate\n" +
"end tell"
let script = NSAppleScript(source: scriptSource)
let error: AutoreleasingUnsafeMutablePointer<NSDictionary?>? = nil
self.log.info("About to go to System Preferences")
if script?.executeAndReturnError(error) == nil {
self.log.error(error.debugDescription)
}
// TODO now what?
} else {
NSApplication.shared().terminate(self)
}
}
}
}
| gpl-2.0 |
felipedemetrius/WatchMe | WatchMeTests/SerieModelTests.swift | 1 | 2106 | //
// SerieModelTests.swift
// WatchMe
//
// Created by Felipe Silva on 1/23/17.
// Copyright © 2017 Felipe Silva . All rights reserved.
//
import XCTest
@testable import WatchMe
class SerieModelTests: 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 testSerieUpdate() {
let wait = expectation(description: "nt")
SerieRepository.nextTrending { series in
if let serie = series?.first{
serie.update(value: true, key: "watching")
serie.update(value: false, key: "watching")
serie.remove()
}
XCTAssertNotNil(series)
wait.fulfill()
}
waitForExpectations(timeout: 4.0, handler: nil)
}
func testSerieAddRemoveEpisode() {
let wait = expectation(description: "saddrm")
SerieRepository.searchSeries(text: "oa") { series in
if let serie = series?.first{
EpisodeRepository.getEpisodeDetail(slug: "the-oa", season: 1, episode: 1) { episode in
if let episode = episode{
serie.addEpisode(episode: episode)
serie.removeEpisode(episode: episode)
serie.addEpisode(episode: episode)
if let serie = SerieRepository.getLocal(slug: "the-oa") {
serie.remove()
}
}
wait.fulfill()
}
}
}
waitForExpectations(timeout: 6.0, handler: nil)
}
}
| mit |
TwilioDevEd/api-snippets | ip-messaging/tokens/initialization/initialization.swift | 1 | 430 | import TwilioChatClient
// Make a secure request to your backend to retrieve an access token.
// Use an authentication mechanism to prevent token exposure to 3rd parties.
let accessToken = "<your token here>"
TwilioChatClient.chatClient(withToken: accessToken,
properties: nil, delegate: self) {
(result, chatClient) in
if (!result.isSuccessful()) {
// warn the user the initialization didn't succeed
}
}
| mit |
rsaenzi/MyMoviesListApp | MyMoviesListApp/MyMoviesListApp/APIService.swift | 1 | 4287 | //
// APIService.swift
// MyMoviesListApp
//
// Created by Rigoberto Sáenz Imbacuán on 5/28/17.
// Copyright © 2017 Rigoberto Sáenz Imbacuán. All rights reserved.
//
import Foundation
import Moya
import SwiftKeychainWrapper
enum APIService {
case getDeviceCode(clientId: String)
case getToken(code: String, clientId: String, clientSecret: String)
case refreshToken(refreshToken: String, clientId: String, clientSecret: String)
case getPopularMovies(page: Int, pageItems: Int)
case getTextQueryResults(query: String, page: Int, pageItems: Int)
case getImage(imageId: String, apiKey: String)
}
extension APIService: TargetType {
var baseURL: URL {
switch self {
case .getImage:
return URL(string: "http://webservice.fanart.tv/v3")!
default:
return URL(string: "https://api.trakt.tv")!
}}
var path: String {
switch self {
case .getDeviceCode:
return "/oauth/device/code"
case .getToken:
return "/oauth/device/token"
case .refreshToken:
return "/oauth/token"
case .getPopularMovies:
return "/movies/popular"
case .getTextQueryResults:
return "/search/movie"
case .getImage(let imageId, _):
return "/movies/\(imageId)"
}
}
var method: Moya.Method {
switch self {
case .getDeviceCode, .getToken, .refreshToken:
return .post
case .getPopularMovies, .getTextQueryResults, .getImage:
return .get
}
}
var parameters: [String: Any]? {
switch self {
case .getDeviceCode(let clientId):
return ["client_id": clientId]
case .getToken(let code, let clientId, let clientSecret):
return ["code": code,
"client_id": clientId,
"client_secret": clientSecret]
case .refreshToken(let refreshToken, let clientId, let clientSecret):
return ["refresh_token": refreshToken,
"client_id": clientId,
"client_secret": clientSecret,
"grant_type": "refresh_token"]
case .getPopularMovies(let page, let pageItems):
return ["extended": "full",
"page": page,
"limit": pageItems]
case .getTextQueryResults(let query, let page, let pageItems):
return ["query": query,
"extended": "full",
"fields": "title",
"page": page,
"limit": pageItems]
case .getImage( _, let apiKey):
return ["api_key": apiKey]
}
}
var parameterEncoding: ParameterEncoding {
switch self {
case .getDeviceCode, .getToken, .refreshToken:
return JSONEncoding.default
case .getPopularMovies, .getTextQueryResults, .getImage:
return URLEncoding.default
}
}
var sampleData: Data {
return "".utf8Encoded
}
var task: Task {
return .request
}
}
extension APIService {
static let endpointClosure = { (target: APIService) -> Endpoint<APIService> in
let defaultEndpoint = MoyaProvider.defaultEndpointMapping(for: target)
switch target {
case .getPopularMovies, .getTextQueryResults:
guard let accessToken: String = KeychainWrapper.standard.string(forKey: KeychainKey.apiAccessToken.rawValue),
let refreshToken: String = KeychainWrapper.standard.string(forKey: KeychainKey.apiRefreshToken.rawValue) else {
return defaultEndpoint
}
return defaultEndpoint.adding(newHTTPHeaderFields:
["trakt-api-key": APICredentials.traktClientId,
"trakt-api-version": "2",
"Authorization": "Bearer \(accessToken)"])
default:
return defaultEndpoint
}
}
}
| mit |
panadaW/MyNews | MyWb/MyWb/Class/Controllers/Home/HomeCell/UIbutten+EXtention.swift | 1 | 606 | //
// UIbutten+EXtention.swift
// MyWb
//
// Created by 王明申 on 15/10/13.
// Copyright © 2015年 晨曦的Mac. All rights reserved.
//
import UIKit
extension UIButton {
convenience init(title: String, imageName: String, fontSize: CGFloat = 12, color: UIColor = UIColor.darkGrayColor()) {
self.init()
setTitle(title, forState: UIControlState.Normal)
setImage(UIImage(named: imageName), forState: UIControlState.Normal)
setTitleColor(color, forState: UIControlState.Normal)
titleLabel?.font = UIFont.systemFontOfSize(fontSize)
}
} | mit |
acevest/acecode | learn/AcePlay/AcePlay.playground/Sources/Utils.swift | 1 | 161 | import UIKit
public
func printLine(_ title: String) -> Void {
let line = String(format:"-----------------------------------<%@>", title)
print(line)
}
| gpl-2.0 |
gb-6k-house/YsSwift | Sources/Peacock/Utils/SwiftUserDefaults.swift | 1 | 15213 | //
// SwiftyUserDefaults
//
// Copyright (c) 2015-2016 Radosław Pietruszewski
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
public extension UserDefaults {
class Proxy {
fileprivate let defaults: UserDefaults
fileprivate let key: String
fileprivate init(_ defaults: UserDefaults, _ key: String) {
self.defaults = defaults
self.key = key
}
// MARK: Getters
public var object: Any? {
return defaults.object(forKey: key)
}
public var string: String? {
return defaults.string(forKey: key)
}
public var array: [Any]? {
return defaults.array(forKey: key)
}
public var dictionary: [String: Any]? {
return defaults.dictionary(forKey: key)
}
public var data: Data? {
return defaults.data(forKey: key)
}
public var date: Date? {
return object as? Date
}
public var number: NSNumber? {
return defaults.numberForKey(key)
}
public var int: Int? {
return number?.intValue
}
public var double: Double? {
return number?.doubleValue
}
public var bool: Bool? {
return number?.boolValue
}
// MARK: Non-Optional Getters
public var stringValue: String {
return string ?? ""
}
public var arrayValue: [Any] {
return array ?? []
}
public var dictionaryValue: [String: Any] {
return dictionary ?? [:]
}
public var dataValue: Data {
return data ?? Data()
}
public var numberValue: NSNumber {
return number ?? 0
}
public var intValue: Int {
return int ?? 0
}
public var doubleValue: Double {
return double ?? 0
}
public var boolValue: Bool {
return bool ?? false
}
}
/// `NSNumber` representation of a user default
func numberForKey(_ key: String) -> NSNumber? {
return object(forKey: key) as? NSNumber
}
/// Returns getter proxy for `key`
public subscript(key: String) -> Proxy {
return Proxy(self, key)
}
/// Sets value for `key`
public subscript(key: String) -> Any? {
get {
// return untyped Proxy
// (make sure we don't fall into infinite loop)
let proxy: Proxy = self[key]
return proxy
}
set {
guard let newValue = newValue else {
removeObject(forKey: key)
return
}
switch newValue {
// @warning This should always be on top of Int because a cast
// from Double to Int will always succeed.
case let v as Double: self.set(v, forKey: key)
case let v as Int: self.set(v, forKey: key)
case let v as Bool: self.set(v, forKey: key)
case let v as URL: self.set(v, forKey: key)
default: self.set(newValue, forKey: key)
}
}
}
/// Returns `true` if `key` exists
public func hasKey(_ key: String) -> Bool {
return object(forKey: key) != nil
}
/// Removes value for `key`
public func remove(_ key: String) {
removeObject(forKey: key)
}
/// Removes all keys and values from user defaults
/// Use with caution!
/// - Note: This method only removes keys on the receiver `UserDefaults` object.
/// System-defined keys will still be present afterwards.
public func removeAll() {
for (key, _) in dictionaryRepresentation() {
removeObject(forKey: key)
}
}
}
/// Global shortcut for `UserDefaults.standard`
///
/// **Pro-Tip:** If you want to use shared user defaults, just
/// redefine this global shortcut in your app target, like so:
/// ~~~
/// var Defaults = UserDefaults(suiteName: "com.my.app")!
/// ~~~
public let Defaults = UserDefaults.standard
// MARK: - Static keys
/// Extend this class and add your user defaults keys as static constants
/// so you can use the shortcut dot notation (e.g. `Defaults[.yourKey]`)
open class DefaultsKeys {
fileprivate init() {}
}
/// Base class for static user defaults keys. Specialize with value type
/// and pass key name to the initializer to create a key.
open class DefaultsKey<ValueType>: DefaultsKeys {
// TODO: Can we use protocols to ensure ValueType is a compatible type?
public let _key: String
public init(_ key: String) {
self._key = key
super.init()
}
}
extension UserDefaults {
/// This function allows you to create your own custom Defaults subscript. Example: [Int: String]
public func set<T>(_ key: DefaultsKey<T>, _ value: Any?) {
self[key._key] = value
}
}
extension UserDefaults {
/// Returns `true` if `key` exists
public func hasKey<T>(_ key: DefaultsKey<T>) -> Bool {
return object(forKey: key._key) != nil
}
/// Removes value for `key`
public func remove<T>(_ key: DefaultsKey<T>) {
removeObject(forKey: key._key)
}
}
// MARK: Subscripts for specific standard types
// TODO: Use generic subscripts when they become available
extension UserDefaults {
public subscript(key: DefaultsKey<String?>) -> String? {
get { return string(forKey: key._key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<String>) -> String {
get { return string(forKey: key._key) ?? "" }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<Int?>) -> Int? {
get { return numberForKey(key._key)?.intValue }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<Int>) -> Int {
get { return numberForKey(key._key)?.intValue ?? 0 }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<Double?>) -> Double? {
get { return numberForKey(key._key)?.doubleValue }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<Double>) -> Double {
get { return numberForKey(key._key)?.doubleValue ?? 0.0 }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<Bool?>) -> Bool? {
get { return numberForKey(key._key)?.boolValue }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<Bool>) -> Bool {
get { return numberForKey(key._key)?.boolValue ?? false }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<Any?>) -> Any? {
get { return object(forKey: key._key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<Data?>) -> Data? {
get { return data(forKey: key._key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<Data>) -> Data {
get { return data(forKey: key._key) ?? Data() }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<Date?>) -> Date? {
get { return object(forKey: key._key) as? Date }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<URL?>) -> URL? {
get { return url(forKey: key._key) }
set { set(key, newValue) }
}
// TODO: It would probably make sense to have support for statically typed dictionaries (e.g. [String: String])
public subscript(key: DefaultsKey<[String: Any]?>) -> [String: Any]? {
get { return dictionary(forKey: key._key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[String: Any]>) -> [String: Any] {
get { return dictionary(forKey: key._key) ?? [:] }
set { set(key, newValue) }
}
}
// MARK: Static subscripts for array types
extension UserDefaults {
public subscript(key: DefaultsKey<[Any]?>) -> [Any]? {
get { return array(forKey: key._key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[Any]>) -> [Any] {
get { return array(forKey: key._key) ?? [] }
set { set(key, newValue) }
}
}
// We need the <T: AnyObject> and <T: _ObjectiveCBridgeable> variants to
// suppress compiler warnings about NSArray not being convertible to [T]
// AnyObject is for NSData and NSDate, _ObjectiveCBridgeable is for value
// types bridge-able to Foundation types (String, Int, ...)
extension UserDefaults {
public func getArray<T: _ObjectiveCBridgeable>(_ key: DefaultsKey<[T]>) -> [T] {
return array(forKey: key._key) as NSArray? as? [T] ?? []
}
public func getArray<T: _ObjectiveCBridgeable>(_ key: DefaultsKey<[T]?>) -> [T]? {
return array(forKey: key._key) as NSArray? as? [T]
}
public func getArray<T: Any>(_ key: DefaultsKey<[T]>) -> [T] {
return array(forKey: key._key) as NSArray? as? [T] ?? []
}
public func getArray<T: Any>(_ key: DefaultsKey<[T]?>) -> [T]? {
return array(forKey: key._key) as NSArray? as? [T]
}
}
extension UserDefaults {
public subscript(key: DefaultsKey<[String]?>) -> [String]? {
get { return getArray(key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[String]>) -> [String] {
get { return getArray(key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[Int]?>) -> [Int]? {
get { return getArray(key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[Int]>) -> [Int] {
get { return getArray(key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[Double]?>) -> [Double]? {
get { return getArray(key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[Double]>) -> [Double] {
get { return getArray(key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[Bool]?>) -> [Bool]? {
get { return getArray(key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[Bool]>) -> [Bool] {
get { return getArray(key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[Data]?>) -> [Data]? {
get { return getArray(key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[Data]>) -> [Data] {
get { return getArray(key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[Date]?>) -> [Date]? {
get { return getArray(key) }
set { set(key, newValue) }
}
public subscript(key: DefaultsKey<[Date]>) -> [Date] {
get { return getArray(key) }
set { set(key, newValue) }
}
}
// MARK: - Archiving custom types
// MARK: RawRepresentable
extension UserDefaults {
// TODO: Ensure that T.RawValue is compatible
public func archive<T: RawRepresentable>(_ key: DefaultsKey<T>, _ value: T) {
set(key, value.rawValue)
}
public func archive<T: RawRepresentable>(_ key: DefaultsKey<T?>, _ value: T?) {
if let value = value {
set(key, value.rawValue)
} else {
remove(key)
}
}
public func unarchive<T: RawRepresentable>(_ key: DefaultsKey<T?>) -> T? {
return object(forKey: key._key).flatMap { T(rawValue: $0 as! T.RawValue) }
}
public func unarchive<T: RawRepresentable>(_ key: DefaultsKey<T>) -> T? {
return object(forKey: key._key).flatMap { T(rawValue: $0 as! T.RawValue) }
}
}
// MARK: NSCoding
extension UserDefaults {
// TODO: Can we simplify this and ensure that T is NSCoding compliant?
public func archive<T>(_ key: DefaultsKey<T>, _ value: T) {
set(key, NSKeyedArchiver.archivedData(withRootObject: value))
}
public func archive<T>(_ key: DefaultsKey<T?>, _ value: T?) {
if let value = value {
set(key, NSKeyedArchiver.archivedData(withRootObject: value))
} else {
remove(key)
}
}
public func unarchive<T>(_ key: DefaultsKey<T>) -> T? {
return data(forKey: key._key).flatMap { NSKeyedUnarchiver.unarchiveObject(with: $0) } as? T
}
public func unarchive<T>(_ key: DefaultsKey<T?>) -> T? {
return data(forKey: key._key).flatMap { NSKeyedUnarchiver.unarchiveObject(with: $0) } as? T
}
}
// MARK: - Deprecations
infix operator ?= : AssignmentPrecedence
/// If key doesn't exist, sets its value to `expr`
/// - Deprecation: This will be removed in a future release.
/// Please migrate to static keys and use this gist: https://gist.github.com/radex/68de9340b0da61d43e60
/// - Note: This isn't the same as `Defaults.registerDefaults`. This method saves the new value to disk, whereas `registerDefaults` only modifies the defaults in memory.
/// - Note: If key already exists, the expression after ?= isn't evaluated
@available(*, deprecated:1, message:"Please migrate to static keys and use this gist: https://gist.github.com/radex/68de9340b0da61d43e60")
public func ?= (proxy: UserDefaults.Proxy, expr: @autoclosure() -> Any) {
if !proxy.defaults.hasKey(proxy.key) {
proxy.defaults[proxy.key] = expr()
}
}
/// Adds `b` to the key (and saves it as an integer)
/// If key doesn't exist or isn't a number, sets value to `b`
@available(*, deprecated:1, message:"Please migrate to static keys to use this.")
public func += (proxy: UserDefaults.Proxy, b: Int) {
let a = proxy.defaults[proxy.key].intValue
proxy.defaults[proxy.key] = a + b
}
@available(*, deprecated:1, message:"Please migrate to static keys to use this.")
public func += (proxy: UserDefaults.Proxy, b: Double) {
let a = proxy.defaults[proxy.key].doubleValue
proxy.defaults[proxy.key] = a + b
}
/// Icrements key by one (and saves it as an integer)
/// If key doesn't exist or isn't a number, sets value to 1
@available(*, deprecated:1, message:"Please migrate to static keys to use this.")
public postfix func ++ (proxy: UserDefaults.Proxy) {
proxy += 1
}
| mit |
Johennes/firefox-ios | Client/Frontend/Share/ShareExtensionHelper.swift | 1 | 6253 | /* 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 OnePasswordExtension
private let log = Logger.browserLogger
class ShareExtensionHelper: NSObject {
private weak var selectedTab: Tab?
private let selectedURL: NSURL
private var onePasswordExtensionItem: NSExtensionItem!
private let activities: [UIActivity]
init(url: NSURL, tab: Tab?, activities: [UIActivity]) {
self.selectedURL = url
self.selectedTab = tab
self.activities = activities
}
func createActivityViewController(completionHandler: (completed: Bool, activityType: String?) -> Void) -> UIActivityViewController {
var activityItems = [AnyObject]()
let printInfo = UIPrintInfo(dictionary: nil)
let absoluteString = selectedTab?.url?.absoluteString ?? selectedURL.absoluteString
if let absoluteString = absoluteString {
printInfo.jobName = absoluteString
}
printInfo.outputType = .General
activityItems.append(printInfo)
if let tab = selectedTab {
activityItems.append(TabPrintPageRenderer(tab: tab))
}
if let title = selectedTab?.title {
activityItems.append(TitleActivityItemProvider(title: title))
}
activityItems.append(self)
let activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: activities)
// Hide 'Add to Reading List' which currently uses Safari.
// We would also hide View Later, if possible, but the exclusion list doesn't currently support
// third-party activity types (rdar://19430419).
activityViewController.excludedActivityTypes = [
UIActivityTypeAddToReadingList,
]
// This needs to be ready by the time the share menu has been displayed and
// activityViewController(activityViewController:, activityType:) is called,
// which is after the user taps the button. So a million cycles away.
if (ShareExtensionHelper.isPasswordManagerExtensionAvailable()) {
findLoginExtensionItem()
}
activityViewController.completionWithItemsHandler = { activityType, completed, returnedItems, activityError in
if !completed {
completionHandler(completed: completed, activityType: activityType)
return
}
if self.isPasswordManagerActivityType(activityType) {
if let logins = returnedItems {
self.fillPasswords(logins)
}
}
completionHandler(completed: completed, activityType: activityType)
}
return activityViewController
}
}
extension ShareExtensionHelper: UIActivityItemSource {
func activityViewControllerPlaceholderItem(activityViewController: UIActivityViewController) -> AnyObject {
if let displayURL = selectedTab?.displayURL {
return displayURL
}
return selectedURL
}
func activityViewController(activityViewController: UIActivityViewController, itemForActivityType activityType: String) -> AnyObject? {
if isPasswordManagerActivityType(activityType) {
return onePasswordExtensionItem
} else {
// Return the URL for the selected tab. If we are in reader view then decode
// it so that we copy the original and not the internal localhost one.
if let url = selectedTab?.displayURL where ReaderModeUtils.isReaderModeURL(url) {
return ReaderModeUtils.decodeURL(url)
}
return selectedTab?.displayURL ?? selectedURL
}
}
func activityViewController(activityViewController: UIActivityViewController, dataTypeIdentifierForActivityType activityType: String?) -> String {
// Because of our UTI declaration, this UTI now satisfies both the 1Password Extension and the usual NSURL for Share extensions.
return "org.appextension.fill-browser-action"
}
}
private extension ShareExtensionHelper {
static func isPasswordManagerExtensionAvailable() -> Bool {
return OnePasswordExtension.sharedExtension().isAppExtensionAvailable()
}
func isPasswordManagerActivityType(activityType: String?) -> Bool {
if (!ShareExtensionHelper.isPasswordManagerExtensionAvailable()) {
return false
}
// A 'password' substring covers the most cases, such as pwsafe and 1Password.
// com.agilebits.onepassword-ios.extension
// com.app77.ios.pwsafe2.find-login-action-password-actionExtension
// If your extension's bundle identifier does not contain "password", simply submit a pull request by adding your bundle identifier.
return (activityType?.rangeOfString("password") != nil)
|| (activityType == "com.lastpass.ilastpass.LastPassExt")
}
func findLoginExtensionItem() {
guard let selectedWebView = selectedTab?.webView else {
return
}
if selectedWebView.URL?.absoluteString == nil {
return
}
// Add 1Password to share sheet
OnePasswordExtension.sharedExtension().createExtensionItemForWebView(selectedWebView, completion: {(extensionItem, error) -> Void in
if extensionItem == nil {
log.error("Failed to create the password manager extension item: \(error).")
return
}
// Set the 1Password extension item property
self.onePasswordExtensionItem = extensionItem
})
}
func fillPasswords(returnedItems: [AnyObject]) {
guard let selectedWebView = selectedTab?.webView else {
return
}
OnePasswordExtension.sharedExtension().fillReturnedItems(returnedItems, intoWebView: selectedWebView, completion: { (success, returnedItemsError) -> Void in
if !success {
log.error("Failed to fill item into webview: \(returnedItemsError).")
}
})
}
}
| mpl-2.0 |
xedin/swift | test/TypeDecoder/nominal_types.swift | 3 | 3218 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -emit-executable %s -g -o %t/nominal_types -emit-module
// RUN: sed -ne '/\/\/ *DEMANGLE-TYPE: /s/\/\/ *DEMANGLE-TYPE: *//p' < %s > %t/input
// RUN: %lldb-moduleimport-test-with-sdk %t/nominal_types -type-from-mangled=%t/input | %FileCheck %s --check-prefix=CHECK-TYPE
// RUN: sed -ne '/\/\/ *DEMANGLE-DECL: /s/\/\/ *DEMANGLE-DECL: *//p' < %s > %t/input
// RUN: %lldb-moduleimport-test-with-sdk %t/nominal_types -decl-from-mangled=%t/input | %FileCheck %s --check-prefix=CHECK-DECL
struct Outer {
enum Inner {
case a
init() { fatalError() }
}
enum GenericInner<T, U> {
case a
init() { fatalError() }
}
}
enum GenericOuter<T, U> {
case a
init() { fatalError() }
struct Inner {}
struct GenericInner<T, U> {}
}
func blackHole(_: Any...) {}
do {
let x1 = Outer()
let x2 = Outer.Inner()
let x3 = Outer.GenericInner<Int, String>()
blackHole(x1, x2, x3)
}
do {
let x1 = GenericOuter<Int, String>()
let x2 = GenericOuter<Int, String>.Inner()
let x3 = GenericOuter<Int, String>.GenericInner<Float, Double>()
blackHole(x1, x2, x3)
}
protocol P {}
struct Constrained<T : P> {}
func generic<T>(_: Constrained<T>) {}
// DEMANGLE-TYPE: $s13nominal_types5OuterVD
// CHECK-TYPE: Outer
// DEMANGLE-TYPE: $s13nominal_types5OuterV5InnerOD
// CHECK-TYPE: Outer.Inner
// DEMANGLE-TYPE: $s13nominal_types5OuterV12GenericInnerOy_SiSSGD
// DEMANGLE-TYPE: $s13nominal_types5OuterV12GenericInnerOy_xq_GD
// CHECK-TYPE: Outer.GenericInner<Int, String>
// CHECK-TYPE: Outer.GenericInner<τ_0_0, τ_0_1>
// DEMANGLE-TYPE: $s13nominal_types12GenericOuterO5InnerVyxq__GD
// DEMANGLE-TYPE: $s13nominal_types12GenericOuterO0C5InnerVyxq__qd__qd_0_GD
// CHECK-TYPE: GenericOuter<τ_0_0, τ_0_1>.Inner
// CHECK-TYPE: GenericOuter<τ_0_0, τ_0_1>.GenericInner<τ_1_0, τ_1_1>
// DEMANGLE-TYPE: $s13nominal_types12GenericOuterO5InnerVySiSS_GD
// DEMANGLE-TYPE: $s13nominal_types12GenericOuterO0C5InnerVySiSS_SfSdGD
// CHECK-TYPE: GenericOuter<Int, String>.Inner
// CHECK-TYPE: GenericOuter<Int, String>.GenericInner<Float, Double>
// DEMANGLE-TYPE: $s13nominal_types12GenericOuterOyxq_GD
// DEMANGLE-TYPE: $s13nominal_types12GenericOuterOySiSSGD
// CHECK-TYPE: GenericOuter<τ_0_0, τ_0_1>
// CHECK-TYPE: GenericOuter<Int, String>
// DEMANGLE-TYPE: $s13nominal_types11ConstrainedVyxGD
// CHECK-TYPE: Constrained<τ_0_0>
// DEMANGLE-DECL: $s13nominal_types5OuterV
// DEMANGLE-DECL: $s13nominal_types5OuterV5InnerO
// DEMANGLE-DECL: $s13nominal_types5OuterV12GenericInnerO
// DEMANGLE-DECL: $s13nominal_types12GenericOuterO
// DEMANGLE-DECL: $s13nominal_types12GenericOuterO5InnerV
// DEMANGLE-DECL: $s13nominal_types12GenericOuterO0C5InnerV
// DEMANGLE-DECL: $s13nominal_types1PP
// DEMANGLE-DECL: $s13nominal_types11ConstrainedV
// CHECK-DECL: nominal_types.(file).Outer
// CHECK-DECL: nominal_types.(file).Outer.Inner
// CHECK-DECL: nominal_types.(file).Outer.GenericInner
// CHECK-DECL: nominal_types.(file).GenericOuter
// CHECK-DECL: nominal_types.(file).GenericOuter.Inner
// CHECK-DECL: nominal_types.(file).GenericOuter.GenericInner
// CHECK-DECL: nominal_types.(file).P
// CHECK-DECL: nominal_types.(file).Constrained
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.