repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
grigaci/RateMyTalkAtMobOS | RateMyTalkAtMobOS/Classes/GUI/Common/Dialogs/Error/RMTWindowErrorViewController.swift | 1 | 2647 | //
// RMTWindowErrorViewController.swift
// RateMyTalkAtMobOS
//
// Created by Bogdan Iusco on 10/17/14.
// Copyright (c) 2014 Grigaci. All rights reserved.
//
import UIKit
class RMTWindowErrorViewController: UIViewController {
lazy var viewContent: RMTWindowErrorViewContent = {
let view = RMTWindowErrorViewContent(frame: CGRectZero)
view.setTranslatesAutoresizingMaskIntoConstraints(false)
return view
}()
var buttonTapped: (() -> ())?
var error: NSError? {
didSet {
self.updateContentTitleText()
self.updateContentDescriptionText()
}
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.clearColor()
self.view.addSubview(self.viewContent)
self.updateContentButtonText()
self.setupActions()
self.setupConstraints()
}
private func setupActions() {
self.viewContent.button.addTarget(self, action: "handleButtonTap", forControlEvents: UIControlEvents.TouchDown)
}
private func setupConstraints() {
let viewsDictionary = ["content" : self.viewContent]
let constraintsH = NSLayoutConstraint.constraintsWithVisualFormat("H:|[content]|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
self.view.addConstraints(constraintsH)
let constraintsV = NSLayoutConstraint.constraintsWithVisualFormat("V:|[content]|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDictionary)
self.view.addConstraints(constraintsV)
}
func handleButtonTap() {
if let buttonClose = self.buttonTapped {
buttonClose()
}
}
private func updateContentTitleText() {
if let displayError = self.error {
if let title = displayError.titleText {
self.viewContent.titleTextView.text = title
}
}
}
private func updateContentDescriptionText() {
if let displayError = self.error {
if let description = displayError.descriptionText {
self.viewContent.descriptionTextView.text = description
}
}
}
private func updateContentButtonText() {
self.viewContent.button.setTitle("OK", forState: UIControlState.Normal)
}
}
| bsd-3-clause | 6c703b3749f2d7a666167d0567f1a782 | 30.511905 | 163 | 0.653192 | 5.200393 | false | false | false | false |
CherishSmile/ZYBase | ZYBaseDemo/SubVCS/HMSegmentVC.swift | 1 | 2930 | //
// HMSegmentVC.swift
// ZYBase
//
// Created by MAC on 2017/5/11.
// Copyright © 2017年 Mzywx. All rights reserved.
//
import UIKit
class HMSegmentVC: BaseDemoVC,UITableViewDelegate,UITableViewDataSource {
fileprivate var dataArr:Array<String> = []
fileprivate var tab:UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
creatSubviews()
dataInit(type: "first")
}
func dataInit(type:String) {
for i in 0..<20 {
dataArr.append(type+"\(i)")
}
tab.reloadData()
}
func creatSubviews() {
let segment = HMSegmentedControl(sectionTitles: ["first","second","third"])
segment?.selectedSegmentIndex = 0
segment?.selectionIndicatorLocation = .down
segment?.selectionIndicatorColor = .green
segment?.selectionIndicatorHeight = 2
segment?.selectedTitleTextAttributes = [NSForegroundColorAttributeName : UIColor.green]
view.addSubview(segment!)
segment?.snp.makeConstraints({ (make) in
make.top.equalTo(NAV_HEIGHT)
make.left.right.equalToSuperview()
make.height.equalTo(40)
})
segment?.indexChangeBlock = {
index in
printLog(index)
self.dataArr.removeAll()
if index==1 {
self.dataInit(type: "second")
}else if index==2 {
self.dataInit(type: "third")
}else{
self.dataInit(type: "first")
}
}
tab = creatTabView(self, .plain)
tab.snp.makeConstraints { (make) in
make.left.right.bottom.equalToSuperview()
make.top.equalTo((segment?.snp.bottom)!)
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cellid")
if cell==nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "cellid")
}
cell?.textLabel?.text = dataArr[indexPath.row]
return cell!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// 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.
}
*/
}
| mit | 8de21302bd506d07017032e21fa60306 | 27.696078 | 106 | 0.593099 | 4.96944 | false | false | false | false |
brentsimmons/Evergreen | Mac/MainWindow/Timeline/TimelineContainerViewController.swift | 1 | 7190 | //
// TimelineContainerViewController.swift
// NetNewsWire
//
// Created by Brent Simmons on 2/14/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import AppKit
import Account
import Articles
protocol TimelineContainerViewControllerDelegate: AnyObject {
func timelineSelectionDidChange(_: TimelineContainerViewController, articles: [Article]?, mode: TimelineSourceMode)
func timelineRequestedWebFeedSelection(_: TimelineContainerViewController, webFeed: WebFeed)
func timelineInvalidatedRestorationState(_: TimelineContainerViewController)
}
final class TimelineContainerViewController: NSViewController {
@IBOutlet weak var viewOptionsPopUpButton: NSPopUpButton!
@IBOutlet weak var newestToOldestMenuItem: NSMenuItem!
@IBOutlet weak var oldestToNewestMenuItem: NSMenuItem!
@IBOutlet weak var groupByFeedMenuItem: NSMenuItem!
@IBOutlet weak var readFilteredButton: NSButton!
@IBOutlet var containerView: TimelineContainerView!
var currentTimelineViewController: TimelineViewController? {
didSet {
let view = currentTimelineViewController?.view
if containerView.contentView === view {
return
}
containerView.contentView = view
view?.window?.recalculateKeyViewLoop()
}
}
weak var delegate: TimelineContainerViewControllerDelegate?
var isReadFiltered: Bool? {
guard let currentTimelineViewController = currentTimelineViewController, mode(for: currentTimelineViewController) == .regular else { return nil }
return regularTimelineViewController.isReadFiltered
}
var isCleanUpAvailable: Bool {
guard let currentTimelineViewController = currentTimelineViewController, mode(for: currentTimelineViewController) == .regular else { return false }
return regularTimelineViewController.isCleanUpAvailable
}
lazy var regularTimelineViewController = {
return TimelineViewController(delegate: self)
}()
private lazy var searchTimelineViewController: TimelineViewController = {
let viewController = TimelineViewController(delegate: self)
viewController.showsSearchResults = true
return viewController
}()
override func viewDidLoad() {
super.viewDidLoad()
setRepresentedObjects(nil, mode: .regular)
showTimeline(for: .regular)
makeMenuItemTitleLarger(newestToOldestMenuItem)
makeMenuItemTitleLarger(oldestToNewestMenuItem)
makeMenuItemTitleLarger(groupByFeedMenuItem)
updateViewOptionsPopUpButton()
NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil)
}
// MARK: - Notifications
@objc func userDefaultsDidChange(_ note: Notification) {
updateViewOptionsPopUpButton()
}
// MARK: - API
func setRepresentedObjects(_ objects: [AnyObject]?, mode: TimelineSourceMode) {
timelineViewController(for: mode).representedObjects = objects
updateReadFilterButton()
}
func showTimeline(for mode: TimelineSourceMode) {
currentTimelineViewController = timelineViewController(for: mode)
}
func regularTimelineViewControllerHasRepresentedObjects(_ representedObjects: [AnyObject]?) -> Bool {
// Use this to find out if the regular timeline view already has the specified representedObjects.
// This is used in determining whether a search should end.
// The sidebar may think that the selection has changed, and therefore search should end —
// but it could be that the regular timeline already has these representedObjects,
// and therefore the selection hasn’t actually changed,
// and therefore search shouldn’t end.
// https://github.com/brentsimmons/NetNewsWire/issues/791
if representedObjects == nil && regularTimelineViewController.representedObjects == nil {
return true
}
guard let currentObjects = regularTimelineViewController.representedObjects, let representedObjects = representedObjects else {
return false
}
if currentObjects.count != representedObjects.count {
return false
}
for object in representedObjects {
guard let _ = currentObjects.firstIndex(where: { $0 === object } ) else {
return false
}
}
return true
}
func cleanUp() {
regularTimelineViewController.cleanUp()
}
func toggleReadFilter() {
regularTimelineViewController.toggleReadFilter()
updateReadFilterButton()
}
// MARK: State Restoration
func saveState(to state: inout [AnyHashable : Any]) {
regularTimelineViewController.saveState(to: &state)
}
func restoreState(from state: [AnyHashable : Any]) {
regularTimelineViewController.restoreState(from: state)
updateReadFilterButton()
}
}
extension TimelineContainerViewController: TimelineDelegate {
func timelineSelectionDidChange(_ timelineViewController: TimelineViewController, selectedArticles: [Article]?) {
delegate?.timelineSelectionDidChange(self, articles: selectedArticles, mode: mode(for: timelineViewController))
}
func timelineRequestedWebFeedSelection(_: TimelineViewController, webFeed: WebFeed) {
delegate?.timelineRequestedWebFeedSelection(self, webFeed: webFeed)
}
func timelineInvalidatedRestorationState(_: TimelineViewController) {
delegate?.timelineInvalidatedRestorationState(self)
}
}
private extension TimelineContainerViewController {
func makeMenuItemTitleLarger(_ menuItem: NSMenuItem) {
menuItem.attributedTitle = NSAttributedString(string: menuItem.title,
attributes: [NSAttributedString.Key.font: NSFont.controlContentFont(ofSize: NSFont.systemFontSize)])
}
func timelineViewController(for mode: TimelineSourceMode) -> TimelineViewController {
switch mode {
case .regular:
return regularTimelineViewController
case .search:
return searchTimelineViewController
}
}
func mode(for timelineViewController: TimelineViewController) -> TimelineSourceMode {
if timelineViewController === regularTimelineViewController {
return .regular
}
else if timelineViewController === searchTimelineViewController {
return .search
}
assertionFailure("Expected timelineViewController to match either regular or search timelineViewController, but it doesn’t.")
return .regular // Should never get here.
}
func updateViewOptionsPopUpButton() {
if AppDefaults.shared.timelineSortDirection == .orderedAscending {
newestToOldestMenuItem.state = .off
oldestToNewestMenuItem.state = .on
viewOptionsPopUpButton.setTitle(oldestToNewestMenuItem.title)
} else {
newestToOldestMenuItem.state = .on
oldestToNewestMenuItem.state = .off
viewOptionsPopUpButton.setTitle(newestToOldestMenuItem.title)
}
if AppDefaults.shared.timelineGroupByFeed == true {
groupByFeedMenuItem.state = .on
} else {
groupByFeedMenuItem.state = .off
}
}
func updateReadFilterButton() {
guard currentTimelineViewController == regularTimelineViewController else {
readFilteredButton.isHidden = true
return
}
guard let isReadFiltered = regularTimelineViewController.isReadFiltered else {
readFilteredButton.isHidden = true
return
}
readFilteredButton.isHidden = false
if isReadFiltered {
readFilteredButton.image = AppAssets.filterActive
} else {
readFilteredButton.image = AppAssets.filterInactive
}
}
}
| mit | bb3bcd31c6c67ef22b266bac8a721297 | 31.789954 | 149 | 0.782482 | 4.52489 | false | false | false | false |
diegosanchezr/Chatto | ChattoApp/ChattoApp/FakeMessageSender.swift | 1 | 2881 | /*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
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 Chatto
import ChattoAdditions
public class FakeMessageSender {
public var onMessageChanged: ((message: MessageModelProtocol) -> Void)?
public func sendMessages(messages: [MessageModelProtocol]) {
for message in messages {
self.fakeMessageStatus(message)
}
}
public func sendMessage(message: MessageModelProtocol) {
self.fakeMessageStatus(message)
}
private func fakeMessageStatus(message: MessageModelProtocol) {
switch message.status {
case .Success:
break
case .Failed:
self.updateMessage(message, status: .Sending)
self.fakeMessageStatus(message)
case .Sending:
switch arc4random_uniform(100) % 5 {
case 0:
if arc4random_uniform(100) % 2 == 0 {
self.updateMessage(message, status: .Failed)
} else {
self.updateMessage(message, status: .Success)
}
default:
let delaySeconds: Double = Double(arc4random_uniform(1200)) / 1000.0
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delaySeconds * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
self.fakeMessageStatus(message)
}
}
}
}
private func updateMessage(message: MessageModelProtocol, status: MessageStatus) {
if message.status != status {
message.status = status
self.notifyMessageChanged(message)
}
}
private func notifyMessageChanged(message: MessageModelProtocol) {
self.onMessageChanged?(message: message)
}
}
| mit | f598546492408811d24ae1484c47fe71 | 35.935897 | 108 | 0.670948 | 4.825796 | false | false | false | false |
tjw/swift | stdlib/public/SDK/Foundation/IndexPath.swift | 4 | 29726 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
import _SwiftFoundationOverlayShims
/**
`IndexPath` represents the path to a specific node in a tree of nested array collections.
Each index in an index path represents the index into an array of children from one node in the tree to another, deeper, node.
*/
public struct IndexPath : ReferenceConvertible, Equatable, Hashable, MutableCollection, RandomAccessCollection, Comparable, ExpressibleByArrayLiteral {
public typealias ReferenceType = NSIndexPath
public typealias Element = Int
public typealias Index = Array<Int>.Index
public typealias Indices = DefaultIndices<IndexPath>
fileprivate enum Storage : ExpressibleByArrayLiteral {
typealias Element = Int
case empty
case single(Int)
case pair(Int, Int)
case array([Int])
init(arrayLiteral elements: Int...) {
self.init(elements)
}
init(_ elements: [Int]) {
switch elements.count {
case 0:
self = .empty
break
case 1:
self = .single(elements[0])
break
case 2:
self = .pair(elements[0], elements[1])
break
default:
self = .array(elements)
break
}
}
func dropLast() -> Storage {
switch self {
case .empty:
return .empty
case .single(_):
return .empty
case .pair(let first, _):
return .single(first)
case .array(let indexes):
switch indexes.count {
case 3:
return .pair(indexes[0], indexes[1])
default:
return .array(Array<Int>(indexes.dropLast()))
}
}
}
mutating func append(_ other: Int) {
switch self {
case .empty:
self = .single(other)
break
case .single(let first):
self = .pair(first, other)
break
case .pair(let first, let second):
self = .array([first, second, other])
break
case .array(let indexes):
self = .array(indexes + [other])
break
}
}
mutating func append(contentsOf other: Storage) {
switch self {
case .empty:
switch other {
case .empty:
// DO NOTHING
break
case .single(let rhsIndex):
self = .single(rhsIndex)
break
case .pair(let rhsFirst, let rhsSecond):
self = .pair(rhsFirst, rhsSecond)
break
case .array(let rhsIndexes):
self = .array(rhsIndexes)
break
}
break
case .single(let lhsIndex):
switch other {
case .empty:
// DO NOTHING
break
case .single(let rhsIndex):
self = .pair(lhsIndex, rhsIndex)
break
case .pair(let rhsFirst, let rhsSecond):
self = .array([lhsIndex, rhsFirst, rhsSecond])
break
case .array(let rhsIndexes):
self = .array([lhsIndex] + rhsIndexes)
break
}
break
case .pair(let lhsFirst, let lhsSecond):
switch other {
case .empty:
// DO NOTHING
break
case .single(let rhsIndex):
self = .array([lhsFirst, lhsSecond, rhsIndex])
break
case .pair(let rhsFirst, let rhsSecond):
self = .array([lhsFirst, lhsSecond, rhsFirst, rhsSecond])
break
case .array(let rhsIndexes):
self = .array([lhsFirst, lhsSecond] + rhsIndexes)
break
}
break
case .array(let lhsIndexes):
switch other {
case .empty:
// DO NOTHING
break
case .single(let rhsIndex):
self = .array(lhsIndexes + [rhsIndex])
break
case .pair(let rhsFirst, let rhsSecond):
self = .array(lhsIndexes + [rhsFirst, rhsSecond])
break
case .array(let rhsIndexes):
self = .array(lhsIndexes + rhsIndexes)
break
}
break
}
}
mutating func append(contentsOf other: [Int]) {
switch self {
case .empty:
switch other.count {
case 0:
// DO NOTHING
break
case 1:
self = .single(other[0])
break
case 2:
self = .pair(other[0], other[1])
break
default:
self = .array(other)
break
}
break
case .single(let first):
switch other.count {
case 0:
// DO NOTHING
break
case 1:
self = .pair(first, other[0])
break
default:
self = .array([first] + other)
break
}
break
case .pair(let first, let second):
switch other.count {
case 0:
// DO NOTHING
break
default:
self = .array([first, second] + other)
break
}
break
case .array(let indexes):
self = .array(indexes + other)
break
}
}
subscript(_ index: Int) -> Int {
get {
switch self {
case .empty:
fatalError("Index \(index) out of bounds of count 0")
break
case .single(let first):
precondition(index == 0, "Index \(index) out of bounds of count 1")
return first
case .pair(let first, let second):
precondition(index >= 0 && index < 2, "Index \(index) out of bounds of count 2")
return index == 0 ? first : second
case .array(let indexes):
return indexes[index]
}
}
set {
switch self {
case .empty:
fatalError("Index \(index) out of bounds of count 0")
break
case .single(_):
precondition(index == 0, "Index \(index) out of bounds of count 1")
self = .single(newValue)
break
case .pair(let first, let second):
precondition(index >= 0 && index < 2, "Index \(index) out of bounds of count 2")
if index == 0 {
self = .pair(newValue, second)
} else {
self = .pair(first, newValue)
}
break
case .array(let indexes_):
var indexes = indexes_
indexes[index] = newValue
self = .array(indexes)
break
}
}
}
subscript(range: Range<Index>) -> Storage {
get {
switch self {
case .empty:
switch (range.lowerBound, range.upperBound) {
case (0, 0):
return .empty
default:
fatalError("Range \(range) is out of bounds of count 0")
}
case .single(let index):
switch (range.lowerBound, range.upperBound) {
case (0, 0): fallthrough
case (1, 1):
return .empty
case (0, 1):
return .single(index)
default:
fatalError("Range \(range) is out of bounds of count 1")
}
return self
case .pair(let first, let second):
switch (range.lowerBound, range.upperBound) {
case (0, 0):
fallthrough
case (1, 1):
fallthrough
case (2, 2):
return .empty
case (0, 1):
return .single(first)
case (1, 2):
return .single(second)
case (0, 2):
return self
default:
fatalError("Range \(range) is out of bounds of count 2")
}
case .array(let indexes):
let slice = indexes[range]
switch slice.count {
case 0:
return .empty
case 1:
return .single(slice.first!)
case 2:
return .pair(slice.first!, slice.last!)
default:
return .array(Array<Int>(slice))
}
}
}
set {
switch self {
case .empty:
precondition(range.lowerBound == 0 && range.upperBound == 0, "Range \(range) is out of bounds of count 0")
self = newValue
break
case .single(let index):
switch (range.lowerBound, range.upperBound, newValue) {
case (0, 0, .empty):
fallthrough
case (1, 1, .empty):
break
case (0, 0, .single(let other)):
self = .pair(other, index)
break
case (0, 0, .pair(let first, let second)):
self = .array([first, second, index])
break
case (0, 0, .array(let other)):
self = .array(other + [index])
break
case (0, 1, .empty):
fallthrough
case (0, 1, .single):
fallthrough
case (0, 1, .pair):
fallthrough
case (0, 1, .array):
self = newValue
case (1, 1, .single(let other)):
self = .pair(index, other)
break
case (1, 1, .pair(let first, let second)):
self = .array([index, first, second])
break
case (1, 1, .array(let other)):
self = .array([index] + other)
break
default:
fatalError("Range \(range) is out of bounds of count 1")
}
case .pair(let first, let second):
switch (range.lowerBound, range.upperBound) {
case (0, 0):
switch newValue {
case .empty:
break
case .single(let other):
self = .array([other, first, second])
break
case .pair(let otherFirst, let otherSecond):
self = .array([otherFirst, otherSecond, first, second])
break
case .array(let other):
self = .array(other + [first, second])
break
}
break
case (0, 1):
switch newValue {
case .empty:
self = .single(second)
break
case .single(let other):
self = .pair(other, second)
break
case .pair(let otherFirst, let otherSecond):
self = .array([otherFirst, otherSecond, second])
break
case .array(let other):
self = .array(other + [second])
break
}
break
case (0, 2):
self = newValue
break
case (1, 2):
switch newValue {
case .empty:
self = .single(first)
break
case .single(let other):
self = .pair(first, other)
break
case .pair(let otherFirst, let otherSecond):
self = .array([first, otherFirst, otherSecond])
break
case .array(let other):
self = .array([first] + other)
}
break
case (2, 2):
switch newValue {
case .empty:
break
case .single(let other):
self = .array([first, second, other])
break
case .pair(let otherFirst, let otherSecond):
self = .array([first, second, otherFirst, otherSecond])
break
case .array(let other):
self = .array([first, second] + other)
}
break
default:
fatalError("Range \(range) is out of bounds of count 2")
}
case .array(let indexes):
var newIndexes = indexes
newIndexes.removeSubrange(range)
switch newValue {
case .empty:
break
case .single(let index):
newIndexes.insert(index, at: range.lowerBound)
break
case .pair(let first, let second):
newIndexes.insert(first, at: range.lowerBound)
newIndexes.insert(second, at: range.lowerBound + 1)
break
case .array(let other):
newIndexes.insert(contentsOf: other, at: range.lowerBound)
break
}
self = Storage(newIndexes)
break
}
}
}
var count: Int {
switch self {
case .empty:
return 0
case .single:
return 1
case .pair:
return 2
case .array(let indexes):
return indexes.count
}
}
var startIndex: Int {
return 0
}
var endIndex: Int {
return count
}
var allValues: [Int] {
switch self {
case .empty: return []
case .single(let index): return [index]
case .pair(let first, let second): return [first, second]
case .array(let indexes): return indexes
}
}
func index(before i: Int) -> Int {
return i - 1
}
func index(after i: Int) -> Int {
return i + 1
}
var description: String {
switch self {
case .empty:
return "[]"
case .single(let index):
return "[\(index)]"
case .pair(let first, let second):
return "[\(first), \(second)]"
case .array(let indexes):
return indexes.description
}
}
func withUnsafeBufferPointer<R>(_ body: (UnsafeBufferPointer<Int>) throws -> R) rethrows -> R {
switch self {
case .empty:
return try body(UnsafeBufferPointer<Int>(start: nil, count: 0))
case .single(let index_):
var index = index_
return try withUnsafePointer(to: &index) { (start) throws -> R in
return try body(UnsafeBufferPointer<Int>(start: start, count: 1))
}
case .pair(let first, let second):
var pair = (first, second)
return try withUnsafeBytes(of: &pair) { (rawBuffer: UnsafeRawBufferPointer) throws -> R in
return try body(UnsafeBufferPointer<Int>(start: rawBuffer.baseAddress?.assumingMemoryBound(to: Int.self), count: 2))
}
case .array(let indexes):
return try indexes.withUnsafeBufferPointer(body)
}
}
var debugDescription: String { return description }
static func +(_ lhs: Storage, _ rhs: Storage) -> Storage {
var res = lhs
res.append(contentsOf: rhs)
return res
}
static func +(_ lhs: Storage, _ rhs: [Int]) -> Storage {
var res = lhs
res.append(contentsOf: rhs)
return res
}
static func ==(_ lhs: Storage, _ rhs: Storage) -> Bool {
switch (lhs, rhs) {
case (.empty, .empty):
return true
case (.single(let lhsIndex), .single(let rhsIndex)):
return lhsIndex == rhsIndex
case (.pair(let lhsFirst, let lhsSecond), .pair(let rhsFirst, let rhsSecond)):
return lhsFirst == rhsFirst && lhsSecond == rhsSecond
case (.array(let lhsIndexes), .array(let rhsIndexes)):
return lhsIndexes == rhsIndexes
default:
return false
}
}
}
fileprivate var _indexes : Storage
/// Initialize an empty index path.
public init() {
_indexes = []
}
/// Initialize with a sequence of integers.
public init<ElementSequence : Sequence>(indexes: ElementSequence)
where ElementSequence.Iterator.Element == Element {
_indexes = Storage(indexes.map { $0 })
}
/// Initialize with an array literal.
public init(arrayLiteral indexes: Element...) {
_indexes = Storage(indexes)
}
/// Initialize with an array of elements.
public init(indexes: Array<Element>) {
_indexes = Storage(indexes)
}
fileprivate init(storage: Storage) {
_indexes = storage
}
/// Initialize with a single element.
public init(index: Element) {
_indexes = [index]
}
/// Return a new `IndexPath` containing all but the last element.
public func dropLast() -> IndexPath {
return IndexPath(storage: _indexes.dropLast())
}
/// Append an `IndexPath` to `self`.
public mutating func append(_ other: IndexPath) {
_indexes.append(contentsOf: other._indexes)
}
/// Append a single element to `self`.
public mutating func append(_ other: Element) {
_indexes.append(other)
}
/// Append an array of elements to `self`.
public mutating func append(_ other: Array<Element>) {
_indexes.append(contentsOf: other)
}
/// Return a new `IndexPath` containing the elements in self and the elements in `other`.
public func appending(_ other: Element) -> IndexPath {
var result = _indexes
result.append(other)
return IndexPath(storage: result)
}
/// Return a new `IndexPath` containing the elements in self and the elements in `other`.
public func appending(_ other: IndexPath) -> IndexPath {
return IndexPath(storage: _indexes + other._indexes)
}
/// Return a new `IndexPath` containing the elements in self and the elements in `other`.
public func appending(_ other: Array<Element>) -> IndexPath {
return IndexPath(storage: _indexes + other)
}
public subscript(index: Index) -> Element {
get {
return _indexes[index]
}
set {
_indexes[index] = newValue
}
}
public subscript(range: Range<Index>) -> IndexPath {
get {
return IndexPath(storage: _indexes[range])
}
set {
_indexes[range] = newValue._indexes
}
}
public func makeIterator() -> IndexingIterator<IndexPath> {
return IndexingIterator(_elements: self)
}
public var count: Int {
return _indexes.count
}
public var startIndex: Index {
return _indexes.startIndex
}
public var endIndex: Index {
return _indexes.endIndex
}
public func index(before i: Index) -> Index {
return _indexes.index(before: i)
}
public func index(after i: Index) -> Index {
return _indexes.index(after: i)
}
/// Sorting an array of `IndexPath` using this comparison results in an array representing nodes in depth-first traversal order.
public func compare(_ other: IndexPath) -> ComparisonResult {
let thisLength = count
let otherLength = other.count
let length = Swift.min(thisLength, otherLength)
for idx in 0..<length {
let otherValue = other[idx]
let value = self[idx]
if value < otherValue {
return .orderedAscending
} else if value > otherValue {
return .orderedDescending
}
}
if thisLength > otherLength {
return .orderedDescending
} else if thisLength < otherLength {
return .orderedAscending
}
return .orderedSame
}
public var hashValue: Int {
func hashIndexes(first: Int, last: Int, count: Int) -> Int {
let totalBits = MemoryLayout<Int>.size * 8
let lengthBits = 8
let firstIndexBits = (totalBits - lengthBits) / 2
return count &+ (first << lengthBits) &+ (last << (lengthBits + firstIndexBits))
}
switch _indexes {
case .empty: return 0
case .single(let index): return index.hashValue
case .pair(let first, let second):
return hashIndexes(first: first, last: second, count: 2)
default:
let cnt = _indexes.count
return hashIndexes(first: _indexes[0], last: _indexes[cnt - 1], count: cnt)
}
}
// MARK: - Bridging Helpers
fileprivate init(nsIndexPath: ReferenceType) {
let count = nsIndexPath.length
if count == 0 {
_indexes = []
} else if count == 1 {
_indexes = .single(nsIndexPath.index(atPosition: 0))
} else if count == 2 {
_indexes = .pair(nsIndexPath.index(atPosition: 0), nsIndexPath.index(atPosition: 1))
} else {
var indexes = Array<Int>(repeating: 0, count: count)
indexes.withUnsafeMutableBufferPointer { (buffer: inout UnsafeMutableBufferPointer<Int>) -> Void in
nsIndexPath.getIndexes(buffer.baseAddress!, range: NSRange(location: 0, length: count))
}
_indexes = .array(indexes)
}
}
fileprivate func makeReference() -> ReferenceType {
switch _indexes {
case .empty:
return ReferenceType()
case .single(let index):
return ReferenceType(index: index)
case .pair(let first, let second):
return _NSIndexPathCreateFromIndexes(first, second) as! ReferenceType
default:
return _indexes.withUnsafeBufferPointer {
return ReferenceType(indexes: $0.baseAddress, length: $0.count)
}
}
}
public static func ==(lhs: IndexPath, rhs: IndexPath) -> Bool {
return lhs._indexes == rhs._indexes
}
public static func +(lhs: IndexPath, rhs: IndexPath) -> IndexPath {
return lhs.appending(rhs)
}
public static func +=(lhs: inout IndexPath, rhs: IndexPath) {
lhs.append(rhs)
}
public static func <(lhs: IndexPath, rhs: IndexPath) -> Bool {
return lhs.compare(rhs) == ComparisonResult.orderedAscending
}
public static func <=(lhs: IndexPath, rhs: IndexPath) -> Bool {
let order = lhs.compare(rhs)
return order == ComparisonResult.orderedAscending || order == ComparisonResult.orderedSame
}
public static func >(lhs: IndexPath, rhs: IndexPath) -> Bool {
return lhs.compare(rhs) == ComparisonResult.orderedDescending
}
public static func >=(lhs: IndexPath, rhs: IndexPath) -> Bool {
let order = lhs.compare(rhs)
return order == ComparisonResult.orderedDescending || order == ComparisonResult.orderedSame
}
}
extension IndexPath : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
return _indexes.description
}
public var debugDescription: String {
return _indexes.debugDescription
}
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: self, displayStyle: .collection)
}
}
extension IndexPath : _ObjectiveCBridgeable {
public static func _getObjectiveCType() -> Any.Type {
return NSIndexPath.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSIndexPath {
return makeReference()
}
public static func _forceBridgeFromObjectiveC(_ x: NSIndexPath, result: inout IndexPath?) {
result = IndexPath(nsIndexPath: x)
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSIndexPath, result: inout IndexPath?) -> Bool {
result = IndexPath(nsIndexPath: x)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSIndexPath?) -> IndexPath {
guard let src = source else { return IndexPath() }
return IndexPath(nsIndexPath: src)
}
}
extension NSIndexPath : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as IndexPath)
}
}
extension IndexPath : Codable {
private enum CodingKeys : Int, CodingKey {
case indexes
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
var indexesContainer = try container.nestedUnkeyedContainer(forKey: .indexes)
var indexes = [Int]()
if let count = indexesContainer.count {
indexes.reserveCapacity(count)
}
while !indexesContainer.isAtEnd {
let index = try indexesContainer.decode(Int.self)
indexes.append(index)
}
self.init(indexes: indexes)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
var indexesContainer = container.nestedUnkeyedContainer(forKey: .indexes)
switch self._indexes {
case .empty:
break
case .single(let index):
try indexesContainer.encode(index)
case .pair(let first, let second):
try indexesContainer.encode(first)
try indexesContainer.encode(second)
case .array(let indexes):
try indexesContainer.encode(contentsOf: indexes)
}
}
}
| apache-2.0 | cb35afa61b38d78039883ace22c2b513 | 34.642686 | 151 | 0.463769 | 5.620344 | false | false | false | false |
PureSwift/SwiftFoundation | Sources/SwiftFoundation/UUID.swift | 1 | 5292 | //
// UUID.swift
// SwiftFoundation
//
// Created by Alsey Coleman Miller on 6/29/15.
// Copyright © 2015 PureSwift. All rights reserved.
//
/// A representation of a universally unique identifier (```UUID```).
public struct UUID {
// MARK: - Properties
public let uuid: uuid_t
// MARK: - Initialization
/// Create a new UUID with RFC 4122 version 4 random bytes
public init() {
let uuid = uuid_t(.random,.random,.random,.random,.random,.random,.random,.random,.random,.random,.random,.random,.random,.random,.random,.random)
self.init(uuid: uuid)
}
/// Create a UUID from a `uuid_t`.
public init(uuid: uuid_t) {
self.uuid = uuid
}
// MARK: - UUID String
/// Create a UUID from a string such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F".
///
/// Returns nil for invalid strings.
public init?(uuidString string: String) {
guard string.count == UUID.stringLength
else { return nil }
let components = string
.split(separator: "-")
guard components[0].count == 8,
components[1].count == 4,
components[2].count == 4,
components[3].count == 4,
components[4].count == 12
else { return nil }
let hexString = components
.reduce("") { $0 + $1 }
assert(hexString.count == UUID.length * 2)
guard let bytes = [UInt8](hexadecimal: hexString)
else { return nil }
assert(bytes.count == UUID.length)
self.init(uuid: uuid_t(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]))
}
/// Returns a string created from the UUID, such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
public var uuidString: String {
return uuid.0.toHexadecimal()
+ uuid.1.toHexadecimal()
+ uuid.2.toHexadecimal()
+ uuid.3.toHexadecimal()
+ "-"
+ uuid.4.toHexadecimal()
+ uuid.5.toHexadecimal()
+ "-"
+ uuid.6.toHexadecimal()
+ uuid.7.toHexadecimal()
+ "-"
+ uuid.8.toHexadecimal()
+ uuid.9.toHexadecimal()
+ "-"
+ uuid.10.toHexadecimal()
+ uuid.11.toHexadecimal()
+ uuid.12.toHexadecimal()
+ uuid.13.toHexadecimal()
+ uuid.14.toHexadecimal()
+ uuid.15.toHexadecimal()
}
}
internal extension SwiftFoundation.UUID {
static var length: Int { return 16 }
static var stringLength: Int { return 36 }
}
// MARK: - Equatable
extension SwiftFoundation.UUID: Equatable {
public static func == (lhs: SwiftFoundation.UUID, rhs: SwiftFoundation.UUID) -> Bool {
return lhs.uuid.0 == rhs.uuid.0 &&
lhs.uuid.1 == rhs.uuid.1 &&
lhs.uuid.2 == rhs.uuid.2 &&
lhs.uuid.3 == rhs.uuid.3 &&
lhs.uuid.4 == rhs.uuid.4 &&
lhs.uuid.5 == rhs.uuid.5 &&
lhs.uuid.6 == rhs.uuid.6 &&
lhs.uuid.7 == rhs.uuid.7 &&
lhs.uuid.8 == rhs.uuid.8 &&
lhs.uuid.9 == rhs.uuid.9 &&
lhs.uuid.10 == rhs.uuid.10 &&
lhs.uuid.11 == rhs.uuid.11 &&
lhs.uuid.12 == rhs.uuid.12 &&
lhs.uuid.13 == rhs.uuid.13 &&
lhs.uuid.14 == rhs.uuid.14 &&
lhs.uuid.15 == rhs.uuid.15
}
}
// MARK: - Hashable
extension UUID: Hashable {
public func hash(into hasher: inout Hasher) {
withUnsafeBytes(of: uuid) { hasher.combine(bytes: $0) }
}
}
// MARK: - CustomStringConvertible
extension UUID: CustomStringConvertible {
public var description: String {
return uuidString
}
}
// MARK: - CustomReflectable
extension UUID: CustomReflectable {
public var customMirror: Mirror {
let c : [(label: String?, value: Any)] = []
let m = Mirror(self, children:c, displayStyle: .struct)
return m
}
}
// MARK: - Codable
extension UUID: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let uuidString = try container.decode(String.self)
guard let uuid = UUID(uuidString: uuidString) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath,
debugDescription: "Attempted to decode UUID from invalid UUID string."))
}
self = uuid
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.uuidString)
}
}
// MARK: - Supporting Types
public typealias uuid_t = (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8)
public typealias uuid_string_t = (Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8)
| mit | c2edec06d575fd2c2f58c64ce55fb28a | 31.660494 | 255 | 0.564544 | 3.763158 | false | false | false | false |
svachmic/ios-url-remote | URLRemote/Classes/Helpers/EnumCollection.swift | 1 | 1356 | //
// EnumCollection.swift
// URLRemote
//
// Created by Michal Švácha on 16/01/17.
// Copyright © 2017 Svacha, Michal. All rights reserved.
//
import Foundation
/// Protocol enabling listing all enum values in an array.
///
/// Inspired by article by @tiborbodecs available at:
/// https://theswiftdev.com/2017/01/05/18-swift-gist-generic-allvalues-for-enums/
protocol EnumCollection: Hashable {
static var allValues: [Self] { get }
}
/// Extension implementing the allValues method.
extension EnumCollection {
/// Helper function listing all cases in a sequence.
///
/// - Returns: Sequence of all the cases as an object of the enum.
static func cases() -> AnySequence<Self> {
typealias Obj = Self
return AnySequence { () -> AnyIterator<Obj> in
var raw = 0
return AnyIterator {
let current: Self = withUnsafePointer(to: &raw) {
$0.withMemoryRebound(to: Obj.self, capacity: 1) {
$0.pointee
}
}
guard current.hashValue == raw else { return nil }
raw += 1
return current
}
}
}
/// Computed variable with all cases in an array.
static var allValues: [Self] {
return Array(self.cases())
}
}
| apache-2.0 | b2b07e7293baa32361ed6004dc1f87d4 | 28.413043 | 81 | 0.578714 | 4.407166 | false | false | false | false |
nielubowicz/Particle-SDK | ParticleSDK/ParticleSDK/Helpers/Event.swift | 1 | 1762 | //
// Event.swift
// ParticleSDK
//
// Created by Chris Nielubowicz on 12/17/15.
// Copyright © 2015 Mobiquity, Inc. All rights reserved.
//
import Foundation
enum EventState: Int {
case Connecting = 0,
Open,
Closed
}
public class Event: NSObject, NSCopying {
public static let MessageEvent = "message"
public static let ErrorEvent = "error"
public static let OpenEvent = "open"
var name: String?
var data: NSData?
var readyState: EventState = .Connecting
var error: NSError?
override init() {
}
override public var description: String {
let state: String
switch self.readyState {
case .Connecting:
state = "CONNECTING"
break
case .Open:
state = "OPEN"
break
case .Closed:
state = "CLOSED"
break
}
return "<Event: event: \(name), readyState: \(state), data: \(data)>"
}
public func copyWithZone(zone: NSZone) -> AnyObject {
let copy = Event()
copy.name = self.name
copy.data = self.data
copy.readyState = self.readyState
copy.error = self.error
return copy
}
}
typealias EventHandler = (event:Event) -> Void
public func ==(lhs: EventSourceEventHandler, rhs: EventSourceEventHandler) -> Bool {
return lhs.UUID == rhs.UUID
}
public func !=(lhs: EventSourceEventHandler, rhs: EventSourceEventHandler) -> Bool {
return lhs.UUID != rhs.UUID
}
public class EventSourceEventHandler: Equatable {
var eventHandler: EventHandler
var UUID: NSUUID = NSUUID()
init(eventHandler: EventHandler) {
self.eventHandler = eventHandler
}
} | mit | cfd4f2621116f84f5545f22858fff714 | 21.025 | 84 | 0.59682 | 4.44697 | false | false | false | false |
apple/swift | test/Sema/availability_versions.swift | 2 | 73406 | // RUN: %target-typecheck-verify-swift -target %target-cpu-apple-macosx10.50 -disable-objc-attr-requires-foundation-module
// RUN: not %target-swift-frontend -target %target-cpu-apple-macosx10.50 -disable-objc-attr-requires-foundation-module -typecheck %s 2>&1 | %FileCheck %s '--implicit-check-not=<unknown>:0'
// Make sure we do not emit availability errors or warnings when -disable-availability-checking is passed
// RUN: not %target-swift-frontend -target %target-cpu-apple-macosx10.50 -typecheck -disable-objc-attr-requires-foundation-module -disable-availability-checking %s 2>&1 | %FileCheck %s '--implicit-check-not=error:' '--implicit-check-not=warning:'
// REQUIRES: OS=macosx
func markUsed<T>(_ t: T) {}
@available(OSX, introduced: 10.9)
func globalFuncAvailableOn10_9() -> Int { return 9 }
@available(OSX, introduced: 10.51)
func globalFuncAvailableOn10_51() -> Int { return 10 }
@available(OSX, introduced: 10.52)
func globalFuncAvailableOn10_52() -> Int { return 11 }
// Top level should reflect the minimum deployment target.
let ignored1: Int = globalFuncAvailableOn10_9()
let ignored2: Int = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let ignored3: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
// Functions without annotations should reflect the minimum deployment target.
func functionWithoutAvailability() {
// expected-note@-1 2{{add @available attribute to enclosing global function}}
let _: Int = globalFuncAvailableOn10_9()
let _: Int = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
// Functions with annotations should refine their bodies.
@available(OSX, introduced: 10.51)
func functionAvailableOn10_51() {
let _: Int = globalFuncAvailableOn10_9()
let _: Int = globalFuncAvailableOn10_51()
// Nested functions should get their own refinement context.
@available(OSX, introduced: 10.52)
func innerFunctionAvailableOn10_52() {
let _: Int = globalFuncAvailableOn10_9()
let _: Int = globalFuncAvailableOn10_51()
let _: Int = globalFuncAvailableOn10_52()
}
let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
// Don't allow script-mode globals to marked potentially unavailable. Their
// initializers are eagerly executed.
@available(OSX, introduced: 10.51) // expected-error {{global variable cannot be marked potentially unavailable with '@available' in script mode}}
var potentiallyUnavailableGlobalInScriptMode: Int = globalFuncAvailableOn10_51()
// Still allow other availability annotations on script-mode globals
@available(OSX, deprecated: 10.51)
var deprecatedGlobalInScriptMode: Int = 5
if #available(OSX 10.51, *) {
let _: Int = globalFuncAvailableOn10_51()
let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
if #available(OSX 10.51, *) {
let _: Int = globalFuncAvailableOn10_51()
let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
} else {
let _: Int = globalFuncAvailableOn10_9()
let _: Int = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
@available(OSX, introduced: 10.51)
@available(iOS, introduced: 8.0)
func globalFuncAvailableOnOSX10_51AndiOS8_0() -> Int { return 10 }
if #available(OSX 10.51, iOS 8.0, *) {
let _: Int = globalFuncAvailableOnOSX10_51AndiOS8_0()
}
if #available(iOS 9.0, *) {
let _: Int = globalFuncAvailableOnOSX10_51AndiOS8_0() // expected-error {{'globalFuncAvailableOnOSX10_51AndiOS8_0()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
// Multiple potentially unavailable references in a single statement
let ignored4: (Int, Int) = (globalFuncAvailableOn10_51(), globalFuncAvailableOn10_52()) // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}} expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}}
// expected-note@-1 2{{add 'if #available' version check}}
_ = globalFuncAvailableOn10_9()
let ignored5 = globalFuncAvailableOn10_51 // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
_ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
// Overloaded global functions
@available(OSX, introduced: 10.9)
func overloadedFunction() {}
@available(OSX, introduced: 10.51)
func overloadedFunction(_ on1010: Int) {}
overloadedFunction()
overloadedFunction(0) // expected-error {{'overloadedFunction' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
// Potentially unavailable methods
class ClassWithPotentiallyUnavailableMethod {
// expected-note@-1 {{add @available attribute to enclosing class}}
@available(OSX, introduced: 10.9)
func methAvailableOn10_9() {}
@available(OSX, introduced: 10.51)
func methAvailableOn10_51() {}
@available(OSX, introduced: 10.51)
class func classMethAvailableOn10_51() {}
func someOtherMethod() {
// expected-note@-1 {{add @available attribute to enclosing instance method}}
methAvailableOn10_9()
methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
}
func callPotentiallyUnavailableMethods(_ o: ClassWithPotentiallyUnavailableMethod) {
// expected-note@-1 2{{add @available attribute to enclosing global function}}
let m10_9 = o.methAvailableOn10_9
m10_9()
let m10_51 = o.methAvailableOn10_51 // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
m10_51()
o.methAvailableOn10_9()
o.methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
func callPotentiallyUnavailableMethodsViaIUO(_ o: ClassWithPotentiallyUnavailableMethod!) {
// expected-note@-1 2{{add @available attribute to enclosing global function}}
let m10_9 = o.methAvailableOn10_9
m10_9()
let m10_51 = o.methAvailableOn10_51 // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}}
m10_51()
o.methAvailableOn10_9()
o.methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
func callPotentiallyUnavailableClassMethod() {
// expected-note@-1 2{{add @available attribute to enclosing global function}}
ClassWithPotentiallyUnavailableMethod.classMethAvailableOn10_51() // expected-error {{'classMethAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let m10_51 = ClassWithPotentiallyUnavailableMethod.classMethAvailableOn10_51 // expected-error {{'classMethAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
m10_51()
}
class SubClassWithPotentiallyUnavailableMethod : ClassWithPotentiallyUnavailableMethod {
// expected-note@-1 {{add @available attribute to enclosing class}}
func someMethod() {
// expected-note@-1 {{add @available attribute to enclosing instance method}}
methAvailableOn10_9()
methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
}
class SubClassOverridingPotentiallyUnavailableMethod : ClassWithPotentiallyUnavailableMethod {
// expected-note@-1 2{{add @available attribute to enclosing class}}
override func methAvailableOn10_51() {
// expected-note@-1 2{{add @available attribute to enclosing instance method}}
methAvailableOn10_9()
super.methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let m10_9 = super.methAvailableOn10_9
m10_9()
let m10_51 = super.methAvailableOn10_51 // expected-error {{'methAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
m10_51()
}
func someMethod() {
methAvailableOn10_9()
// Calling our override should be fine
methAvailableOn10_51()
}
}
class ClassWithPotentiallyUnavailableOverloadedMethod {
@available(OSX, introduced: 10.9)
func overloadedMethod() {}
@available(OSX, introduced: 10.51)
func overloadedMethod(_ on1010: Int) {}
}
func callPotentiallyUnavailableOverloadedMethod(_ o: ClassWithPotentiallyUnavailableOverloadedMethod) {
// expected-note@-1 {{add @available attribute to enclosing global function}}
o.overloadedMethod()
o.overloadedMethod(0) // expected-error {{'overloadedMethod' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
// Initializers
class ClassWithPotentiallyUnavailableInitializer {
// expected-note@-1 {{add @available attribute to enclosing class}}
@available(OSX, introduced: 10.9)
required init() { }
@available(OSX, introduced: 10.51)
required init(_ val: Int) { }
convenience init(s: String) {
// expected-note@-1 {{add @available attribute to enclosing initializer}}
self.init(5) // expected-error {{'init(_:)' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
@available(OSX, introduced: 10.51)
convenience init(onlyOn1010: String) {
self.init(5)
}
}
func callPotentiallyUnavailableInitializer() {
// expected-note@-1 2{{add @available attribute to enclosing global function}}
_ = ClassWithPotentiallyUnavailableInitializer()
_ = ClassWithPotentiallyUnavailableInitializer(5) // expected-error {{'init(_:)' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let i = ClassWithPotentiallyUnavailableInitializer.self
_ = i.init()
_ = i.init(5) // expected-error {{'init(_:)' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
class SuperWithWithPotentiallyUnavailableInitializer {
@available(OSX, introduced: 10.9)
init() { }
@available(OSX, introduced: 10.51)
init(_ val: Int) { }
}
class SubOfClassWithPotentiallyUnavailableInitializer : SuperWithWithPotentiallyUnavailableInitializer {
// expected-note@-1 {{add @available attribute to enclosing class}}
override init(_ val: Int) {
// expected-note@-1 {{add @available attribute to enclosing initializer}}
super.init(5) // expected-error {{'init(_:)' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
override init() {
super.init()
}
@available(OSX, introduced: 10.51)
init(on1010: Int) {
super.init(22)
}
}
// Properties
class ClassWithPotentiallyUnavailableProperties {
// expected-note@-1 4{{add @available attribute to enclosing class}}
var nonLazyAvailableOn10_9Stored: Int = 9
@available(OSX, introduced: 10.51) // expected-error {{stored properties cannot be marked potentially unavailable with '@available'}}
var nonLazyAvailableOn10_51Stored : Int = 10
@available(OSX, introduced: 10.51) // expected-error {{stored properties cannot be marked potentially unavailable with '@available'}}
let nonLazyLetAvailableOn10_51Stored : Int = 10
// Make sure that we don't emit a Fix-It to mark a stored property as potentially unavailable.
// We don't support potentially unavailable stored properties yet.
var storedPropertyOfPotentiallyUnavailableType: ClassAvailableOn10_51? = nil // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
@available(OSX, introduced: 10.9)
lazy var availableOn10_9Stored: Int = 9
@available(OSX, introduced: 10.51) // expected-error {{stored properties cannot be marked potentially unavailable with '@available'}}
lazy var availableOn10_51Stored : Int = 10
@available(OSX, introduced: 10.9)
var availableOn10_9Computed: Int {
get {
let _: Int = availableOn10_51Stored // expected-error {{'availableOn10_51Stored' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
if #available(OSX 10.51, *) {
let _: Int = availableOn10_51Stored
}
return availableOn10_9Stored
}
set(newVal) {
availableOn10_9Stored = newVal
}
}
@available(OSX, introduced: 10.51)
var availableOn10_51Computed: Int {
get {
return availableOn10_51Stored
}
set(newVal) {
availableOn10_51Stored = newVal
}
}
var propWithSetterOnlyAvailableOn10_51 : Int {
// expected-note@-1 {{add @available attribute to enclosing property}}
get {
_ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
return 0
}
@available(OSX, introduced: 10.51)
set(newVal) {
_ = globalFuncAvailableOn10_51()
}
}
var propWithGetterOnlyAvailableOn10_51 : Int {
// expected-note@-1 {{add @available attribute to enclosing property}}
@available(OSX, introduced: 10.51)
get {
_ = globalFuncAvailableOn10_51()
return 0
}
set(newVal) {
_ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
}
var propWithGetterAndSetterOnlyAvailableOn10_51 : Int {
@available(OSX, introduced: 10.51)
get {
return 0
}
@available(OSX, introduced: 10.51)
set(newVal) {
}
}
var propWithSetterOnlyAvailableOn10_51ForNestedMemberRef : ClassWithPotentiallyUnavailableProperties {
get {
return ClassWithPotentiallyUnavailableProperties()
}
@available(OSX, introduced: 10.51)
set(newVal) {
}
}
var propWithGetterOnlyAvailableOn10_51ForNestedMemberRef : ClassWithPotentiallyUnavailableProperties {
@available(OSX, introduced: 10.51)
get {
return ClassWithPotentiallyUnavailableProperties()
}
set(newVal) {
}
}
}
@available(OSX, introduced: 10.51)
class ClassWithReferencesInInitializers {
var propWithInitializer10_51: Int = globalFuncAvailableOn10_51()
var propWithInitializer10_52: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}}
lazy var lazyPropWithInitializer10_51: Int = globalFuncAvailableOn10_51()
lazy var lazyPropWithInitializer10_52: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}}
}
func accessPotentiallyUnavailableProperties(_ o: ClassWithPotentiallyUnavailableProperties) {
// expected-note@-1 17{{add @available attribute to enclosing global function}}
// Stored properties
let _: Int = o.availableOn10_9Stored
let _: Int = o.availableOn10_51Stored // expected-error {{'availableOn10_51Stored' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
o.availableOn10_9Stored = 9
o.availableOn10_51Stored = 10 // expected-error {{'availableOn10_51Stored' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
// Computed Properties
let _: Int = o.availableOn10_9Computed
let _: Int = o.availableOn10_51Computed // expected-error {{'availableOn10_51Computed' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
o.availableOn10_9Computed = 9
o.availableOn10_51Computed = 10 // expected-error {{'availableOn10_51Computed' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
// Getter allowed on 10.9 but setter is not
let _: Int = o.propWithSetterOnlyAvailableOn10_51
o.propWithSetterOnlyAvailableOn10_51 = 5 // expected-error {{setter for 'propWithSetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
if #available(OSX 10.51, *) {
// Setter is allowed on 10.51 and greater
o.propWithSetterOnlyAvailableOn10_51 = 5
}
// Setter allowed on 10.9 but getter is not
o.propWithGetterOnlyAvailableOn10_51 = 5
let _: Int = o.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
if #available(OSX 10.51, *) {
// Getter is allowed on 10.51 and greater
let _: Int = o.propWithGetterOnlyAvailableOn10_51
}
// Tests for nested member refs
// Both getters are potentially unavailable.
let _: Int = o.propWithGetterOnlyAvailableOn10_51ForNestedMemberRef.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51ForNestedMemberRef' is only available in macOS 10.51 or newer}} expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 2{{add 'if #available' version check}}
// Nested getter is potentially unavailable, outer getter is available
let _: Int = o.propWithGetterOnlyAvailableOn10_51ForNestedMemberRef.propWithSetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51ForNestedMemberRef' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
// Nested getter is available, outer getter is potentially unavailable
let _:Int = o.propWithSetterOnlyAvailableOn10_51ForNestedMemberRef.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
// Both getters are always available.
let _: Int = o.propWithSetterOnlyAvailableOn10_51ForNestedMemberRef.propWithSetterOnlyAvailableOn10_51
// Nesting in source of assignment
var v: Int
v = o.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
v = (o.propWithGetterOnlyAvailableOn10_51) // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
_ = v // muffle warning
// Inout requires access to both getter and setter
func takesInout(_ i : inout Int) { }
takesInout(&o.propWithGetterOnlyAvailableOn10_51) // expected-error {{cannot pass as inout because getter for 'propWithGetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
takesInout(&o.propWithSetterOnlyAvailableOn10_51) // expected-error {{cannot pass as inout because setter for 'propWithSetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
takesInout(&o.propWithGetterAndSetterOnlyAvailableOn10_51) // expected-error {{cannot pass as inout because getter for 'propWithGetterAndSetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}} expected-error {{cannot pass as inout because setter for 'propWithGetterAndSetterOnlyAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 2{{add 'if #available' version check}}
takesInout(&o.availableOn10_9Computed)
takesInout(&o.propWithGetterOnlyAvailableOn10_51ForNestedMemberRef.availableOn10_9Computed) // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51ForNestedMemberRef' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
// _silgen_name
@_silgen_name("SomeName")
@available(OSX, introduced: 10.51)
func funcWith_silgen_nameAvailableOn10_51(_ p: ClassAvailableOn10_51?) -> ClassAvailableOn10_51
// Enums
@available(OSX, introduced: 10.51)
enum EnumIntroducedOn10_51 {
case Element
}
@available(OSX, introduced: 10.52)
enum EnumIntroducedOn10_52 {
case Element
}
@available(OSX, introduced: 10.51)
enum CompassPoint {
case North
case South
case East
@available(OSX, introduced: 10.52)
case West
case WithAvailableByEnumPayload(p : EnumIntroducedOn10_51)
// expected-error@+1 {{enum cases with associated values cannot be marked potentially unavailable with '@available'}}
@available(OSX, introduced: 10.52)
case WithAvailableByEnumElementPayload(p : EnumIntroducedOn10_52)
// expected-error@+1 2{{enum cases with associated values cannot be marked potentially unavailable with '@available'}}
@available(OSX, introduced: 10.52)
case WithAvailableByEnumElementPayload1(p : EnumIntroducedOn10_52), WithAvailableByEnumElementPayload2(p : EnumIntroducedOn10_52)
case WithPotentiallyUnavailablePayload(p : EnumIntroducedOn10_52) // expected-error {{'EnumIntroducedOn10_52' is only available in macOS 10.52 or newer}}
case WithPotentiallyUnavailablePayload1(p : EnumIntroducedOn10_52), WithPotentiallyUnavailablePayload2(p : EnumIntroducedOn10_52) // expected-error 2{{'EnumIntroducedOn10_52' is only available in macOS 10.52 or newer}}
@available(OSX, unavailable)
case WithPotentiallyUnavailablePayload3(p : EnumIntroducedOn10_52)
}
@available(OSX, introduced: 10.52)
func functionTakingEnumIntroducedOn10_52(_ e: EnumIntroducedOn10_52) { }
func useEnums() {
// expected-note@-1 3{{add @available attribute to enclosing global function}}
let _: CompassPoint = .North // expected-error {{'CompassPoint' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
if #available(OSX 10.51, *) {
let _: CompassPoint = .North
let _: CompassPoint = .West // expected-error {{'West' is only available in macOS 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
if #available(OSX 10.52, *) {
let _: CompassPoint = .West
}
// Pattern matching on an enum element does not require it to be definitely available
if #available(OSX 10.51, *) {
let point: CompassPoint = .North
switch (point) {
case .North, .South, .East:
markUsed("NSE")
case .West: // We do not expect an error here
markUsed("W")
case .WithPotentiallyUnavailablePayload(_):
markUsed("WithPotentiallyUnavailablePayload")
case .WithPotentiallyUnavailablePayload1(_):
markUsed("WithPotentiallyUnavailablePayload1")
case .WithPotentiallyUnavailablePayload2(_):
markUsed("WithPotentiallyUnavailablePayload2")
case .WithAvailableByEnumPayload(_):
markUsed("WithAvailableByEnumPayload")
case .WithAvailableByEnumElementPayload1(_):
markUsed("WithAvailableByEnumElementPayload1")
case .WithAvailableByEnumElementPayload2(_):
markUsed("WithAvailableByEnumElementPayload2")
case .WithAvailableByEnumElementPayload(let p):
markUsed("WithAvailableByEnumElementPayload")
// For the moment, we do not incorporate enum element availability into
// TRC construction. Perhaps we should?
functionTakingEnumIntroducedOn10_52(p) // expected-error {{'functionTakingEnumIntroducedOn10_52' is only available in macOS 10.52 or newer}}
// expected-note@-2 {{add 'if #available' version check}}
}
}
}
// Classes
@available(OSX, introduced: 10.9)
class ClassAvailableOn10_9 {
func someMethod() {}
class func someClassMethod() {}
var someProp : Int = 22
}
@available(OSX, introduced: 10.51)
class ClassAvailableOn10_51 { // expected-note {{enclosing scope requires availability of macOS 10.51 or newer}}
func someMethod() {}
class func someClassMethod() {
let _ = ClassAvailableOn10_51()
}
var someProp : Int = 22
@available(OSX, introduced: 10.9) // expected-error {{instance method cannot be more available than enclosing scope}}
func someMethodAvailableOn10_9() { }
@available(OSX, introduced: 10.52)
var propWithGetter: Int { // expected-note{{enclosing scope requires availability of macOS 10.52 or newer}}
@available(OSX, introduced: 10.51) // expected-error {{getter cannot be more available than enclosing scope}}
get { return 0 }
}
}
func classAvailability() {
// expected-note@-1 3{{add @available attribute to enclosing global function}}
ClassAvailableOn10_9.someClassMethod()
ClassAvailableOn10_51.someClassMethod() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
_ = ClassAvailableOn10_9.self
_ = ClassAvailableOn10_51.self // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let o10_9 = ClassAvailableOn10_9()
let o10_51 = ClassAvailableOn10_51() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
o10_9.someMethod()
o10_51.someMethod()
let _ = o10_9.someProp
let _ = o10_51.someProp
}
func castingPotentiallyUnavailableClass(_ o : AnyObject) {
// expected-note@-1 3{{add @available attribute to enclosing global function}}
let _ = o as! ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let _ = o as? ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let _ = o is ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
protocol Creatable {
init()
}
@available(OSX, introduced: 10.51)
class ClassAvailableOn10_51_Creatable : Creatable {
required init() {}
}
func create<T : Creatable>() -> T {
return T()
}
class ClassWithGenericTypeParameter<T> { }
class ClassWithTwoGenericTypeParameter<T, S> { }
func classViaTypeParameter() {
// expected-note@-1 9{{add @available attribute to enclosing global function}}
let _ : ClassAvailableOn10_51_Creatable = // expected-error {{'ClassAvailableOn10_51_Creatable' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
create()
let _ = create() as
ClassAvailableOn10_51_Creatable // expected-error {{'ClassAvailableOn10_51_Creatable' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let _ = [ClassAvailableOn10_51]() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let _: ClassWithGenericTypeParameter<ClassAvailableOn10_51> = ClassWithGenericTypeParameter() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let _: ClassWithTwoGenericTypeParameter<ClassAvailableOn10_51, String> = ClassWithTwoGenericTypeParameter() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let _: ClassWithTwoGenericTypeParameter<String, ClassAvailableOn10_51> = ClassWithTwoGenericTypeParameter() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let _: ClassWithTwoGenericTypeParameter<ClassAvailableOn10_51, ClassAvailableOn10_51> = ClassWithTwoGenericTypeParameter() // expected-error 2{{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 2{{add 'if #available' version check}}
let _: ClassAvailableOn10_51? = nil // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
// Potentially unavailable class used in declarations
class ClassWithDeclarationsOfPotentiallyUnavailableClasses {
// expected-note@-1 6{{add @available attribute to enclosing class}}
@available(OSX, introduced: 10.51)
init() {}
var propertyOfPotentiallyUnavailableType: ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
@available(OSX, introduced: 10.51)
static var potentiallyUnavailableStaticPropertyOfPotentiallyUnavailableType: ClassAvailableOn10_51 = ClassAvailableOn10_51()
@available(OSX, introduced: 10.51)
static var potentiallyUnavailableStaticPropertyOfOptionalPotentiallyUnavailableType: ClassAvailableOn10_51?
func methodWithPotentiallyUnavailableParameterType(_ o : ClassAvailableOn10_51) { // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing instance method}}
}
@available(OSX, introduced: 10.51)
func potentiallyUnavailableMethodWithPotentiallyUnavailableParameterType(_ o : ClassAvailableOn10_51) {}
func methodWithPotentiallyUnavailableReturnType() -> ClassAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 2{{add @available attribute to enclosing instance method}}
return ClassAvailableOn10_51() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
@available(OSX, unavailable)
func unavailableMethodWithPotentiallyUnavailableParameterType(_ o : ClassAvailableOn10_51) {}
@available(OSX, introduced: 10.51)
func potentiallyUnavailableMethodWithPotentiallyUnavailableReturnType() -> ClassAvailableOn10_51 {
return ClassAvailableOn10_51()
}
@available(OSX, unavailable)
func unavailableMethodWithPotentiallyUnavailableReturnType() -> ClassAvailableOn10_51 {
guard #available(OSX 10.51, *) else { fatalError() }
return ClassAvailableOn10_51()
}
func methodWithPotentiallyUnavailableLocalDeclaration() {
// expected-note@-1 {{add @available attribute to enclosing instance method}}
let _ : ClassAvailableOn10_51 = methodWithPotentiallyUnavailableReturnType() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
@available(OSX, introduced: 10.51)
func potentiallyUnavailableMethodWithPotentiallyUnavailableLocalDeclaration() {
let _ : ClassAvailableOn10_51 = methodWithPotentiallyUnavailableReturnType()
}
@available(OSX, unavailable)
func unavailableMethodWithPotentiallyUnavailableLocalDeclaration() {
let _ : ClassAvailableOn10_51 = methodWithPotentiallyUnavailableReturnType() // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
}
func referToPotentiallyUnavailableStaticProperty() {
// expected-note@-1 {{add @available attribute to enclosing global function}}
let _ = ClassWithDeclarationsOfPotentiallyUnavailableClasses.potentiallyUnavailableStaticPropertyOfPotentiallyUnavailableType // expected-error {{'potentiallyUnavailableStaticPropertyOfPotentiallyUnavailableType' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
class ClassExtendingPotentiallyUnavailableClass : ClassAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
}
@available(OSX, introduced: 10.51)
class PotentiallyUnavailableClassExtendingPotentiallyUnavailableClass : ClassAvailableOn10_51 {
}
@available(OSX, unavailable)
class UnavailableClassExtendingPotentiallyUnavailableClass : ClassAvailableOn10_51 {
}
// Method availability is contravariant
class SuperWithAlwaysAvailableMembers {
func shouldAlwaysBeAvailableMethod() { // expected-note {{overridden declaration is here}}
}
var shouldAlwaysBeAvailableProperty: Int { // expected-note {{overridden declaration is here}}
get { return 9 }
set(newVal) {}
}
var setterShouldAlwaysBeAvailableProperty: Int {
get { return 9 }
set(newVal) {} // expected-note {{overridden declaration is here}}
}
var getterShouldAlwaysBeAvailableProperty: Int {
get { return 9 } // expected-note {{overridden declaration is here}}
set(newVal) {}
}
}
class SubWithLimitedMemberAvailability : SuperWithAlwaysAvailableMembers {
@available(OSX, introduced: 10.51)
override func shouldAlwaysBeAvailableMethod() { // expected-error {{overriding 'shouldAlwaysBeAvailableMethod' must be as available as declaration it overrides}}
}
@available(OSX, introduced: 10.51)
override var shouldAlwaysBeAvailableProperty: Int { // expected-error {{overriding 'shouldAlwaysBeAvailableProperty' must be as available as declaration it overrides}}
get { return 10 }
set(newVal) {}
}
override var setterShouldAlwaysBeAvailableProperty: Int {
get { return 9 }
@available(OSX, introduced: 10.51)
set(newVal) {} // expected-error {{overriding setter for 'setterShouldAlwaysBeAvailableProperty' must be as available as declaration it overrides}}
// This is a terrible diagnostic. rdar://problem/20427938
}
override var getterShouldAlwaysBeAvailableProperty: Int {
@available(OSX, introduced: 10.51)
get { return 9 } // expected-error {{overriding getter for 'getterShouldAlwaysBeAvailableProperty' must be as available as declaration it overrides}}
set(newVal) {}
}
}
@available(OSX, introduced: 10.51)
class SubWithLimitedAvailablility : SuperWithAlwaysAvailableMembers {
override func shouldAlwaysBeAvailableMethod() {}
override var shouldAlwaysBeAvailableProperty: Int {
get { return 10 }
set(newVal) {}
}
override var setterShouldAlwaysBeAvailableProperty: Int {
get { return 9 }
set(newVal) {}
}
override var getterShouldAlwaysBeAvailableProperty: Int {
get { return 9 }
set(newVal) {}
}
}
class SuperWithLimitedMemberAvailability {
@available(OSX, introduced: 10.51)
func someMethod() {
}
@available(OSX, introduced: 10.51)
var someProperty: Int {
get { return 10 }
set(newVal) {}
}
}
class SubWithLargerMemberAvailability : SuperWithLimitedMemberAvailability {
// expected-note@-1 2{{add @available attribute to enclosing class}}
@available(OSX, introduced: 10.9)
override func someMethod() {
super.someMethod() // expected-error {{'someMethod()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
if #available(OSX 10.51, *) {
super.someMethod()
}
}
@available(OSX, introduced: 10.9)
override var someProperty: Int {
get {
let _ = super.someProperty // expected-error {{'someProperty' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
if #available(OSX 10.51, *) {
let _ = super.someProperty
}
return 9
}
set(newVal) {}
}
}
@available(OSX, introduced: 10.51)
class SubWithLimitedAvailability : SuperWithLimitedMemberAvailability {
override func someMethod() {
super.someMethod()
}
override var someProperty: Int {
get { super.someProperty }
set(newVal) { super.someProperty = newVal }
}
}
@available(OSX, introduced: 10.52)
class SubWithMoreLimitedAvailability : SuperWithLimitedMemberAvailability {
override func someMethod() {
super.someMethod()
}
override var someProperty: Int {
get { super.someProperty }
set(newVal) { super.someProperty = newVal }
}
}
@available(OSX, introduced: 10.52)
class SubWithMoreLimitedAvailabilityAndRedundantMemberAvailability : SuperWithLimitedMemberAvailability {
@available(OSX, introduced: 10.52)
override func someMethod() {
super.someMethod()
}
@available(OSX, introduced: 10.52)
override var someProperty: Int {
get { super.someProperty }
set(newVal) { super.someProperty = newVal }
}
}
@available(OSX, unavailable)
class UnavailableSubWithLargerMemberAvailability : SuperWithLimitedMemberAvailability {
override func someMethod() {
}
override var someProperty: Int {
get { return 5 }
set(newVal) {}
}
}
// Inheritance and availability
@available(OSX, introduced: 10.51)
protocol ProtocolAvailableOn10_9 {
}
@available(OSX, introduced: 10.51)
protocol ProtocolAvailableOn10_51 {
}
@available(OSX, introduced: 10.9)
protocol ProtocolAvailableOn10_9InheritingFromProtocolAvailableOn10_51 : ProtocolAvailableOn10_51 { // expected-error {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}}
}
@available(OSX, introduced: 10.51)
protocol ProtocolAvailableOn10_51InheritingFromProtocolAvailableOn10_9 : ProtocolAvailableOn10_9 {
}
@available(OSX, unavailable)
protocol UnavailableProtocolInheritingFromProtocolAvailableOn10_51 : ProtocolAvailableOn10_51 {
}
@available(OSX, introduced: 10.9)
class SubclassAvailableOn10_9OfClassAvailableOn10_51 : ClassAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
}
@available(OSX, unavailable)
class UnavailableSubclassOfClassAvailableOn10_51 : ClassAvailableOn10_51 {
}
// We allow nominal types to conform to protocols that are less available than the types themselves.
@available(OSX, introduced: 10.9)
class ClassAvailableOn10_9AdoptingProtocolAvailableOn10_51 : ProtocolAvailableOn10_51 {
}
func castToPotentiallyUnavailableProtocol() {
// expected-note@-1 2{{add @available attribute to enclosing global function}}
let o: ClassAvailableOn10_9AdoptingProtocolAvailableOn10_51 = ClassAvailableOn10_9AdoptingProtocolAvailableOn10_51()
let _: ProtocolAvailableOn10_51 = o // expected-error {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let _ = o as ProtocolAvailableOn10_51 // expected-error {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
@available(OSX, introduced: 10.9)
class SubclassAvailableOn10_9OfClassAvailableOn10_51AlsoAdoptingProtocolAvailableOn10_51 : ClassAvailableOn10_51, ProtocolAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
}
class SomeGenericClass<T> { }
@available(OSX, introduced: 10.9)
class SubclassAvailableOn10_9OfSomeGenericClassOfProtocolAvailableOn10_51 : SomeGenericClass<ProtocolAvailableOn10_51> { // expected-error {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}}
}
@available(OSX, unavailable)
class UnavailableSubclassOfSomeGenericClassOfProtocolAvailableOn10_51 : SomeGenericClass<ProtocolAvailableOn10_51> {
}
func GenericWhereClause<T>(_ t: T) where T: ProtocolAvailableOn10_51 { // expected-error * {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 * {{add @available attribute to enclosing global function}}
}
@available(OSX, unavailable)
func UnavailableGenericWhereClause<T>(_ t: T) where T: ProtocolAvailableOn10_51 {
}
func GenericSignature<T : ProtocolAvailableOn10_51>(_ t: T) { // expected-error * {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 * {{add @available attribute to enclosing global function}}
}
@available(OSX, unavailable)
func UnavailableGenericSignature<T : ProtocolAvailableOn10_51>(_ t: T) {
}
struct GenericType<T> { // expected-note {{add @available attribute to enclosing generic struct}}
func nonGenericWhereClause() where T : ProtocolAvailableOn10_51 {} // expected-error {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing instance method}}
@available(OSX, unavailable)
func unavailableNonGenericWhereClause() where T : ProtocolAvailableOn10_51 {}
struct NestedType where T : ProtocolAvailableOn10_51 {} // expected-error {{'ProtocolAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 2{{add @available attribute to enclosing struct}}
@available(OSX, unavailable)
struct UnavailableNestedType where T : ProtocolAvailableOn10_51 {}
}
// Extensions
extension ClassAvailableOn10_51 { } // expected-error {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing extension}}
@available(OSX, unavailable)
extension ClassAvailableOn10_51 { }
@available(OSX, introduced: 10.51)
extension ClassAvailableOn10_51 {
func m() {
// expected-note@-1 {{add @available attribute to enclosing instance method}}
let _ = globalFuncAvailableOn10_51()
let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
}
class ClassToExtend { }
@available(OSX, introduced: 10.51)
extension ClassToExtend {
func extensionMethod() { }
@available(OSX, introduced: 10.52)
func extensionMethod10_52() { }
class ExtensionClass { }
// We rely on not allowing nesting of extensions, so test to make sure
// this emits an error.
// CHECK:error: declaration is only valid at file scope
extension ClassToExtend { } // expected-error {{declaration is only valid at file scope}}
}
// We allow protocol extensions for protocols that are less available than the
// conforming class.
extension ClassToExtend : ProtocolAvailableOn10_51 {
}
@available(OSX, introduced: 10.51)
extension ClassToExtend { // expected-note {{enclosing scope requires availability of macOS 10.51 or newer}}
@available(OSX, introduced: 10.9) // expected-error {{instance method cannot be more available than enclosing scope}}
func extensionMethod10_9() { }
}
func usePotentiallyUnavailableExtension() {
// expected-note@-1 3{{add @available attribute to enclosing global function}}
let o = ClassToExtend()
o.extensionMethod() // expected-error {{'extensionMethod()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let _ = ClassToExtend.ExtensionClass() // expected-error {{'ExtensionClass' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
o.extensionMethod10_52() // expected-error {{'extensionMethod10_52()' is only available in macOS 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
// Availability of synthesized designated initializers.
@available(OSX, introduced: 10.51)
class WidelyAvailableBase {
init() {}
@available(OSX, introduced: 10.52)
init(thing: ()) {}
}
@available(OSX, introduced: 10.53)
class EsotericSmallBatchHipsterThing : WidelyAvailableBase {}
@available(OSX, introduced: 10.53)
class NestedClassTest {
class InnerClass : WidelyAvailableBase {}
}
// Useless #available(...) checks
func functionWithDefaultAvailabilityAndUselessCheck(_ p: Bool) {
// Default availability reflects minimum deployment: 10.9 and up
if #available(OSX 10.9, *) { // no-warning
let _ = globalFuncAvailableOn10_9()
}
if #available(OSX 10.51, *) { // expected-note {{enclosing scope here}}
let _ = globalFuncAvailableOn10_51()
if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}}
let _ = globalFuncAvailableOn10_51()
}
}
if #available(OSX 10.9, *) { // expected-note {{enclosing scope here}}
} else {
// Make sure we generate a warning about an unnecessary check even if the else branch of if is dead.
if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}}
}
}
// This 'if' is strictly to limit the scope of the guard fallthrough
if p {
guard #available(OSX 10.9, *) else { // expected-note {{enclosing scope here}}
// Make sure we generate a warning about an unnecessary check even if the else branch of guard is dead.
if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}}
}
}
}
// We don't want * generate a warn about useless checks; the check may be required on
// another platform
if #available(iOS 8.0, *) {
}
if #available(OSX 10.51, *) {
// Similarly do not want '*' to generate a warning in a refined TRC.
if #available(iOS 8.0, *) {
}
}
}
@available(OSX, unavailable)
func explicitlyUnavailable() { } // expected-note 2{{'explicitlyUnavailable()' has been explicitly marked unavailable here}}
func functionWithUnavailableInDeadBranch() {
if #available(iOS 8.0, *) {
} else {
// This branch is dead on OSX, so we shouldn't a warning about use of potentially unavailable APIs in it.
_ = globalFuncAvailableOn10_51() // no-warning
@available(OSX 10.51, *)
func localFuncAvailableOn10_51() {
_ = globalFuncAvailableOn10_52() // no-warning
}
localFuncAvailableOn10_51() // no-warning
explicitlyUnavailable() // expected-error {{'explicitlyUnavailable()' is unavailable}}
}
guard #available(iOS 8.0, *) else {
_ = globalFuncAvailableOn10_51() // no-warning
explicitlyUnavailable() // expected-error {{'explicitlyUnavailable()' is unavailable}}
}
}
@available(OSX, introduced: 10.51)
func functionWithSpecifiedAvailabilityAndUselessCheck() { // expected-note 2{{enclosing scope here}}
if #available(OSX 10.9, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}}
let _ = globalFuncAvailableOn10_9()
}
if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}}
let _ = globalFuncAvailableOn10_51()
}
}
// #available(...) outside if statement guards
func injectToOptional<T>(_ v: T) -> T? {
return v
}
if let _ = injectToOptional(5), #available(OSX 10.52, *) {} // ok
// Refining context inside guard
if #available(OSX 10.51, *),
let _ = injectToOptional(globalFuncAvailableOn10_51()),
let _ = injectToOptional(globalFuncAvailableOn10_52()) { // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let _ = globalFuncAvailableOn10_51()
let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
if let _ = injectToOptional(5), #available(OSX 10.51, *),
let _ = injectToOptional(globalFuncAvailableOn10_51()),
let _ = injectToOptional(globalFuncAvailableOn10_52()) { // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let _ = globalFuncAvailableOn10_51()
let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
if let _ = injectToOptional(globalFuncAvailableOn10_51()), #available(OSX 10.51, *), // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let _ = injectToOptional(globalFuncAvailableOn10_52()) { // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
if let _ = injectToOptional(5), #available(OSX 10.51, *), // expected-note {{enclosing scope here}}
let _ = injectToOptional(6), #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}}
}
// Tests for the guard control construct.
func useGuardAvailable() {
// expected-note@-1 3{{add @available attribute to enclosing global function}}
// Guard fallthrough should refine context
guard #available(OSX 10.51, *) else { // expected-note {{enclosing scope here}}
let _ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
return
}
let _ = globalFuncAvailableOn10_51()
let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}}
}
if globalFuncAvailableOn10_51() > 0 {
guard #available(OSX 10.52, *),
let x = injectToOptional(globalFuncAvailableOn10_52()) else { return }
_ = x
}
let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
func twoGuardsInSameBlock(_ p: Int) {
// expected-note@-1 {{add @available attribute to enclosing global function}}
if (p > 0) {
guard #available(OSX 10.51, *) else { return }
let _ = globalFuncAvailableOn10_51()
guard #available(OSX 10.52, *) else { return }
let _ = globalFuncAvailableOn10_52()
}
let _ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
// Refining while loops
while globalFuncAvailableOn10_51() > 10 { } // expected-error {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
while #available(OSX 10.51, *), // expected-note {{enclosing scope here}}
globalFuncAvailableOn10_51() > 10 {
let _ = globalFuncAvailableOn10_51()
let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
while globalFuncAvailableOn10_51() > 11,
let _ = injectToOptional(5),
#available(OSX 10.52, *) {
let _ = globalFuncAvailableOn10_52();
}
while #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'macOS'; enclosing scope ensures guard will always be true}}
}
}
// Tests for Fix-It replacement text
// The whitespace in the replacement text is particularly important here -- it reflects the level
// of indentation for the added if #available() or @available attribute. Note that, for the moment, we hard
// code *added* indentation in Fix-Its as 4 spaces (that is, when indenting in a Fix-It, we
// take whatever indentation was there before and add 4 spaces to it).
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{1-27=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n} else {\n // Fallback on earlier versions\n}}}
let declForFixitAtTopLevel: ClassAvailableOn10_51? = nil
// expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{1-57=if #available(macOS 10.51, *) {\n let declForFixitAtTopLevel: ClassAvailableOn10_51? = nil\n} else {\n // Fallback on earlier versions\n}}}
func fixitForReferenceInGlobalFunction() {
// expected-note@-1 {{add @available attribute to enclosing global function}} {{1-1=@available(macOS 10.51, *)\n}}
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{3-29=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
}
public func fixitForReferenceInGlobalFunctionWithDeclModifier() {
// expected-note@-1 {{add @available attribute to enclosing global function}} {{1-1=@available(macOS 10.51, *)\n}}
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{3-29=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
}
func fixitForReferenceInGlobalFunctionWithAttribute() -> Never {
// expected-note@-1 {{add @available attribute to enclosing global function}} {{1-1=@available(macOS 10.51, *)\n}}
_ = 0 // Avoid treating the call to functionAvailableOn10_51 as an implicit return
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{3-29=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
}
func takesAutoclosure(_ c : @autoclosure () -> ()) {
}
class ClassForFixit {
// expected-note@-1 12{{add @available attribute to enclosing class}} {{1-1=@available(macOS 10.51, *)\n}}
func fixitForReferenceInMethod() {
// expected-note@-1 {{add @available attribute to enclosing instance method}} {{3-3=@available(macOS 10.51, *)\n }}
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{5-31=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
}
func fixitForReferenceNestedInMethod() {
// expected-note@-1 3{{add @available attribute to enclosing instance method}} {{3-3=@available(macOS 10.51, *)\n }}
func inner() {
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{7-33=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
}
let _: () -> () = { () in
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{7-33=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
}
takesAutoclosure(functionAvailableOn10_51())
// expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{5-49=if #available(macOS 10.51, *) {\n takesAutoclosure(functionAvailableOn10_51())\n } else {\n // Fallback on earlier versions\n }}}
}
var fixitForReferenceInPropertyAccessor: Int {
// expected-note@-1 {{add @available attribute to enclosing property}} {{3-3=@available(macOS 10.51, *)\n }}
get {
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{7-33=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
return 5
}
}
var fixitForReferenceInPropertyType: ClassAvailableOn10_51? = nil
// expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
lazy var fixitForReferenceInLazyPropertyType: ClassAvailableOn10_51? = nil
// expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
private lazy var fixitForReferenceInPrivateLazyPropertyType: ClassAvailableOn10_51? = nil
// expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
lazy private var fixitForReferenceInLazyPrivatePropertyType: ClassAvailableOn10_51? = nil
// expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
static var fixitForReferenceInStaticPropertyType: ClassAvailableOn10_51? = nil
// expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-2 {{add @available attribute to enclosing static property}} {{3-3=@available(macOS 10.51, *)\n }}
var fixitForReferenceInPropertyTypeMultiple: ClassAvailableOn10_51? = nil, other: Int = 7
// expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
func fixitForRefInGuardOfIf() {
// expected-note@-1 {{add @available attribute to enclosing instance method}} {{3-3=@available(macOS 10.51, *)\n }}
if (globalFuncAvailableOn10_51() > 1066) {
let _ = 5
let _ = 6
}
// expected-error@-4 {{'globalFuncAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-5 {{add 'if #available' version check}} {{5-6=if #available(macOS 10.51, *) {\n if (globalFuncAvailableOn10_51() > 1066) {\n let _ = 5\n let _ = 6\n }\n } else {\n // Fallback on earlier versions\n }}}
}
}
extension ClassToExtend {
// expected-note@-1 {{add @available attribute to enclosing extension}}
func fixitForReferenceInExtensionMethod() {
// expected-note@-1 {{add @available attribute to enclosing instance method}} {{3-3=@available(macOS 10.51, *)\n }}
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{5-31=if #available(macOS 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
}
}
enum EnumForFixit {
// expected-note@-1 2{{add @available attribute to enclosing enum}} {{1-1=@available(macOS 10.51, *)\n}}
case CaseWithPotentiallyUnavailablePayload(p: ClassAvailableOn10_51)
// expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
case CaseWithPotentiallyUnavailablePayload2(p: ClassAvailableOn10_51), WithoutPayload
// expected-error@-1 {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
}
@objc
class Y {
var z = 0
}
@objc
class X {
@objc var y = Y()
}
func testForFixitWithNestedMemberRefExpr() {
// expected-note@-1 2{{add @available attribute to enclosing global function}} {{1-1=@available(macOS 10.52, *)\n}}
let x = X()
x.y.z = globalFuncAvailableOn10_52()
// expected-error@-1 {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{3-39=if #available(macOS 10.52, *) {\n x.y.z = globalFuncAvailableOn10_52()\n } else {\n // Fallback on earlier versions\n }}}
// Access via dynamic member reference
let anyX: AnyObject = x
anyX.y?.z = globalFuncAvailableOn10_52()
// expected-error@-1 {{'globalFuncAvailableOn10_52()' is only available in macOS 10.52 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{3-43=if #available(macOS 10.52, *) {\n anyX.y?.z = globalFuncAvailableOn10_52()\n } else {\n // Fallback on earlier versions\n }}}
}
// Protocol Conformances
protocol ProtocolWithRequirementMentioningPotentiallyUnavailable {
// expected-note@-1 2{{add @available attribute to enclosing protocol}}
func hasPotentiallyUnavailableParameter(_ p: ClassAvailableOn10_51) // expected-error * {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 * {{add @available attribute to enclosing instance method}}
func hasPotentiallyUnavailableReturn() -> ClassAvailableOn10_51 // expected-error * {{'ClassAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 * {{add @available attribute to enclosing instance method}}
@available(OSX 10.51, *)
func hasPotentiallyUnavailableWithAnnotation(_ p: ClassAvailableOn10_51) -> ClassAvailableOn10_51
}
protocol HasMethodF {
associatedtype T
func f(_ p: T) // expected-note 3{{protocol requirement here}}
}
class TriesToConformWithFunctionIntroducedOn10_51 : HasMethodF {
@available(OSX, introduced: 10.51)
func f(_ p: Int) { } // expected-error {{protocol 'HasMethodF' requires 'f' to be available in macOS 10.50 and newer}}
}
class ConformsWithFunctionIntroducedOnMinimumDeploymentTarget : HasMethodF {
// Even though this function is less available than its requirement,
// it is available on a deployment targets, so the conformance is safe.
@available(OSX, introduced: 10.9)
func f(_ p: Int) { }
}
class SuperHasMethodF {
@available(OSX, introduced: 10.51)
func f(_ p: Int) { } // expected-note {{'f' declared here}}
}
class TriesToConformWithPotentiallyUnavailableFunctionInSuperClass : SuperHasMethodF, HasMethodF { // expected-error {{protocol 'HasMethodF' requires 'f' to be available in macOS 10.50 and newer}}
// The conformance here is generating an error on f in the super class.
}
@available(OSX, introduced: 10.51)
class ConformsWithPotentiallyUnavailableFunctionInSuperClass : SuperHasMethodF, HasMethodF {
// Limiting this class to only be available on 10.51 and newer means that
// the witness in SuperHasMethodF is safe for the requirement on HasMethodF.
// in order for this class to be referenced we must be running on 10.51 or
// greater.
}
class ConformsByOverridingFunctionInSuperClass : SuperHasMethodF, HasMethodF {
// Now the witness is this f() (which is always available) and not the f()
// from the super class, so conformance is safe.
override func f(_ p: Int) { }
}
// Attempt to conform in protocol extension with unavailable witness
// in extension
class HasNoMethodF1 { }
extension HasNoMethodF1 : HasMethodF {
@available(OSX, introduced: 10.51)
func f(_ p: Int) { } // expected-error {{protocol 'HasMethodF' requires 'f' to be available in macOS 10.50 and newer}}
}
class HasNoMethodF2 { }
@available(OSX, introduced: 10.51)
extension HasNoMethodF2 : HasMethodF {
// This is OK, because the conformance was introduced by an extension.
func f(_ p: Int) { }
}
@available(OSX, introduced: 10.51)
class HasNoMethodF3 { }
@available(OSX, introduced: 10.51)
extension HasNoMethodF3 : HasMethodF {
// We expect this conformance to succeed because on every version where HasNoMethodF3
// is available, HasNoMethodF3's f() is as available as the protocol requirement
func f(_ p: Int) { }
}
@available(OSX, introduced: 10.51)
protocol HasMethodFOn10_51 {
func f(_ p: Int)
}
class ConformsToPotentiallyUnavailableProtocolWithPotentiallyUnavailableWitness : HasMethodFOn10_51 {
@available(OSX, introduced: 10.51)
func f(_ p: Int) { }
}
@available(OSX, introduced: 10.51)
class HasNoMethodF4 { }
@available(OSX, introduced: 10.52)
extension HasNoMethodF4 : HasMethodFOn10_51 {
// This is OK, because the conformance was introduced by an extension.
func f(_ p: Int) { }
}
@available(OSX, introduced: 10.51)
protocol HasTakesClassAvailableOn10_51 {
func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) // expected-note 2{{protocol requirement here}}
}
class AttemptsToConformToHasTakesClassAvailableOn10_51 : HasTakesClassAvailableOn10_51 {
@available(OSX, introduced: 10.52)
func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) { // expected-error {{protocol 'HasTakesClassAvailableOn10_51' requires 'takesClassAvailableOn10_51' to be available in macOS 10.51 and newer}}
}
}
class ConformsToHasTakesClassAvailableOn10_51 : HasTakesClassAvailableOn10_51 {
@available(OSX, introduced: 10.51)
func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) {
}
}
class TakesClassAvailableOn10_51_A { }
extension TakesClassAvailableOn10_51_A : HasTakesClassAvailableOn10_51 {
@available(OSX, introduced: 10.52)
func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) { // expected-error {{protocol 'HasTakesClassAvailableOn10_51' requires 'takesClassAvailableOn10_51' to be available in macOS 10.51 and newer}}
}
}
class TakesClassAvailableOn10_51_B { }
extension TakesClassAvailableOn10_51_B : HasTakesClassAvailableOn10_51 {
@available(OSX, introduced: 10.51)
func takesClassAvailableOn10_51(_ o: ClassAvailableOn10_51) {
}
}
// We want conditional availability to play a role in picking a witness for a
// protocol requirement.
class TestAvailabilityAffectsWitnessCandidacy : HasMethodF {
// Test that we choose the less specialized witness, because the more specialized
// witness is conditionally unavailable.
@available(OSX, introduced: 10.51)
func f(_ p: Int) { }
func f<T>(_ p: T) { }
}
protocol HasPotentiallyUnavailableMethodF {
@available(OSX, introduced: 10.51)
func f(_ p: String)
}
class ConformsWithPotentiallyUnavailableFunction : HasPotentiallyUnavailableMethodF {
@available(OSX, introduced: 10.9)
func f(_ p: String) { }
}
func usePotentiallyUnavailableProtocolMethod(_ h: HasPotentiallyUnavailableMethodF) {
// expected-note@-1 {{add @available attribute to enclosing global function}}
h.f("Foo") // expected-error {{'f' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
func usePotentiallyUnavailableProtocolMethod<H : HasPotentiallyUnavailableMethodF> (_ h: H) {
// expected-note@-1 {{add @available attribute to enclosing global function}}
h.f("Foo") // expected-error {{'f' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
// Short-form @available() annotations
@available(OSX 10.51, *)
class ClassWithShortFormAvailableOn10_51 {
}
@available(OSX 10.53, *)
class ClassWithShortFormAvailableOn10_53 {
}
@available(OSX 10.54, *)
class ClassWithShortFormAvailableOn10_54 {
}
@available(OSX 10.9, *)
func funcWithShortFormAvailableOn10_9() {
let _ = ClassWithShortFormAvailableOn10_51() // expected-error {{'ClassWithShortFormAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
@available(OSX 10.51, *)
func funcWithShortFormAvailableOn10_51() {
let _ = ClassWithShortFormAvailableOn10_51()
}
@available(iOS 14.0, *)
func funcWithShortFormAvailableOniOS14() {
// expected-note@-1 {{add @available attribute to enclosing global function}}
let _ = ClassWithShortFormAvailableOn10_51() // expected-error {{'ClassWithShortFormAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
@available(iOS 14.0, OSX 10.53, *)
func funcWithShortFormAvailableOniOS14AndOSX10_53() {
let _ = ClassWithShortFormAvailableOn10_51()
}
// Not idiomatic but we need to be able to handle it.
@available(iOS 8.0, *)
@available(OSX 10.51, *)
func funcWithMultipleShortFormAnnotationsForDifferentPlatforms() {
let _ = ClassWithShortFormAvailableOn10_51()
}
@available(OSX 10.51, *)
@available(OSX 10.53, *)
@available(OSX 10.52, *)
func funcWithMultipleShortFormAnnotationsForTheSamePlatform() {
let _ = ClassWithShortFormAvailableOn10_53()
let _ = ClassWithShortFormAvailableOn10_54() // expected-error {{'ClassWithShortFormAvailableOn10_54' is only available in macOS 10.54 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
func useShortFormAvailable() {
// expected-note@-1 4{{add @available attribute to enclosing global function}}
funcWithShortFormAvailableOn10_9()
funcWithShortFormAvailableOn10_51() // expected-error {{'funcWithShortFormAvailableOn10_51()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
funcWithShortFormAvailableOniOS14()
funcWithShortFormAvailableOniOS14AndOSX10_53() // expected-error {{'funcWithShortFormAvailableOniOS14AndOSX10_53()' is only available in macOS 10.53 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
funcWithMultipleShortFormAnnotationsForDifferentPlatforms() // expected-error {{'funcWithMultipleShortFormAnnotationsForDifferentPlatforms()' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
funcWithMultipleShortFormAnnotationsForTheSamePlatform() // expected-error {{'funcWithMultipleShortFormAnnotationsForTheSamePlatform()' is only available in macOS 10.53 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
// Unavailability takes precedence over availability and is inherited
@available(OSX 10.9, *)
@available(OSX, unavailable)
func unavailableWins() { }
// expected-note@-1 {{'unavailableWins()' has been explicitly marked unavailable here}}
struct HasUnavailableExtension {
@available(OSX, unavailable)
public func directlyUnavailable() { }
// expected-note@-1 {{'directlyUnavailable()' has been explicitly marked unavailable here}}
}
@available(OSX, unavailable)
extension HasUnavailableExtension {
// expected-note@-1 {{enclosing scope has been explicitly marked unavailable here}}
public func inheritsUnavailable() { }
// expected-note@-1 {{'inheritsUnavailable()' has been explicitly marked unavailable here}}
@available(OSX 10.9, *) // expected-warning {{instance method cannot be more available than unavailable enclosing scope}}
public func moreAvailableButStillUnavailable() { }
// expected-note@-1 {{'moreAvailableButStillUnavailable()' has been explicitly marked unavailable here}}
}
func useHasUnavailableExtension(_ s: HasUnavailableExtension) {
unavailableWins() // expected-error {{'unavailableWins()' is unavailable}}
s.directlyUnavailable() // expected-error {{'directlyUnavailable()' is unavailable}}
s.inheritsUnavailable() // expected-error {{'inheritsUnavailable()' is unavailable in macOS}}
s.moreAvailableButStillUnavailable() // expected-error {{'moreAvailableButStillUnavailable()' is unavailable in macOS}}
}
| apache-2.0 | 3cb1a133a9286ee60926b3864474961f | 41.114745 | 357 | 0.715214 | 3.85475 | false | false | false | false |
tiagobsbraga/TBPagarME | Example/Pods/SwiftLuhn/Pod/Classes/SwiftLuhn.swift | 1 | 3721 | //
// ObjectiveLuhn.swift
// Example Project
//
// Created by Max Kramer on 29/03/2016.
// Copyright © 2016 Max Kramer. All rights reserved.
//
import Foundation
public class SwiftLuhn {
public enum CardType: Int {
case Amex = 0
case Visa
case Mastercard
case Discover
case DinersClub
case JCB
}
public enum CardError: ErrorType {
case Unsupported
case Invalid
}
private class func regularExpression(cardType: CardType) -> String {
switch cardType {
case .Amex:
return "^3[47][0-9]{5,}$";
case .DinersClub:
return "^3(?:0[0-5]|[68][0-9])[0-9]{4,}$";
case .Discover:
return "^6(?:011|5[0-9]{2})[0-9]{3,}$";
case .JCB:
return "^(?:2131|1800|35[0-9]{3})[0-9]{3,}$";
case .Mastercard:
return "^5[1-5][0-9]{5,}$";
case .Visa:
return "^4[0-9]{6,}$";
}
}
class func performLuhnAlgorithm(cardNumber: String) throws {
guard cardNumber.characters.count >= 9 else {
throw CardError.Invalid
}
let originalCheckDigit = cardNumber.characters.last!
let characters = cardNumber.characters.dropLast().reverse()
var digitSum = 0
for (idx, character) in characters.enumerate() {
let value = Int(String(character)) ?? 0
if idx % 2 == 0 {
var product = value * 2
if product > 9 {
product = product - 9
}
digitSum = digitSum + product
}
else {
digitSum = digitSum + value
}
}
digitSum = digitSum * 9
let computedCheckDigit = digitSum % 10
let originalCheckDigitInt = Int(String(originalCheckDigit))
let valid = originalCheckDigitInt == computedCheckDigit
if valid == false {
throw CardError.Invalid
}
}
class func cardType(cardNumber: String) throws -> CardType {
var foundCardType: CardType?
for i in CardType.Amex.rawValue...CardType.JCB.rawValue {
let cardType = CardType(rawValue: i)!
let regex = regularExpression(cardType)
let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
if predicate.evaluateWithObject(cardNumber) == true {
foundCardType = cardType
break
}
}
if foundCardType == nil {
throw CardError.Invalid
}
return foundCardType!
}
}
public extension SwiftLuhn.CardType {
func stringValue() -> String {
switch self {
case .Amex:
return "American Express"
case .Visa:
return "Visa"
case .Mastercard:
return "Mastercard"
case .Discover:
return "Discover"
case .DinersClub:
return "Diner's Club"
case .JCB:
return "JCB"
}
}
init?(string: String) {
switch string.lowercaseString {
case "american express":
self.init(rawValue: 0)
case "visa":
self.init(rawValue: 1)
case "mastercard":
self.init(rawValue: 2)
case "discover":
self.init(rawValue: 3)
case "diner's club":
self.init(rawValue: 4)
case "jcb":
self.init(rawValue: 5)
default:
return nil
}
}
}
| mit | a635a01f27c54c3b6e0066b63d5986c4 | 25.571429 | 73 | 0.495161 | 4.661654 | false | false | false | false |
noprom/swiftmi-app | swiftmi/swiftmi/RefreshFooterView.swift | 2 | 6734 |
//
// File.swift
// RefreshExample
//
// Created by SunSet on 14-6-23.
// Copyright (c) 2014 zhaokaiyuan. All rights reserved.
//
import UIKit
class RefreshFooterView: RefreshBaseView {
class func footer()->RefreshFooterView{
let footer:RefreshFooterView = RefreshFooterView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width,
CGFloat(RefreshViewHeight)))
return footer
}
var lastRefreshCount:Int = 0
override func layoutSubviews() {
super.layoutSubviews()
self.statusLabel.frame = self.bounds;
}
override func willMoveToSuperview(newSuperview: UIView!) {
super.willMoveToSuperview(newSuperview)
if (self.superview != nil){
self.superview!.removeObserver(self, forKeyPath: RefreshContentSize,context:nil)
}
if (newSuperview != nil) {
newSuperview.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.New, context: nil)
// 重新调整frame
adjustFrameWithContentSize()
}
}
//重写调整frame
func adjustFrameWithContentSize(){
let contentHeight:CGFloat = self.scrollView.contentSize.height//
let scrollHeight:CGFloat = self.scrollView.frame.size.height - self.scrollViewOriginalInset.top - self.scrollViewOriginalInset.bottom
var rect:CGRect = self.frame;
rect.origin.y = contentHeight > scrollHeight ? contentHeight : scrollHeight
self.frame = rect;
}
//监听UIScrollView的属性
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<()>) {
if (!self.userInteractionEnabled || self.hidden){
return
}
if RefreshContentSize == keyPath {
adjustFrameWithContentSize()
}else if RefreshContentOffset == keyPath {
if self.State == RefreshState.Refreshing{
return
}
adjustStateWithContentOffset()
}
}
func adjustStateWithContentOffset()
{
let currentOffsetY:CGFloat = self.scrollView.contentOffset.y
let happenOffsetY:CGFloat = self.happenOffsetY()
if currentOffsetY <= happenOffsetY {
return
}
if self.scrollView.dragging {
let normal2pullingOffsetY = happenOffsetY + self.frame.size.height
if self.State == RefreshState.Normal && currentOffsetY > normal2pullingOffsetY {
self.State = RefreshState.Pulling;
} else if (self.State == RefreshState.Pulling && currentOffsetY <= normal2pullingOffsetY) {
self.State = RefreshState.Normal;
}
} else if (self.State == RefreshState.Pulling) {
self.State = RefreshState.Refreshing
}
}
override var State:RefreshState {
willSet {
if State == newValue{
return;
}
oldState = State
setState(newValue)
}
didSet{
switch State{
case .Normal:
self.statusLabel.text = RefreshFooterPullToRefresh;
if (RefreshState.Refreshing == oldState) {
self.arrowImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
UIView.animateWithDuration(RefreshSlowAnimationDuration, animations: {
self.scrollView.contentInset.bottom = self.scrollViewOriginalInset.bottom
})
} else {
UIView.animateWithDuration(RefreshSlowAnimationDuration, animations: {
self.arrowImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI));
})
}
let deltaH:CGFloat = self.heightForContentBreakView()
let currentCount:Int = self.totalDataCountInScrollView()
if (RefreshState.Refreshing == oldState && deltaH > 0 && currentCount != self.lastRefreshCount) {
var offset:CGPoint = self.scrollView.contentOffset;
offset.y = self.scrollView.contentOffset.y
self.scrollView.contentOffset = offset;
}
break
case .Pulling:
self.statusLabel.text = RefreshFooterReleaseToRefresh
UIView.animateWithDuration(RefreshSlowAnimationDuration, animations: {
self.arrowImage.transform = CGAffineTransformIdentity
})
break
case .Refreshing:
self.statusLabel.text = RefreshFooterRefreshing;
self.lastRefreshCount = self.totalDataCountInScrollView();
UIView.animateWithDuration(RefreshSlowAnimationDuration, animations: {
var bottom:CGFloat = self.frame.size.height + self.scrollViewOriginalInset.bottom
let deltaH:CGFloat = self.heightForContentBreakView()
if deltaH < 0 {
bottom = bottom - deltaH
}
var inset:UIEdgeInsets = self.scrollView.contentInset;
inset.bottom = bottom;
self.scrollView.contentInset = inset;
})
break
default:
break
}
}
}
func totalDataCountInScrollView()->Int
{
var totalCount:Int = 0
if self.scrollView is UITableView {
let tableView:UITableView = self.scrollView as! UITableView
for (var i:Int = 0 ; i < tableView.numberOfSections ; i++){
totalCount = totalCount + tableView.numberOfRowsInSection(i)
}
} else if self.scrollView is UICollectionView{
let collectionView:UICollectionView = self.scrollView as! UICollectionView
for (var i:Int = 0 ; i < collectionView.numberOfSections() ; i++){
totalCount = totalCount + collectionView.numberOfItemsInSection(i)
}
}
return totalCount
}
func heightForContentBreakView()->CGFloat
{
let h:CGFloat = self.scrollView.frame.size.height - self.scrollViewOriginalInset.bottom - self.scrollViewOriginalInset.top;
return self.scrollView.contentSize.height - h;
}
func happenOffsetY()->CGFloat
{
let deltaH:CGFloat = self.heightForContentBreakView()
if deltaH > 0 {
return deltaH - self.scrollViewOriginalInset.top;
} else {
return -self.scrollViewOriginalInset.top;
}
}
func addState(state:RefreshState){
self.State = state
}
} | mit | a2a7d2551e0b897e02d766ded4bd41d8 | 35.264865 | 155 | 0.601521 | 5.375 | false | false | false | false |
cwwise/CWWeChat | CWWeChat/MainClass/Contacts/ContactsController/Tool/CWContactHelper.swift | 2 | 4814 | //
// CWContactHelper.swift
// CWWeChat
//
// Created by wei chen on 2017/4/3.
// Copyright © 2017年 cwcoder. All rights reserved.
//
import UIKit
import SwiftyJSON
typealias CWContactListChanged = ([[CWUserModel]], [String], Int) -> Void
typealias CWFetchContactComplete = (CWUserModel,CWChatError?) -> Void
public class CWContactHelper: NSObject {
static let share = CWContactHelper()
///默认的分组
fileprivate var defaultGroup = [CWUserModel]()
var contactsData = [CWUserModel]()
var contactsDict = [String: CWUserModel]()
var sectionHeaders = [String]()
var sortedContactArray = [[CWUserModel]]()
var dataChange: CWContactListChanged?
private override init() {
super.init()
setupDefaultGroup()
initTestData()
}
func fetchContactById(_ userId: String, complete: CWFetchContactComplete) {
if let contact = contactsDict[userId] {
complete(contact, nil)
}
// 如果没有找到,进行网络查询
}
func initTestData() {
///读取数据
let path = Bundle.main.path(forResource: "ContactList", ofType: "json")
guard let filepath = path else {
log.error("不存在 ContactList.json 文件。")
return
}
let contantData = try? Data(contentsOf: URL(fileURLWithPath: filepath))
let contactList = JSON(data: contantData!)
for (_,subJson):(String, JSON) in contactList {
let userId = subJson["userID"].stringValue
let username = subJson["username"].stringValue
let user = CWUserModel(userId: userId, username: username)
user.remarkName = subJson["remarkName"].string
user.nickname = subJson["nikeName"].string
user.avatarURL = subJson["avatarURL"].url
contactsData.append(user)
contactsDict[userId] = user
}
DispatchQueue.global().async {
self.sortContactData()
}
}
///对数据进行排序分组
func sortContactData() {
//先根据拼音的首字母排序
contactsData.sort { (leftUser, rightUser) -> Bool in
let pingYingA = leftUser.pinying
let pingYingB = rightUser.pinying
return pingYingA < pingYingB
}
sectionHeaders = [String]()
let indexCollation = UILocalizedIndexedCollation.current()
sectionHeaders.append(contentsOf: indexCollation.sectionTitles)
// 设置数组
var sortedArray = [[CWUserModel]]()
for _ in 0..<sectionHeaders.count {
sortedArray.append([CWUserModel]())
}
for contact in contactsData {
let initial = contact.pinyingInitial.fistLetter
// 如果不是字母
let section: Int
if matchLetter(string: initial) == false {
section = sectionHeaders.count - 1
} else {
section = sectionHeaders.index(of: initial)!
}
sortedArray[section].append(contact)
}
// 去除空的section
for i in (0..<sortedArray.count).reversed() {
let sectionArray = sortedArray[i]
if sectionArray.count == 0 {
sortedArray.remove(at: i)
sectionHeaders.remove(at: i)
}
}
sortedArray.insert(defaultGroup, at: 0)
self.sortedContactArray = sortedArray
// 头部分
DispatchQueue.main.async(execute: {
self.dataChange?(self.sortedContactArray,
self.sectionHeaders,
self.contactsData.count)
})
}
// 判断是否为字母
func matchLetter(string: String) -> Bool {
if string.characters.count == 0 {return false}
let index = string.index(string.startIndex, offsetBy: 1)
let regextest = NSPredicate(format: "SELF MATCHES %@", "^[A-Za-z]+$")
return regextest.evaluate(with: string[..<index])
}
//初始化默认的组
func setupDefaultGroup() {
let titleArray = ["新的朋友","群聊", "标签", "公众号"]
let iconArray = ["contact_new_friend","contact_group_chat",
"contact_signature","contact_official_account"]
let idArray = ["-1","-2", "-3", "-4"]
for index in 0..<titleArray.count {
let item = CWUserModel(userId: idArray[index], username: "")
item.nickname = titleArray[index]
item.avatarImage = UIImage(named: iconArray[index])
defaultGroup.append(item)
}
}
}
| mit | 4126fbb387911ec532703e3eee638155 | 30.080537 | 79 | 0.562729 | 4.663646 | false | false | false | false |
danielpi/Swift-Playgrounds | Swift-Playgrounds/Using Swift With Cocoa And Objective-C/AdoptingCocoaDesignPatterns.playground/section-1.swift | 1 | 2572 | // Adopting Cocoa Design Patterns
import Cocoa
// Delegation
/*
if let fullScreenSize = myDelegate?.window?(myWindow, willUseFullScreenContentSize: mySize) {
println(NSStringFromSize(fullScreenSize))
}
*/
// 1. Check that myDelegate is not nil.
// 2. Check that myDelegate implements the method window:willUseFullScreenContentSize:.
// 3. If 1 and 2 hold true, invoke the method and assign the result of the method to the value named fullScreenSize.
// 4. Print the return value of the method.
// In a pure Swift app, type the delegate property as an optional NSWindowDelegate object and assign it an initial value of nil.
class MyDelegate: NSObject, NSWindowDelegate {
func window(_ window: NSWindow, willUseFullScreenContentSize proposedSize: NSSize) -> NSSize {
return proposedSize
}
}
let myWindow = NSWindow()
myWindow.delegate = MyDelegate()
//if let fullScreenSize = myWindow.delegate?.window(myWindow, willUseFullScreenContentSize: NSSize()) {
// print(NSStringFromSize(fullScreenSize))
//}
// Lazy Initialization
// Error Reporting
// Error reporting in Swift follows the same pattern it does in Objective-C.
// In the simplest case, you return a Bool value from the function to indicate whether or not it succeeded.
// When you need to report the reason for the error, you can add to the function an NSError out parameter of type NSErrorPointer. This type is roughly equivalent to Objective-C’s NSError **. You can use the prefix & operator to pass in a reference to an optional NSError type as an NSErrorPointer object, as shown in the code listing below.
/*
var writeError: NSError?
let written = myString.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: &writeError)
if !written {
if let error = writeError {
println("write failure: \(error.localizedDescription)")
}
}
*/
// Target-Action
// Basically the same as in Objective-C
// Introspection
// In ObjC you use isKindOfClass: and conformsToProtocol:
// In Swift you use the is operator and the as? operator to downcast
/*if errorPointer is NSButton {
println("\(typeName) is a string")
} else {
println("typeName is not a string")
}
if let button = errorPointer as? NSErrorPointer {
}
*/
// Checking for and casting to a protocol follows exactly the same syntax as checking for and casting to a class.
/*
if let dataSource = object as? UITableViewDataSource {
// object conforms to UITableViewDataSource and is bound to dataSource
} else {
// object not conform to UITableViewDataSource
}
*/
| mit | 1c4b0639acaf8a53e413f2362e0e5a84 | 32.376623 | 341 | 0.745525 | 4.393162 | false | false | false | false |
dokun1/Lumina | Sources/Lumina/Camera/Extensions/CameraUtilExtension.swift | 1 | 612 | //
// CameraUtilExtension.swift
// Lumina
//
// Created by David Okun on 11/20/17.
// Copyright © 2017 David Okun. All rights reserved.
//
import Foundation
extension Formatter {
static let iso8601: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
return formatter
}()
}
extension Date {
var iso8601: String {
return Formatter.iso8601.string(from: self)
}
}
| mit | 23310667831b187f566d9c5d87e017f0 | 23.44 | 59 | 0.698854 | 3.658683 | false | false | false | false |
emilletfr/domo-server-vapor | Sources/App/ViewModel/RollerShuttersViewModel.swift | 2 | 5576 | //
// RollerShuttersViewModel.swift
// VaporApp
//
// Created by Eric on 20/12/2016.
//
//
import Foundation
import RxSwift
import Dispatch
final class RollerShuttersViewModel : RollerShuttersViewModelable
{
//MARK: Subscriptions
let currentPositionObserver = [PublishSubject<Int>(), PublishSubject<Int>(), PublishSubject<Int>(), PublishSubject<Int>(), PublishSubject<Int>()]
let targetPositionObserver = [PublishSubject<Int>(), PublishSubject<Int>(), PublishSubject<Int>(), PublishSubject<Int>(), PublishSubject<Int>()]
let manualAutomaticModeObserver = PublishSubject<Int>()
//MARK: Actions
let targetPositionPublisher = [PublishSubject<Int>(), PublishSubject<Int>(), PublishSubject<Int>(), PublishSubject<Int>(), PublishSubject<Int>()]
let manualAutomaticModePublisher = PublishSubject<Int>()
//MARK: Services
let rollerShuttersService : RollerShutterServicable
let inBedService: InBedServicable
let sunriseSunsetService : SunriseSunsetServicable
let hourMinutePublisher = PublishSubject<String>()
let secondPublisher: PublishSubject<Int>
//MARK: Dispatcher
required init(rollerShuttersService: RollerShutterServicable = RollerShutterService(), inBedService: InBedServicable = InBedService(), sunriseSunsetService: SunriseSunsetServicable = SunriseSunsetService(), secondEmitter: PublishSubject<Int> = secondEmitter)
{
self.rollerShuttersService = rollerShuttersService
self.inBedService = inBedService
self.sunriseSunsetService = sunriseSunsetService
self.secondPublisher = secondEmitter
self.reduce()
}
//MARK: Reducer
func reduce()
{
_ = secondPublisher.map({ _ -> String in
let date = Date(timeIntervalSinceNow: 0)
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "CEST")
dateFormatter.locale = Locale(identifier: "fr_FR")
dateFormatter.dateFormat = "HH:mm"
return dateFormatter.string(from: date)
})
.distinctUntilChanged()
.subscribe(hourMinutePublisher)
//MARK: Wrap Manual/Automatic Mode
_ = self.manualAutomaticModePublisher.subscribe(manualAutomaticModeObserver)
//MARK: Wrap observers and targetAllPublisher
for placeIndex in 0..<RollerShutter.count.rawValue {
_ = self.rollerShuttersService.currentPositionObserver[placeIndex].subscribe(self.currentPositionObserver[placeIndex])
_ = self.rollerShuttersService.targetPositionObserver[placeIndex].subscribe(self.targetPositionObserver[placeIndex])
_ = self.targetPositionPublisher[placeIndex].subscribe(self.rollerShuttersService.targetPositionPublisher[placeIndex])
}
//MARK: Open AllRollingShutters at sunrise if automatic mode
_ = Observable.combineLatest(hourMinutePublisher, sunriseSunsetService.sunriseTimeObserver.debug("sunriseTime"), manualAutomaticModePublisher, inBedService.isInBedObserver, resultSelector:
{(($0 == $1) && ($2 == 0), $3)})
.filter{$0.0 == true}
.map{$0.1}
.debug("sunrise")
.subscribe(onNext: { isInBed in
for placeIndex in 0..<RollerShutter.count.rawValue {
if placeIndex != RollerShutter.bedroom.rawValue || (placeIndex == RollerShutter.bedroom.rawValue && !isInBed) {
self.rollerShuttersService.targetPositionPublisher[placeIndex].onNext(100)
}
}
})
//MARK: Close AllRollingShutters at sunset if automatic mode
_ = Observable.combineLatest(hourMinutePublisher, sunriseSunsetService.sunsetTimeObserver.debug("sunsetTime"), manualAutomaticModePublisher, resultSelector:
{($0 == $1) && $2 == 0})
.filter{$0 == true}
.debug("sunset")
.subscribe(onNext: { _ in
for placeIndex in 0..<RollerShutter.count.rawValue {
self.rollerShuttersService.targetPositionPublisher[placeIndex].onNext(0)
}
})
//MARK: check if it is daylight or nighttime
var isDaylight = false
_ = Observable.combineLatest(hourMinutePublisher, sunriseSunsetService.sunriseTimeObserver, sunriseSunsetService.sunsetTimeObserver, resultSelector:{ now, sunrise, sunset in
let stringToInt : (String) -> Int = { Int($0.replacingOccurrences(of: ":", with: ""))! }
return stringToInt(now) > stringToInt(sunrise) && stringToInt(now) < stringToInt(sunset)
}).subscribe(onNext: { isDayOrNight in
isDaylight = isDayOrNight
})
//MARK: Open bedroom rollershutter after getting out of bed for 15mn if daylight
let wakeUpSequence = [true] + Array(repeating: false, count: 15)
_ = inBedService.isInBedObserver
.throttle(60, scheduler: ConcurrentDispatchQueueScheduler(qos: .default))
.scan([false], accumulator: { (isInBedAccu:[Bool], isInBed:Bool) -> [Bool] in
return isInBedAccu.count >= wakeUpSequence.count ? Array(isInBedAccu.dropFirst()) + [isInBed] : isInBedAccu + [isInBed] })
.filter{$0 == wakeUpSequence}
.map{isInBedSequence in return 100}
.filter({ _ in return isDaylight})
.debug("OutOfBed")
.subscribe(self.rollerShuttersService.targetPositionPublisher[RollerShutter.bedroom.rawValue])
}
}
| mit | 153ffbdc1bb5c37e40c3432c99a8a5b0 | 50.155963 | 262 | 0.664455 | 4.658312 | false | false | false | false |
kylef/JSONWebToken.swift | Sources/JWT/CompactJSONDecoder.swift | 1 | 1033 | import Foundation
class CompactJSONDecoder: JSONDecoder {
override func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable {
guard let string = String(data: data, encoding: .ascii) else {
throw InvalidToken.decodeError("data should contain only ASCII characters")
}
return try decode(type, from: string)
}
func decode<T>(_ type: T.Type, from string: String) throws -> T where T : Decodable {
guard let decoded = base64decode(string) else {
throw InvalidToken.decodeError("data should be a valid base64 string")
}
return try super.decode(type, from: decoded)
}
func decode(from string: String) throws -> Payload {
guard let decoded = base64decode(string) else {
throw InvalidToken.decodeError("Payload is not correctly encoded as base64")
}
let object = try JSONSerialization.jsonObject(with: decoded)
guard let payload = object as? Payload else {
throw InvalidToken.decodeError("Invalid payload")
}
return payload
}
}
| bsd-2-clause | c9fcf4819acaeb67c0d0c856efe45a85 | 31.28125 | 92 | 0.694095 | 4.199187 | false | false | false | false |
JeanVinge/JVInfinityScrollView | JVInfinityScrollView/classes/JVInfinityScrollView.swift | 1 | 3805 | //
// JVInfinityScrollView.swift
// JVInfinityScrollView
//
// Created by Jean Vinge on 02/05/15.
// Copyright (c) 2015 Jean Vinge. All rights reserved.
//
import UIKit
class JVInfinityScrollView: UIScrollView, UIScrollViewDelegate {
/// This var get the last ContentOffset when UIScrollView moves
var lastContentOffsetX = CGFloat()
/// This var get the end of the Content, get the last photo
var endContentOffSet = CGFloat()
init(frame: CGRect, photos: [UIImage?]) {
super.init(frame: frame)
delegate = self
pagingEnabled = true
showsHorizontalScrollIndicator = false
contentMode = UIViewContentMode.ScaleAspectFit
addImages(photos)
// it makes the magic in the scrollView.. we need to set the last - 1 photo because we will create the same photo in the first index so it will make the effect of infinity scroll =)
scrollRectToVisible(CGRectMake(endContentOffSet, 0, frame.width, frame.height), animated: false)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addImages(photos: [UIImage?]) {
var imageViewPositionX = CGFloat()
// here we set the last image on beginning of the scrollview content
var imageView = UIImageView(frame: CGRectMake(imageViewPositionX, frame.origin.y, frame.size.width, frame.size.height))
imageView.image = photos.last!
imageViewPositionX += frame.width
addSubview(imageView)
for photo in photos {
imageView = UIImageView(frame: CGRectMake(imageViewPositionX, frame.origin.y, frame.size.width, frame.size.height))
imageView.image = photo
imageViewPositionX += frame.width
addSubview(imageView)
}
// get the context size total
endContentOffSet = imageViewPositionX
// add the first image at the end of the scrollview content to make the trick
imageView = UIImageView(frame: CGRectMake(imageViewPositionX, frame.origin.y, frame.size.width, frame.size.height))
imageView.image = photos.first!
imageViewPositionX += frame.width
addSubview(imageView)
contentSize = CGSizeMake(imageViewPositionX, imageView.frame.size.height)
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
/* Gets called only after scrolling */
print("ContentOffset.x = \(scrollView.contentOffset.x)")
/**
* This if makes the scrollview moves to the first photo in the array, in fact it is the second photo in the content..
*/
if (scrollView.contentOffset.x == endContentOffSet) {
scrollRectToVisible(CGRectMake(frame.width, 0, frame.width, frame.height), animated: false)
}
/**
* this if verify if the contentOffset is in the begining of the content, if its true, and i scroll <<<<<, the scrollview will be set to the last - 1 photo in my content, that in fact is the last photo on my array of photos =)
*/
if (scrollView.contentOffset.x == 0) {
scrollRectToVisible(CGRectMake(endContentOffSet - frame.width, 0, frame.width, frame.height), animated: false)
}
/**
* See where user is scrolling
*/
if (lastContentOffsetX < scrollView.contentOffset.x) {
print("Scrolling >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
} else {
print("Scrolling <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
}
lastContentOffsetX = scrollView.contentOffset.x
}
}
| mit | 19d4dd5adaeebd6aa09d9906cf131c60 | 36.303922 | 234 | 0.613666 | 5.046419 | false | false | false | false |
guowilling/iOSExamples | Swift/Animations/CAEmitterLayerAnimation/CAEmitterLayerAnimation/EmitterLayerAnimationable.swift | 2 | 1990 | //
// EmitterLayerAnimationable.swift
// CAEmitterLayerAnimation
//
// Created by 郭伟林 on 2017/8/28.
// Copyright © 2017年 SR. All rights reserved.
//
import UIKit
protocol EmitterLayerAnimationable {
}
extension EmitterLayerAnimationable where Self: UIViewController {
func startEmittering(_ point : CGPoint) {
// 创建发射器
let emitter = CAEmitterLayer()
// 设置发射器的位置
emitter.emitterPosition = point
// 开启三维效果
emitter.preservesDepth = true
var cells = [CAEmitterCell]()
for i in 0..<10 { // 创建粒子并设置粒子的相关属性
let cell = CAEmitterCell()
// 粒子速度
cell.velocity = 150
cell.velocityRange = 100
// 粒子大小
cell.scale = 0.7
cell.scaleRange = 0.3
// 粒子方向
cell.emissionLongitude = CGFloat(-Double.pi / 2)
cell.emissionRange = CGFloat(Double.pi / 2 / 6)
// 粒子存活时间
cell.lifetime = 3
cell.lifetimeRange = 1.5
// 粒子旋转
cell.spin = CGFloat(Double.pi / 2)
cell.spinRange = CGFloat(Double.pi / 2 / 2)
// 每秒弹出的粒子个数
cell.birthRate = 2
// 粒子展示的图片
cell.contents = UIImage(named: "good\(i)_30x30")?.cgImage
cells.append(cell)
}
emitter.emitterCells = cells
view.layer.addSublayer(emitter)
}
func stopEmittering() {
// for layer in view.layer.sublayers! {
// if layer.isKind(of: CAEmitterLayer.self) {
// layer.removeFromSuperlayer()
// }
// }
view.layer.sublayers?.filter({ $0.isKind(of: CAEmitterLayer.self)}).first?.removeFromSuperlayer()
}
}
| mit | 526bb79e5408148641983abf2f5222d2 | 26.447761 | 105 | 0.520935 | 4.431325 | false | false | false | false |
bcylin/QuickTableViewController | Example-iOS/ViewControllers/DynamicTableViewController.swift | 1 | 2536 | //
// DynamicTableViewController.swift
// Example-iOS
//
// Created by Zac on 30/01/2018.
//
// 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 QuickTableViewController
internal final class DynamicViewController: QuickTableViewController {
var dynamicRows: [Row & RowStyle] = []
private var cachedTableContents: [Section] = []
override var tableContents: [Section] {
get {
return cachedTableContents
}
set {}
}
private let quickTableView = QuickTableView(frame: .zero, style: .grouped)
override var tableView: UITableView {
get {
return quickTableView
}
set {}
}
private func buildContents() -> [Section] {
let rows: [Row & RowStyle] = [
TapActionRow(text: "AddCell", action: { [unowned self] _ in
self.dynamicRows.append(
NavigationRow(text: "UITableViewCell", detailText: .value1(String(describing: (self.dynamicRows.count + 1))), action: nil)
)
self.tableView.insertRows(at: [IndexPath(row: self.dynamicRows.count, section: 0)], with: .automatic)
})
] + dynamicRows
return [
Section(title: "Tap Action", rows: rows)
]
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Dynamic"
cachedTableContents = buildContents()
quickTableView.quickDelegate = self
}
}
extension DynamicViewController: QuickTableViewDelegate {
func quickReload() {
cachedTableContents = buildContents()
}
}
| mit | 752d9c4846504f8a49bf7fc91e49a9d1 | 31.101266 | 134 | 0.699921 | 4.305603 | false | false | false | false |
github/Nimble | Nimble/Matchers/BeGreaterThanOrEqualTo.swift | 77 | 1498 | import Foundation
public func beGreaterThanOrEqualTo<T: Comparable>(expectedValue: T?) -> MatcherFunc<T> {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be greater than or equal to <\(stringify(expectedValue))>"
let actualValue = actualExpression.evaluate()
return actualValue >= expectedValue
}
}
public func beGreaterThanOrEqualTo<T: NMBComparable>(expectedValue: T?) -> MatcherFunc<T> {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be greater than or equal to <\(stringify(expectedValue))>"
let actualValue = actualExpression.evaluate()
let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) != NSComparisonResult.OrderedAscending
return matches
}
}
public func >=<T: Comparable>(lhs: Expectation<T>, rhs: T) {
lhs.to(beGreaterThanOrEqualTo(rhs))
}
public func >=<T: NMBComparable>(lhs: Expectation<T>, rhs: T) {
lhs.to(beGreaterThanOrEqualTo(rhs))
}
extension NMBObjCMatcher {
public class func beGreaterThanOrEqualToMatcher(expected: NMBComparable?) -> NMBObjCMatcher {
return NMBObjCMatcher { actualBlock, failureMessage, location in
let block = ({ actualBlock() as NMBComparable? })
let expr = Expression(expression: block, location: location)
return beGreaterThanOrEqualTo(expected).matches(expr, failureMessage: failureMessage)
}
}
}
| apache-2.0 | 98d63e12868cf603e9cfd8f93b20cb5e | 40.611111 | 122 | 0.712283 | 5.330961 | false | false | false | false |
xiaoyouPrince/WeiBo | WeiBo/WeiBo/Classes/Tools/Commen/Commen.swift | 1 | 2280 | //
// Commen.swift
// WeiBo
//
// Created by 渠晓友 on 2017/5/24.
// Copyright © 2017年 xiaoyouPrince. All rights reserved.
//
import UIKit
/// itravel 的 app信息,临时使用
let app_key = "2681167680"
let app_secret = "5072b1af9da41b457202eb8b7ebfa30f"
let redirect_uri = "http://www.baidu.com"
// MARK: - 一些微博授权常量
private let rootUrl = "https://api.weibo.com/oauth2/authorize" /// 授权根路径
//let app_key = "2625427871" /// client_id 对应参数 app_key
//let app_secret = "eca1ed907d76ad6f6ce62a8feda67a1c" /// app_secret
//let redirect_uri = "http://www.520it.com" /// 回调路径
let authUrlStr = "\(rootUrl)?client_id=\(app_key)&redirect_uri=\(redirect_uri)" /// authUrlstring
// MARK: - 通知常量
// 发微博添加/删除 image的通知
let picPickerAddPhotoNote = NSNotification.Name(rawValue: "picPickerAddPhotoNote")
let picPickerDeletePhotoNote = NSNotification.Name(rawValue: "picPickerDeletePhotoNote")
let ShowPhotoBrowserIndexKey = "ShowPhotoBrowserIndexKey"
let ShowPhotoBrowserUrlsKey = "ShowPhotoBrowserUrlsKey"
let ShowPhotoBrowserNote = NSNotification.Name(rawValue: "picPickerDeletePhotoNote")
// MARK: - 测试地址
let kGetUrl : String = "http://httpbin.org/get" /// git请求测试
let kPostUrl : String = "http://httpbin.org/post" /// post请求测试
// MARK:-一些常量
let kStatusBarH : CGFloat = 20 /// 状态栏高度
let kNavBarH : CGFloat = 44 /// 导航栏高度
let kTabbarH : CGFloat = 44 /// tabbar高度
let kScreenW : CGFloat = (UIScreen.screens.first?.bounds.size.width)! /// 屏幕宽度
let kScreenH : CGFloat = (UIScreen.screens.first?.bounds.size.height)! /// 屏幕高度
// MARK: - 打印增强
func Dlog<T>(_ message : T ,file : String = #file , funName : String = #function , lineNum : Int = #line){
let filePath = (file as NSString).lastPathComponent
#if DEBUG
print("\(filePath):\(funName):第\(lineNum)行-\n\(message)")
#endif
}
| mit | 60568307e1be00ee60bce11d376a1741 | 29.449275 | 106 | 0.600666 | 3.585324 | false | false | false | false |
SummerHH/swift3.0WeBo | WeBo/Classes/View/PhotoBrowser/ProgressView.swift | 1 | 1073 | //
// ProgressView.swift
// WeBo
//
// Created by Apple on 16/11/20.
// Copyright © 2016年 叶炯. All rights reserved.
//
import UIKit
class ProgressView: UIView {
// MARK:- 定义属性
var progress : CGFloat = 0 {
didSet {
setNeedsDisplay()
}
}
// MARK:- 重写drawRect方法
override func draw(_ rect: CGRect) {
super.draw(rect)
// 获取参数
let center = CGPoint(x: rect.width * 0.5, y: rect.height * 0.5)
let radius = rect.width * 0.5 - 3
let startAngle = CGFloat(-M_PI_2)
let endAngle = CGFloat(2 * M_PI) * progress + startAngle
// 创建贝塞尔曲线
let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
// 绘制一条中心点的线
path.addLine(to: center)
path.close()
// 设置绘制的颜色
UIColor(white: 1.0, alpha: 0.4).setFill()
// 开始绘制
path.fill()
}
}
| apache-2.0 | f818c664e21558b7588dde4d57c4ed77 | 22.52381 | 127 | 0.535425 | 3.756654 | false | false | false | false |
bradhilton/Table | Table/UISearchController.swift | 1 | 1061 | //
// UISearchController.swift
// Table
//
// Created by Bradley Hilton on 3/20/18.
// Copyright © 2018 Brad Hilton. All rights reserved.
//
private class SearchResultsUpdating : NSObject, UISearchResultsUpdating {
var lastSearchResult: String?
func updateSearchResults(for searchController: UISearchController) {
let searchResult = searchController.searchBar.text.flatMap { !$0.isEmpty ? $0 : nil }
if searchResult != lastSearchResult {
lastSearchResult = searchResult
searchController.didSearch?(searchResult)
}
}
}
extension UISearchController {
public var didSearch: ((String?) -> ())? {
get {
return storage[\.didSearch]
}
set {
storage[\.didSearch] = newValue
searchResultsUpdater = defaultSearchResultsUpdater
}
}
private var defaultSearchResultsUpdater: UISearchResultsUpdating {
return storage[\.defaultSearchResultsUpdater, default: SearchResultsUpdating()]
}
}
| mit | c1503c8463e2f3dbf4168c42fd54a528 | 26.179487 | 93 | 0.643396 | 5.353535 | false | false | false | false |
HeartOfCarefreeHeavens/TestKitchen_pww | TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBWorksCell.swift | 1 | 3650 | //
// CBWorksCell.swift
// TestKitchen
//
// Created by qianfeng on 16/8/22.
// Copyright © 2016年 qianfeng. All rights reserved.
//
import UIKit
class CBWorksCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var descLabel: UILabel!
@IBAction func clickBtn(sender: UIButton) {
}
@IBAction func clickUserBtn(sender: UIButton) {
}
var model:CBRecommendWidgetListModel?{
didSet{
showData()
}
}
func showData(){
for i in 0..<3{
if model?.widget_data?.count>i*3{
let imageModel = model?.widget_data![i*3]
if imageModel?.type == "image" {
let subView = contentView.viewWithTag(100+i)
if subView?.isKindOfClass(UIButton.self) == true {
let btn = subView as! UIButton
let url = NSURL(string: imageModel!.content!)
btn.kf_setBackgroundImageWithURL(url, forState: .Normal, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
}
}
if model?.widget_data?.count>i*3+1{
let imageModel = model?.widget_data![i*3+1]
if imageModel?.type == "image" {
let subView = contentView.viewWithTag(200+i)
if subView?.isKindOfClass(UIButton.self) == true {
let btn = subView as! UIButton
btn.layer.cornerRadius = 20
btn.layer.masksToBounds = true
let url = NSURL(string: imageModel!.content!)
btn.kf_setBackgroundImageWithURL(url, forState: .Normal, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
}
}
if model?.widget_data?.count>i*3+2{
let nameModel = model?.widget_data![i*3+2]
if nameModel?.type == "text" {
let subView = contentView.viewWithTag(300+i)
if subView?.isKindOfClass(UILabel.self) == true {
let nameLabel = subView as! UILabel
nameLabel.text = nameModel?.content
}
}
}
}
let subView = contentView.viewWithTag(400)
if subView?.isKindOfClass(UILabel.self) == true {
let descLabel = subView as! UILabel
descLabel.text = model?.desc
}
}
class func createWorksCellFor(tableView:UITableView,atIndexPath indexPath:NSIndexPath,withListModel listModel:CBRecommendWidgetListModel)->CBWorksCell{
let cellId = "worksCellId"
var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CBWorksCell
if cell == nil {
cell = NSBundle.mainBundle().loadNibNamed("CBWorksCell", owner:nil , options: nil).last as? CBWorksCell
}
cell?.model = listModel
return cell!
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 7874fd8fc17edb8dd56994d96cdb6ce6 | 30.439655 | 193 | 0.52646 | 5.262626 | false | false | false | false |
SeraZheng/GitHouse.swift | 3rd/NavigationStack/CollectionStackViewController.swift | 1 | 6847 | //
// CollectionStackViewController.swift
// NavigationStackDemo
//
// Copyright (c) 26/02/16 Ramotion Inc. (http://ramotion.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
// MARK: CollectionStackViewController
protocol CollectionStackViewControllerDelegate: class {
func controllerDidSelected(index index: Int)
}
class CollectionStackViewController: UICollectionViewController {
private var screens: [UIImage]
private let overlay: Float
weak var delegate: CollectionStackViewControllerDelegate?
init(images: [UIImage],
delegate: CollectionStackViewControllerDelegate?,
overlay: Float,
scaleRatio: Float,
scaleValue: Float,
bgColor: UIColor,
decelerationRate:CGFloat) {
self.screens = images
self.delegate = delegate
self.overlay = overlay
let layout = CollectionViewStackFlowLayout(itemsCount: images.count, overlay: overlay, scaleRatio: scaleRatio, scale:scaleValue)
super.init(collectionViewLayout: layout)
if let collectionView = self.collectionView {
collectionView.backgroundColor = bgColor
collectionView.decelerationRate = decelerationRate
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
configureCollectionView()
scrolltoIndex(screens.count - 1, animated: false, position: .Left) // move to end
}
override func viewDidAppear(animated: Bool) {
guard let collectionViewLayout = self.collectionViewLayout as? CollectionViewStackFlowLayout else {
fatalError("wrong collection layout")
}
collectionViewLayout.openAnimating = true
scrolltoIndex(0, animated: true, position: .Left) // open animation
}
}
// MARK: configure
extension CollectionStackViewController {
private func configureCollectionView() {
guard let collectionViewLayout = self.collectionViewLayout as? UICollectionViewFlowLayout else {
fatalError("wrong collection layout")
}
collectionViewLayout.scrollDirection = .Horizontal
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.registerClass(CollectionViewStackCell.self, forCellWithReuseIdentifier: String(CollectionViewStackCell))
}
}
// MARK: CollectionViewDataSource
extension CollectionStackViewController {
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return screens.count
}
override func collectionView(collectionView: UICollectionView,
willDisplayCell cell: UICollectionViewCell,
forItemAtIndexPath indexPath: NSIndexPath) {
if let cell = cell as? CollectionViewStackCell {
cell.imageView?.image = screens[indexPath.row]
}
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(String(CollectionViewStackCell),
forIndexPath: indexPath)
return cell
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
delegate?.controllerDidSelected(index: indexPath.row)
guard let currentCell = collectionView.cellForItemAtIndexPath(indexPath) else {
return
}
// move cells
UIView.animateWithDuration(0.3, delay: 0, options:.CurveEaseIn,
animations: { () -> Void in
for cell in self.collectionView!.visibleCells() where cell != currentCell {
let row = self.collectionView?.indexPathForCell(cell)?.row
let xPosition = row < indexPath.row ? cell.center.x - self.view.bounds.size.width * 2
: cell.center.x + self.view.bounds.size.width * 2
cell.center = CGPoint(x: xPosition, y: cell.center.y)
}
}, completion: nil)
// move to center current cell
UIView.animateWithDuration(0.2, delay: 0.2, options:.CurveEaseOut,
animations: { () -> Void in
let offset = collectionView.contentOffset.x - (self.view.bounds.size.width - collectionView.bounds.size.width * CGFloat(self.overlay)) * CGFloat(indexPath.row)
currentCell.center = CGPoint(x: (currentCell.center.x + offset), y: currentCell.center.y)
}, completion: nil)
// scale current cell
UIView.animateWithDuration(0.2, delay: 0.6, options:.CurveEaseOut, animations: { () -> Void in
let scale = CGAffineTransformMakeScale(1, 1)
currentCell.transform = scale
currentCell.alpha = 1
}) { (success) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.dismissViewControllerAnimated(false, completion: nil)
})
}
}
}
// MARK: UICollectionViewDelegateFlowLayout
extension CollectionStackViewController: UICollectionViewDelegateFlowLayout {
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return view.bounds.size
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: NSInteger) -> CGFloat {
return -collectionView.bounds.size.width * CGFloat(overlay)
}
}
// MARK: Additional helpers
extension CollectionStackViewController {
private func scrolltoIndex(index: Int, animated: Bool , position: UICollectionViewScrollPosition) {
let indexPath = NSIndexPath(forItem: index, inSection: 0)
collectionView?.scrollToItemAtIndexPath(indexPath, atScrollPosition: position, animated: animated)
}
}
| mit | d52d287c7d769585cc04e0acdb550a2e | 36.415301 | 177 | 0.727034 | 5.214775 | false | false | false | false |
CliffLee/Vendope | daf/CircleTransitionAnimator.swift | 1 | 2540 | //
// CircleTransitionAnimator.swift
// daf
//
// Created by Nicholas Cai on 10/3/15.
// Copyright © 2015 Clifford Lee. All rights reserved.
//
import UIKit
class CircleTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.2
}
weak var transitionContext: UIViewControllerContextTransitioning?
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
//1
self.transitionContext = transitionContext
//2
var containerView = transitionContext.containerView()
var fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! StartViewController
var toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! LoginViewController
var button = fromViewController.button
//3
containerView!.addSubview(toViewController.view)
//4
var circleMaskPathInitial = UIBezierPath(ovalInRect: button.frame)
var extremePoint = CGPoint(x: button.center.x - 0, y: button.center.y - CGRectGetHeight(toViewController.view.bounds))
var radius = sqrt((extremePoint.x*extremePoint.x) + (extremePoint.y*extremePoint.y))
var circleMaskPathFinal = UIBezierPath(ovalInRect: CGRectInset(button.frame, -radius, -radius))
//5
var maskLayer = CAShapeLayer()
maskLayer.path = circleMaskPathFinal.CGPath
toViewController.view.layer.mask = maskLayer
//6
var maskLayerAnimation = CABasicAnimation(keyPath: "path")
maskLayerAnimation.fromValue = circleMaskPathInitial.CGPath
maskLayerAnimation.toValue = circleMaskPathFinal.CGPath
maskLayerAnimation.duration = self.transitionDuration(transitionContext)
maskLayerAnimation.delegate = self
// maskLayerAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
maskLayer.addAnimation(maskLayerAnimation, forKey: "path")
}
override func animationDidStop(anim: CAAnimation!, finished flag: Bool) {
self.transitionContext?.completeTransition(!self.transitionContext!.transitionWasCancelled())
self.transitionContext?.viewControllerForKey(UITransitionContextFromViewControllerKey)?.view.layer.mask = nil
}
}
| mit | 8c9525d307184594eee9584c78baf30c | 42.033898 | 137 | 0.724695 | 5.836782 | false | false | false | false |
almazrafi/Metatron | Tests/MetatronTests/ID3v2/FrameStuffs/ID3v2LyricsValueTest.swift | 1 | 22644 | //
// ID3v2LyricsValueTest.swift
// Metatron
//
// Copyright (c) 2016 Almaz Ibragimov
//
// 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 Metatron
class ID3v2LyricsValueTest: XCTestCase {
// MARK: Instance Methods
func testSyncedLyrics() {
let stuff = ID3v2SyncedLyrics()
do {
stuff.lyricsValue = TagLyrics()
XCTAssert(stuff.lyricsValue == TagLyrics())
XCTAssert(stuff.timeStampFormat == ID3v2TimeStampFormat.absoluteMilliseconds)
XCTAssert(stuff.syllables == [])
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("Abc 123")])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 123")]))
XCTAssert(stuff.timeStampFormat == ID3v2TimeStampFormat.absoluteMilliseconds)
XCTAssert(stuff.syllables == [ID3v2SyncedLyrics.Syllable("Abc 123", timeStamp: 0)])
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("Абв 123")])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Абв 123")]))
XCTAssert(stuff.timeStampFormat == ID3v2TimeStampFormat.absoluteMilliseconds)
XCTAssert(stuff.syllables == [ID3v2SyncedLyrics.Syllable("Абв 123", timeStamp: 0)])
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("Abc 1"),
TagLyrics.Piece("Abc 2")])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1"),
TagLyrics.Piece("Abc 2")]))
XCTAssert(stuff.timeStampFormat == ID3v2TimeStampFormat.absoluteMilliseconds)
XCTAssert(stuff.syllables == [ID3v2SyncedLyrics.Syllable("Abc 1", timeStamp: 0),
ID3v2SyncedLyrics.Syllable("Abc 2", timeStamp: 0)])
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 1230),
TagLyrics.Piece("Abc 2", timeStamp: 4560)])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 1230),
TagLyrics.Piece("Abc 2", timeStamp: 4560)]))
XCTAssert(stuff.timeStampFormat == ID3v2TimeStampFormat.absoluteMilliseconds)
XCTAssert(stuff.syllables == [ID3v2SyncedLyrics.Syllable("Abc 1", timeStamp: 1230),
ID3v2SyncedLyrics.Syllable("Abc 2", timeStamp: 4560)])
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("Abc 1"),
TagLyrics.Piece("Abc 2", timeStamp: 4560)])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1"),
TagLyrics.Piece("Abc 2", timeStamp: 4560)]))
XCTAssert(stuff.timeStampFormat == ID3v2TimeStampFormat.absoluteMilliseconds)
XCTAssert(stuff.syllables == [ID3v2SyncedLyrics.Syllable("Abc 1", timeStamp: 0),
ID3v2SyncedLyrics.Syllable("Abc 2", timeStamp: 4560)])
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 1230),
TagLyrics.Piece("Abc 2")])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 1230),
TagLyrics.Piece("Abc 2")]))
XCTAssert(stuff.timeStampFormat == ID3v2TimeStampFormat.absoluteMilliseconds)
XCTAssert(stuff.syllables == [ID3v2SyncedLyrics.Syllable("Abc 1", timeStamp: 1230),
ID3v2SyncedLyrics.Syllable("Abc 2", timeStamp: 0)])
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 4560),
TagLyrics.Piece("Abc 2", timeStamp: 1230)])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 4560),
TagLyrics.Piece("Abc 2", timeStamp: 1230)]))
XCTAssert(stuff.timeStampFormat == ID3v2TimeStampFormat.absoluteMilliseconds)
XCTAssert(stuff.syllables == [ID3v2SyncedLyrics.Syllable("Abc 1", timeStamp: 4560),
ID3v2SyncedLyrics.Syllable("Abc 2", timeStamp: 1230)])
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("", timeStamp: 1230),
TagLyrics.Piece("Abc 2", timeStamp: 4560)])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("", timeStamp: 1230),
TagLyrics.Piece("Abc 2", timeStamp: 4560)]))
XCTAssert(stuff.timeStampFormat == ID3v2TimeStampFormat.absoluteMilliseconds)
XCTAssert(stuff.syllables == [ID3v2SyncedLyrics.Syllable("", timeStamp: 1230),
ID3v2SyncedLyrics.Syllable("Abc 2", timeStamp: 4560)])
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("", timeStamp: 4560),
TagLyrics.Piece("Abc 2", timeStamp: 1230)])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("", timeStamp: 4560),
TagLyrics.Piece("Abc 2", timeStamp: 1230)]))
XCTAssert(stuff.timeStampFormat == ID3v2TimeStampFormat.absoluteMilliseconds)
XCTAssert(stuff.syllables == [ID3v2SyncedLyrics.Syllable("", timeStamp: 4560),
ID3v2SyncedLyrics.Syllable("Abc 2", timeStamp: 1230)])
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 1230),
TagLyrics.Piece("", timeStamp: 4560)])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 1230),
TagLyrics.Piece("", timeStamp: 4560)]))
XCTAssert(stuff.timeStampFormat == ID3v2TimeStampFormat.absoluteMilliseconds)
XCTAssert(stuff.syllables == [ID3v2SyncedLyrics.Syllable("Abc 1", timeStamp: 1230),
ID3v2SyncedLyrics.Syllable("", timeStamp: 4560)])
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 4560),
TagLyrics.Piece("", timeStamp: 1230)])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 4560),
TagLyrics.Piece("", timeStamp: 1230)]))
XCTAssert(stuff.timeStampFormat == ID3v2TimeStampFormat.absoluteMilliseconds)
XCTAssert(stuff.syllables == [ID3v2SyncedLyrics.Syllable("Abc 1", timeStamp: 4560),
ID3v2SyncedLyrics.Syllable("", timeStamp: 1230)])
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("", timeStamp: 1230),
TagLyrics.Piece("", timeStamp: 4560)])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("", timeStamp: 1230),
TagLyrics.Piece("", timeStamp: 4560)]))
XCTAssert(stuff.timeStampFormat == ID3v2TimeStampFormat.absoluteMilliseconds)
XCTAssert(stuff.syllables == [ID3v2SyncedLyrics.Syllable("", timeStamp: 1230),
ID3v2SyncedLyrics.Syllable("", timeStamp: 4560)])
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("", timeStamp: 4560),
TagLyrics.Piece("", timeStamp: 1230)])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("", timeStamp: 4560),
TagLyrics.Piece("", timeStamp: 1230)]))
XCTAssert(stuff.timeStampFormat == ID3v2TimeStampFormat.absoluteMilliseconds)
XCTAssert(stuff.syllables == [ID3v2SyncedLyrics.Syllable("", timeStamp: 4560),
ID3v2SyncedLyrics.Syllable("", timeStamp: 1230)])
}
do {
stuff.timeStampFormat = ID3v2TimeStampFormat.absoluteMPEGFrames
stuff.syllables = []
XCTAssert(stuff.lyricsValue == TagLyrics())
}
do {
stuff.timeStampFormat = ID3v2TimeStampFormat.absoluteMilliseconds
stuff.syllables = []
XCTAssert(stuff.lyricsValue == TagLyrics())
}
do {
stuff.timeStampFormat = ID3v2TimeStampFormat.absoluteMPEGFrames
stuff.syllables = [ID3v2SyncedLyrics.Syllable("Abc 1", timeStamp: 1230),
ID3v2SyncedLyrics.Syllable("Abc 2", timeStamp: 4560)]
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1"),
TagLyrics.Piece("Abc 2")]))
}
do {
stuff.timeStampFormat = ID3v2TimeStampFormat.absoluteMPEGFrames
stuff.syllables = [ID3v2SyncedLyrics.Syllable("Abc 1", timeStamp: 4560),
ID3v2SyncedLyrics.Syllable("Abc 2", timeStamp: 1230)]
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1"),
TagLyrics.Piece("Abc 2")]))
}
do {
stuff.timeStampFormat = ID3v2TimeStampFormat.absoluteMilliseconds
stuff.syllables = [ID3v2SyncedLyrics.Syllable("Abc 123", timeStamp: 0)]
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 123")]))
}
do {
stuff.timeStampFormat = ID3v2TimeStampFormat.absoluteMilliseconds
stuff.syllables = [ID3v2SyncedLyrics.Syllable("Абв 123", timeStamp: 0)]
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Абв 123")]))
}
do {
stuff.timeStampFormat = ID3v2TimeStampFormat.absoluteMilliseconds
stuff.syllables = [ID3v2SyncedLyrics.Syllable("Abc 1", timeStamp: 0),
ID3v2SyncedLyrics.Syllable("Abc 2", timeStamp: 0)]
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1"),
TagLyrics.Piece("Abc 2")]))
}
do {
stuff.timeStampFormat = ID3v2TimeStampFormat.absoluteMilliseconds
stuff.syllables = [ID3v2SyncedLyrics.Syllable("Abc 1", timeStamp: 1230),
ID3v2SyncedLyrics.Syllable("Abc 2", timeStamp: 4560)]
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 1230),
TagLyrics.Piece("Abc 2", timeStamp: 4560)]))
}
do {
stuff.timeStampFormat = ID3v2TimeStampFormat.absoluteMilliseconds
stuff.syllables = [ID3v2SyncedLyrics.Syllable("Abc 1", timeStamp: 0),
ID3v2SyncedLyrics.Syllable("Abc 2", timeStamp: 4560)]
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1"),
TagLyrics.Piece("Abc 2", timeStamp: 4560)]))
}
do {
stuff.timeStampFormat = ID3v2TimeStampFormat.absoluteMilliseconds
stuff.syllables = [ID3v2SyncedLyrics.Syllable("Abc 1", timeStamp: 1230),
ID3v2SyncedLyrics.Syllable("Abc 2", timeStamp: 0)]
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 1230),
TagLyrics.Piece("Abc 2")]))
}
do {
stuff.timeStampFormat = ID3v2TimeStampFormat.absoluteMilliseconds
stuff.syllables = [ID3v2SyncedLyrics.Syllable("Abc 1", timeStamp: 4560),
ID3v2SyncedLyrics.Syllable("Abc 2", timeStamp: 1230)]
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 4560),
TagLyrics.Piece("Abc 2", timeStamp: 1230)]))
}
do {
stuff.timeStampFormat = ID3v2TimeStampFormat.absoluteMilliseconds
stuff.syllables = [ID3v2SyncedLyrics.Syllable("", timeStamp: 1230),
ID3v2SyncedLyrics.Syllable("Abc 2", timeStamp: 4560)]
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("", timeStamp: 1230),
TagLyrics.Piece("Abc 2", timeStamp: 4560)]))
}
do {
stuff.timeStampFormat = ID3v2TimeStampFormat.absoluteMilliseconds
stuff.syllables = [ID3v2SyncedLyrics.Syllable("", timeStamp: 4560),
ID3v2SyncedLyrics.Syllable("Abc 2", timeStamp: 1230)]
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("", timeStamp: 4560),
TagLyrics.Piece("Abc 2", timeStamp: 1230)]))
}
do {
stuff.timeStampFormat = ID3v2TimeStampFormat.absoluteMilliseconds
stuff.syllables = [ID3v2SyncedLyrics.Syllable("Abc 1", timeStamp: 1230),
ID3v2SyncedLyrics.Syllable("", timeStamp: 4560)]
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 1230),
TagLyrics.Piece("", timeStamp: 4560)]))
}
do {
stuff.timeStampFormat = ID3v2TimeStampFormat.absoluteMilliseconds
stuff.syllables = [ID3v2SyncedLyrics.Syllable("Abc 1", timeStamp: 4560),
ID3v2SyncedLyrics.Syllable("", timeStamp: 1230)]
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 4560),
TagLyrics.Piece("", timeStamp: 1230)]))
}
do {
stuff.timeStampFormat = ID3v2TimeStampFormat.absoluteMilliseconds
stuff.syllables = [ID3v2SyncedLyrics.Syllable("", timeStamp: 1230),
ID3v2SyncedLyrics.Syllable("", timeStamp: 4560)]
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("", timeStamp: 1230),
TagLyrics.Piece("", timeStamp: 4560)]))
}
do {
stuff.timeStampFormat = ID3v2TimeStampFormat.absoluteMilliseconds
stuff.syllables = [ID3v2SyncedLyrics.Syllable("", timeStamp: 4560),
ID3v2SyncedLyrics.Syllable("", timeStamp: 1230)]
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("", timeStamp: 4560),
TagLyrics.Piece("", timeStamp: 1230)]))
}
}
func testUnsyncedLyrics() {
let stuff = ID3v2UnsyncedLyrics()
do {
stuff.lyricsValue = TagLyrics()
XCTAssert(stuff.lyricsValue == TagLyrics())
XCTAssert(stuff.content == "")
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("Abc 123")])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 123")]))
XCTAssert(stuff.content == "Abc 123")
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("Абв 123")])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Абв 123")]))
XCTAssert(stuff.content == "Абв 123")
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("Abc 1"),
TagLyrics.Piece("Abc 2")])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1\nAbc 2")]))
XCTAssert(stuff.content == "Abc 1\nAbc 2")
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 1230),
TagLyrics.Piece("Abc 2", timeStamp: 4560)])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1\nAbc 2")]))
XCTAssert(stuff.content == "Abc 1\nAbc 2")
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("Abc 1"),
TagLyrics.Piece("Abc 2", timeStamp: 4560)])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1\nAbc 2")]))
XCTAssert(stuff.content == "Abc 1\nAbc 2")
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 1230),
TagLyrics.Piece("Abc 2")])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1\nAbc 2")]))
XCTAssert(stuff.content == "Abc 1\nAbc 2")
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 4560),
TagLyrics.Piece("Abc 2", timeStamp: 1230)])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1\nAbc 2")]))
XCTAssert(stuff.content == "Abc 1\nAbc 2")
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("", timeStamp: 1230),
TagLyrics.Piece("Abc 2", timeStamp: 4560)])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("\nAbc 2")]))
XCTAssert(stuff.content == "\nAbc 2")
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("", timeStamp: 4560),
TagLyrics.Piece("Abc 2", timeStamp: 1230)])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("\nAbc 2")]))
XCTAssert(stuff.content == "\nAbc 2")
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 1230),
TagLyrics.Piece("", timeStamp: 4560)])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1\n")]))
XCTAssert(stuff.content == "Abc 1\n")
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("Abc 1", timeStamp: 4560),
TagLyrics.Piece("", timeStamp: 1230)])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1\n")]))
XCTAssert(stuff.content == "Abc 1\n")
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("", timeStamp: 4560),
TagLyrics.Piece("", timeStamp: 1230)])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("\n")]))
XCTAssert(stuff.content == "\n")
}
do {
stuff.lyricsValue = TagLyrics(pieces: [TagLyrics.Piece("", timeStamp: 1230),
TagLyrics.Piece("", timeStamp: 4560)])
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("\n")]))
XCTAssert(stuff.content == "\n")
}
do {
stuff.content = ""
XCTAssert(stuff.lyricsValue == TagLyrics())
}
do {
stuff.content = "Abc 123"
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 123")]))
}
do {
stuff.content = "Абв 123"
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Абв 123")]))
}
do {
stuff.content = "Abc 1\nAbc 2"
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1\nAbc 2")]))
}
do {
stuff.content = "\nAbc 2"
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("\nAbc 2")]))
}
do {
stuff.content = "Abc 1\n"
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("Abc 1\n")]))
}
do {
stuff.content = "\n"
XCTAssert(stuff.lyricsValue == TagLyrics(pieces: [TagLyrics.Piece("\n")]))
}
}
}
| mit | 8dd36560b7af9ed369a372ae0bd22128 | 41.910816 | 106 | 0.539533 | 4.664604 | false | false | false | false |
Yurssoft/QuickFile | Pods/SwiftMessages/SwiftMessages/MaskingView.swift | 2 | 1284 | //
// MaskingView.swift
// SwiftMessages
//
// Created by Timothy Moose on 3/11/17.
// Copyright © 2017 SwiftKick Mobile. All rights reserved.
//
import UIKit
class MaskingView: PassthroughView {
var accessibleElements: [NSObject] = []
weak var backgroundView: UIView? {
didSet {
oldValue?.removeFromSuperview()
if let view = backgroundView {
view.isUserInteractionEnabled = false
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(view)
sendSubview(toBack: view)
}
}
}
override func accessibilityElementCount() -> Int {
return accessibleElements.count
}
override func accessibilityElement(at index: Int) -> Any? {
return accessibleElements[index]
}
override func index(ofAccessibilityElement element: Any) -> Int {
guard let object = element as? NSObject else { return 0 }
return accessibleElements.index(of: object) ?? 0
}
init() {
super.init(frame: CGRect.zero)
clipsToBounds = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
clipsToBounds = true
}
}
| mit | 1fc9b93ce9d6e4af27978d077fb9c5f0 | 24.156863 | 73 | 0.605612 | 4.878327 | false | false | false | false |
149393437/Templates | Templates/Project Templates/Mac/Application Extension/Share Extension.xctemplate/GenericViewController.swift | 1 | 1162 | //
// ___FILENAME___
// ___PACKAGENAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
//___COPYRIGHT___
//
import Cocoa
class ___FILEBASENAME___: NSViewController {
override var nibName: String? {
return "___FILEBASENAME___"
}
override func loadView() {
super.loadView()
// Insert code here to customize the view
let item = self.extensionContext!.inputItems[0] as NSExtensionItem
if let attachments = item.attachments {
NSLog("Attachments = %@", attachments)
} else {
NSLog("No Attachments")
}
}
@IBAction func send(sender: AnyObject?) {
let outputItem = NSExtensionItem()
// Complete implementation by setting the appropriate value on the output item
let outputItems = [outputItem]
self.extensionContext!.completeRequestReturningItems(outputItems, completionHandler: nil)
}
@IBAction func cancel(sender: AnyObject?) {
let cancelError = NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError, userInfo: nil)
self.extensionContext!.cancelRequestWithError(cancelError)
}
}
| mit | e7908d03885f18a7f141c752ef0c90be | 26.666667 | 104 | 0.63253 | 5.052174 | false | false | false | false |
Pyrolr/aditsss | SegmentedSearch/MainVCViewController.swift | 1 | 1867 | //
// MainVCViewController.swift
// SegmentedSearch
//
// Created by Hardik on 13/12/15.
// Copyright © 2015 HDG. All rights reserved.
//
import UIKit
class MainVCViewController: UIViewController {
// MARK: - Memory Managment methods
// ---------------------------------------------------------------------
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// ---------------------------------------------------------------------
deinit {
}
// ---------------------------------------------------------------------
// MARK: - Custom methods
// ---------------------------------------------------------------------
func baseSetup() {
}
@IBAction func btnClicked(sender: AnyObject) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("SearchVC") as! ViewController
let navigationController = UINavigationController(rootViewController: vc)
navigationController.navigationBar.translucent = false
vc.arrColors = ["Red","Green","Blue","Black","Yellow","Orange","Purple","Brown","Gray","Pink"]
self.presentViewController(navigationController, animated: true, completion: nil)
}
// ---------------------------------------------------------------------
// MARK: - Life cycle methods
// ---------------------------------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
self.baseSetup()
// Do any additional setup after loading the view, typically from a nib.
}
// ---------------------------------------------------------------------
}
| mit | 02efada2b931ebd743d6ad08f333d8e4 | 29.096774 | 102 | 0.450161 | 6.71223 | false | false | false | false |
WeHUD/app | weHub-ios/Gzone_App/Pods/XLPagerTabStrip/Sources/PagerTabStripViewController.swift | 5 | 16741 | // PagerTabStripViewController.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
// MARK: Protocols
public protocol IndicatorInfoProvider {
func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo
}
public protocol PagerTabStripDelegate: class {
func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int)
}
public protocol PagerTabStripIsProgressiveDelegate : PagerTabStripDelegate {
func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool)
}
public protocol PagerTabStripDataSource: class {
func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController]
}
//MARK: PagerTabStripViewController
open class PagerTabStripViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet weak public var containerView: UIScrollView!
open weak var delegate: PagerTabStripDelegate?
open weak var datasource: PagerTabStripDataSource?
open var pagerBehaviour = PagerTabStripBehaviour.progressive(skipIntermediateViewControllers: true, elasticIndicatorLimit: true)
open private(set) var viewControllers = [UIViewController]()
open private(set) var currentIndex = 0
open var pageWidth: CGFloat {
return containerView.bounds.width
}
open var scrollPercentage: CGFloat {
if swipeDirection != .right {
let module = fmod(containerView.contentOffset.x, pageWidth)
return module == 0.0 ? 1.0 : module / pageWidth
}
return 1 - fmod(containerView.contentOffset.x >= 0 ? containerView.contentOffset.x : pageWidth + containerView.contentOffset.x, pageWidth) / pageWidth
}
open var swipeDirection: SwipeDirection {
if containerView.contentOffset.x > lastContentOffset {
return .left
}
else if containerView.contentOffset.x < lastContentOffset {
return .right
}
return .none
}
override open func viewDidLoad() {
super.viewDidLoad()
let conteinerViewAux = containerView ?? {
let containerView = UIScrollView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height))
containerView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
return containerView
}()
containerView = conteinerViewAux
if containerView.superview == nil {
view.addSubview(containerView)
}
containerView.bounces = true
containerView.alwaysBounceHorizontal = true
containerView.alwaysBounceVertical = false
containerView.scrollsToTop = false
containerView.delegate = self
containerView.showsVerticalScrollIndicator = false
containerView.showsHorizontalScrollIndicator = false
containerView.isPagingEnabled = true
reloadViewControllers()
let childController = viewControllers[currentIndex]
addChildViewController(childController)
childController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
containerView.addSubview(childController.view)
childController.didMove(toParentViewController: self)
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
isViewAppearing = true
childViewControllers.forEach { $0.beginAppearanceTransition(true, animated: animated) }
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
lastSize = containerView.bounds.size
updateIfNeeded()
isViewAppearing = false
childViewControllers.forEach { $0.endAppearanceTransition() }
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
childViewControllers.forEach { $0.beginAppearanceTransition(false, animated: animated) }
}
open override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
childViewControllers.forEach { $0.endAppearanceTransition() }
}
override open func viewDidLayoutSubviews(){
super.viewDidLayoutSubviews()
updateIfNeeded()
}
open override var shouldAutomaticallyForwardAppearanceMethods: Bool {
return false
}
open func moveToViewController(at index: Int, animated: Bool = true) {
guard isViewLoaded && view.window != nil && currentIndex != index else {
currentIndex = index
return
}
if animated && pagerBehaviour.skipIntermediateViewControllers && abs(currentIndex - index) > 1 {
var tmpViewControllers = viewControllers
let currentChildVC = viewControllers[currentIndex]
let fromIndex = currentIndex < index ? index - 1 : index + 1
let fromChildVC = viewControllers[fromIndex]
tmpViewControllers[currentIndex] = fromChildVC
tmpViewControllers[fromIndex] = currentChildVC
pagerTabStripChildViewControllersForScrolling = tmpViewControllers
containerView.setContentOffset(CGPoint(x: pageOffsetForChild(at: fromIndex), y: 0), animated: false)
(navigationController?.view ?? view).isUserInteractionEnabled = !animated
containerView.setContentOffset(CGPoint(x: pageOffsetForChild(at: index), y: 0), animated: true)
}
else {
(navigationController?.view ?? view).isUserInteractionEnabled = !animated
containerView.setContentOffset(CGPoint(x: pageOffsetForChild(at: index), y: 0), animated: animated)
}
}
open func moveTo(viewController: UIViewController, animated: Bool = true) {
moveToViewController(at: viewControllers.index(of: viewController)!, animated: animated)
}
//MARK: - PagerTabStripDataSource
open func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] {
assertionFailure("Sub-class must implement the PagerTabStripDataSource viewControllers(for:) method")
return []
}
//MARK: - Helpers
open func updateIfNeeded() {
if isViewLoaded && !lastSize.equalTo(containerView.bounds.size){
updateContent()
}
}
open func canMoveTo(index: Int) -> Bool {
return currentIndex != index && viewControllers.count > index
}
open func pageOffsetForChild(at index: Int) -> CGFloat {
return CGFloat(index) * containerView.bounds.width
}
open func offsetForChild(at index: Int) -> CGFloat{
return (CGFloat(index) * containerView.bounds.width) + ((containerView.bounds.width - view.bounds.width) * 0.5)
}
open func offsetForChild(viewController: UIViewController) throws -> CGFloat{
guard let index = viewControllers.index(of: viewController) else {
throw PagerTabStripError.viewControllerNotContainedInPagerTabStrip
}
return offsetForChild(at: index)
}
open func pageFor(contentOffset: CGFloat) -> Int {
let result = virtualPageFor(contentOffset: contentOffset)
return pageFor(virtualPage: result)
}
open func virtualPageFor(contentOffset: CGFloat) -> Int {
return Int((contentOffset + 1.5 * pageWidth) / pageWidth) - 1
}
open func pageFor(virtualPage: Int) -> Int{
if virtualPage < 0 {
return 0
}
if virtualPage > viewControllers.count - 1 {
return viewControllers.count - 1
}
return virtualPage
}
open func updateContent() {
if lastSize.width != containerView.bounds.size.width {
lastSize = containerView.bounds.size
containerView.contentOffset = CGPoint(x: pageOffsetForChild(at: currentIndex), y: 0)
}
lastSize = containerView.bounds.size
let pagerViewControllers = pagerTabStripChildViewControllersForScrolling ?? viewControllers
containerView.contentSize = CGSize(width: containerView.bounds.width * CGFloat(pagerViewControllers.count), height: containerView.contentSize.height)
for (index, childController) in pagerViewControllers.enumerated() {
let pageOffsetForChild = self.pageOffsetForChild(at: index)
if fabs(containerView.contentOffset.x - pageOffsetForChild) < containerView.bounds.width {
if let _ = childController.parent {
childController.view.frame = CGRect(x: offsetForChild(at: index), y: 0, width: view.bounds.width, height: containerView.bounds.height)
childController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
}
else {
childController.beginAppearanceTransition(true, animated: false)
addChildViewController(childController)
childController.view.frame = CGRect(x: offsetForChild(at: index), y: 0, width: view.bounds.width, height: containerView.bounds.height)
childController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
containerView.addSubview(childController.view)
childController.didMove(toParentViewController: self)
childController.endAppearanceTransition()
}
}
else {
if let _ = childController.parent {
childController.beginAppearanceTransition(false, animated: false)
childController.willMove(toParentViewController: nil)
childController.view.removeFromSuperview()
childController.removeFromParentViewController()
childController.endAppearanceTransition()
}
}
}
let oldCurrentIndex = currentIndex
let virtualPage = virtualPageFor(contentOffset: containerView.contentOffset.x)
let newCurrentIndex = pageFor(virtualPage: virtualPage)
currentIndex = newCurrentIndex
let changeCurrentIndex = newCurrentIndex != oldCurrentIndex
if let progressiveDeledate = self as? PagerTabStripIsProgressiveDelegate, pagerBehaviour.isProgressiveIndicator {
let (fromIndex, toIndex, scrollPercentage) = progressiveIndicatorData(virtualPage)
progressiveDeledate.updateIndicator(for: self, fromIndex: fromIndex, toIndex: toIndex, withProgressPercentage: scrollPercentage, indexWasChanged: changeCurrentIndex)
}
else{
delegate?.updateIndicator(for: self, fromIndex: min(oldCurrentIndex, pagerViewControllers.count - 1), toIndex: newCurrentIndex)
}
}
open func reloadPagerTabStripView() {
guard isViewLoaded else { return }
for childController in viewControllers {
if let _ = childController.parent {
childController.beginAppearanceTransition(false, animated: false)
childController.willMove(toParentViewController: nil)
childController.view.removeFromSuperview()
childController.removeFromParentViewController()
childController.endAppearanceTransition()
}
}
reloadViewControllers()
containerView.contentSize = CGSize(width: containerView.bounds.width * CGFloat(viewControllers.count), height: containerView.contentSize.height)
if currentIndex >= viewControllers.count {
currentIndex = viewControllers.count - 1
}
containerView.contentOffset = CGPoint(x: pageOffsetForChild(at: currentIndex), y: 0)
updateContent()
}
//MARK: - UIScrollDelegate
open func scrollViewDidScroll(_ scrollView: UIScrollView) {
if containerView == scrollView {
updateContent()
}
}
open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
if containerView == scrollView {
lastPageNumber = pageFor(contentOffset: scrollView.contentOffset.x)
lastContentOffset = scrollView.contentOffset.x
}
}
open func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
if containerView == scrollView {
pagerTabStripChildViewControllersForScrolling = nil
(navigationController?.view ?? view).isUserInteractionEnabled = true
updateContent()
}
}
//MARK: - Orientation
open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
isViewRotating = true
pageBeforeRotate = currentIndex
coordinator.animate(alongsideTransition: nil) { [weak self] _ in
guard let me = self else { return }
me.isViewRotating = false
me.currentIndex = me.pageBeforeRotate
me.updateIfNeeded()
}
}
//MARK: Private
private func progressiveIndicatorData(_ virtualPage: Int) -> (Int, Int, CGFloat) {
let count = viewControllers.count
var fromIndex = currentIndex
var toIndex = currentIndex
let direction = swipeDirection
if direction == .left {
if virtualPage > count - 1 {
fromIndex = count - 1
toIndex = count
}
else {
if self.scrollPercentage >= 0.5 {
fromIndex = max(toIndex - 1, 0)
}
else {
toIndex = fromIndex + 1
}
}
}
else if direction == .right {
if virtualPage < 0 {
fromIndex = 0
toIndex = -1
}
else {
if self.scrollPercentage > 0.5 {
fromIndex = min(toIndex + 1, count - 1)
}
else {
toIndex = fromIndex - 1
}
}
}
let scrollPercentage = pagerBehaviour.isElasticIndicatorLimit ? self.scrollPercentage : ((toIndex < 0 || toIndex >= count) ? 0.0 : self.scrollPercentage)
return (fromIndex, toIndex, scrollPercentage)
}
private func reloadViewControllers(){
guard let dataSource = datasource else {
fatalError("dataSource must not be nil")
}
viewControllers = dataSource.viewControllers(for: self)
// viewControllers
guard viewControllers.count != 0 else {
fatalError("viewControllers(for:) should provide at least one child view controller")
}
viewControllers.forEach { if !($0 is IndicatorInfoProvider) { fatalError("Every view controller provided by PagerTabStripDataSource's viewControllers(for:) method must conform to InfoProvider") }}
}
private var pagerTabStripChildViewControllersForScrolling : [UIViewController]?
private var lastPageNumber = 0
private var lastContentOffset: CGFloat = 0.0
private var pageBeforeRotate = 0
private var lastSize = CGSize(width: 0, height: 0)
internal var isViewRotating = false
internal var isViewAppearing = false
}
| bsd-3-clause | db500e360d100015f15fb1356c5207d6 | 40.644279 | 205 | 0.659399 | 5.688413 | false | false | false | false |
GreatfeatServices/gf-mobile-app | olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift | 37 | 5565 | //
// CompositeDisposable.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/20/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/// Represents a group of disposable resources that are disposed together.
public final class CompositeDisposable : DisposeBase, Disposable, Cancelable {
/// Key used to remove disposable from composite disposable
public struct DisposeKey {
fileprivate let key: BagKey
fileprivate init(key: BagKey) {
self.key = key
}
}
private var _lock = SpinLock()
// state
private var _disposables: Bag<Disposable>? = Bag()
public var isDisposed: Bool {
_lock.lock(); defer { _lock.unlock() }
return _disposables == nil
}
public override init() {
}
/// Initializes a new instance of composite disposable with the specified number of disposables.
public init(_ disposable1: Disposable, _ disposable2: Disposable) {
// This overload is here to make sure we are using optimized version up to 4 arguments.
let _ = _disposables!.insert(disposable1)
let _ = _disposables!.insert(disposable2)
}
/// Initializes a new instance of composite disposable with the specified number of disposables.
public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) {
// This overload is here to make sure we are using optimized version up to 4 arguments.
let _ = _disposables!.insert(disposable1)
let _ = _disposables!.insert(disposable2)
let _ = _disposables!.insert(disposable3)
}
/// Initializes a new instance of composite disposable with the specified number of disposables.
public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposable4: Disposable, _ disposables: Disposable...) {
// This overload is here to make sure we are using optimized version up to 4 arguments.
let _ = _disposables!.insert(disposable1)
let _ = _disposables!.insert(disposable2)
let _ = _disposables!.insert(disposable3)
let _ = _disposables!.insert(disposable4)
for disposable in disposables {
let _ = _disposables!.insert(disposable)
}
}
/// Initializes a new instance of composite disposable with the specified number of disposables.
public init(disposables: [Disposable]) {
for disposable in disposables {
let _ = _disposables!.insert(disposable)
}
}
/**
Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
- parameter disposable: Disposable to add.
- returns: Key that can be used to remove disposable from composite disposable. In case dispose bag was already
disposed `nil` will be returned.
*/
public func insert(_ disposable: Disposable) -> DisposeKey? {
let key = _insert(disposable)
if key == nil {
disposable.dispose()
}
return key
}
private func _insert(_ disposable: Disposable) -> DisposeKey? {
_lock.lock(); defer { _lock.unlock() }
let bagKey = _disposables?.insert(disposable)
return bagKey.map(DisposeKey.init)
}
/// - returns: Gets the number of disposables contained in the `CompositeDisposable`.
public var count: Int {
_lock.lock(); defer { _lock.unlock() }
return _disposables?.count ?? 0
}
/// Removes and disposes the disposable identified by `disposeKey` from the CompositeDisposable.
///
/// - parameter disposeKey: Key used to identify disposable to be removed.
public func remove(for disposeKey: DisposeKey) {
_remove(for: disposeKey)?.dispose()
}
private func _remove(for disposeKey: DisposeKey) -> Disposable? {
_lock.lock(); defer { _lock.unlock() }
return _disposables?.removeKey(disposeKey.key)
}
/// Disposes all disposables in the group and removes them from the group.
public func dispose() {
if let disposables = _dispose() {
disposeAll(in: disposables)
}
}
private func _dispose() -> Bag<Disposable>? {
_lock.lock(); defer { _lock.unlock() }
let disposeBag = _disposables
_disposables = nil
return disposeBag
}
}
extension Disposables {
/// Creates a disposable with the given disposables.
public static func create(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) -> Cancelable {
return CompositeDisposable(disposable1, disposable2, disposable3)
}
/// Creates a disposable with the given disposables.
public static func create(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposables: Disposable ...) -> Cancelable {
var disposables = disposables
disposables.append(disposable1)
disposables.append(disposable2)
disposables.append(disposable3)
return CompositeDisposable(disposables: disposables)
}
/// Creates a disposable with the given disposables.
public static func create(_ disposables: [Disposable]) -> Cancelable {
switch disposables.count {
case 2:
return Disposables.create(disposables[0], disposables[1])
default:
return CompositeDisposable(disposables: disposables)
}
}
}
| apache-2.0 | 6a391662fd3878b65bfef1974751639d | 35.366013 | 157 | 0.648095 | 4.972297 | false | false | false | false |
rdhiggins/GoogleURLShortener | GoogleURLShortener/GoogleURLShortenerViewController.swift | 1 | 5148 | //
// GoogleURLShortenerViewController.swift
// MIT License
//
// Copyright (c) 2016 Spazstik Software, 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
class GoogleURLShortenerViewController: UIViewController {
@IBOutlet weak var longURLLabel: UILabel!
@IBOutlet weak var longURLField: UITextField!
@IBOutlet weak var shortURLLabel: UILabel!
@IBOutlet weak var shortURLField: UITextField!
@IBOutlet weak var shortenURLButton: UIButton!
@IBOutlet weak var lookupURLButton: UIButton!
// Properties
var googleURL: GoogleURL? {
didSet {
longURLField.text = googleURL?.longURL
shortURLField.text = googleURL?.shortURL
updateButtonStates()
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
fileprivate func updateButtonStates() {
if let gu = googleURL {
shortenURLButton.isEnabled = gu.isLongURLValid ? true : false
lookupURLButton.isEnabled = gu.isShortURLValid ? true : false
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBAction func longURLEditingChanged(_ sender: UITextField) {
if let n = sender.text {
if googleURL == nil {
googleURL = GoogleURL(longURL: n)
} else {
googleURL?.longURL = n
}
} else {
if googleURL == nil {
googleURL = GoogleURL(longURL: "")
} else {
googleURL?.longURL = ""
}
}
updateButtonStates()
}
@IBAction func shortURLEditingChanged(_ sender: UITextField) {
if let n = sender.text {
if googleURL == nil {
googleURL = GoogleURL(shortURL: n)
} else {
googleURL?.shortURL = n
}
} else {
if googleURL == nil {
googleURL = GoogleURL(shortURL: "")
} else {
googleURL?.shortURL = ""
}
}
updateButtonStates()
}
@IBAction func shortenURLRequested(_ sender: AnyObject) {
if let lu = longURLField.text {
GoogleURLShortener.requestShorten(lu) { result in
switch result {
case let .success(googleURL):
self.googleURL = googleURL
case .failedParse:
self.showGoogleURLShortenerErrorMessage("Could not parse the response from the service!")
case let .failure(error):
self.showGoogleURLShortenerErrorMessage("WebAPI Error \(error)")
}
}
}
}
@IBAction func lookupURLRequested(_ sender: AnyObject) {
if let su = shortURLField.text {
GoogleURLShortener.requestLookup(su) { result in
switch result {
case let .success(googleURL):
self.googleURL = googleURL
case .failedParse:
self.showGoogleURLShortenerErrorMessage("Could not parse the response from the service!")
case let .failure(error):
self.showGoogleURLShortenerErrorMessage("WebAPI Error \(error)")
}
}
}
}
fileprivate func showGoogleURLShortenerErrorMessage(_ message: String) {
let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
}
| mit | 4d3ad66276684ccaafa00bed15124362 | 33.783784 | 109 | 0.616356 | 4.940499 | false | false | false | false |
zvonicek/SpriteKit-Pong | TDT4240-pong/SKTUtils/SKTAudio.swift | 15 | 2927 | /*
* Copyright (c) 2013-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 AVFoundation
/**
* Audio player that uses AVFoundation to play looping background music and
* short sound effects. For when using SKActions just isn't good enough.
*/
public class SKTAudio {
public var backgroundMusicPlayer: AVAudioPlayer?
public var soundEffectPlayer: AVAudioPlayer?
public class func sharedInstance() -> SKTAudio {
return SKTAudioInstance
}
public func playBackgroundMusic(filename: String) {
let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
if (url == nil) {
println("Could not find file: \(filename)")
return
}
var error: NSError? = nil
backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
if let player = backgroundMusicPlayer {
player.numberOfLoops = -1
player.prepareToPlay()
player.play()
} else {
println("Could not create audio player: \(error!)")
}
}
public func pauseBackgroundMusic() {
if let player = backgroundMusicPlayer {
if player.playing {
player.pause()
}
}
}
public func resumeBackgroundMusic() {
if let player = backgroundMusicPlayer {
if !player.playing {
player.play()
}
}
}
public func playSoundEffect(filename: String) {
let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
if (url == nil) {
println("Could not find file: \(filename)")
return
}
var error: NSError? = nil
soundEffectPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
if let player = soundEffectPlayer {
player.numberOfLoops = 0
player.prepareToPlay()
player.play()
} else {
println("Could not create audio player: \(error!)")
}
}
}
private let SKTAudioInstance = SKTAudio()
| mit | 1aa61dc664398042b023a7646b2ad489 | 31.522222 | 80 | 0.700034 | 4.646032 | false | false | false | false |
KeithPiTsui/Pavers | Pavers/Sources/ObjectiveKit/ObjectiveClass.swift | 2 | 2873 | //
// UnregisteredClass.swift
// ObjectiveKit
//
// Created by Roy Marmelstein on 11/11/2016.
// Copyright © 2016 Roy Marmelstein. All rights reserved.
//
import Foundation
public typealias ImplementationBlock = @convention(block) () -> Void
/// An object that allows you to introspect and modify classes through the ObjC runtime.
public class ObjectiveClass <T: NSObject>: ObjectiveKitRuntimeModification {
public var internalClass: AnyClass
// MARK: Lifecycle
/// Init
public init() {
self.internalClass = T.classForCoder()
}
// MARK: Introspection
/// Get all instance variables implemented by the class.
///
/// - Returns: An array of instance variables.
public var ivars: [String] {
get {
var count: CUnsignedInt = 0
var ivars = [String]()
let ivarList = class_copyIvarList(internalClass, &count)
for i in (0..<Int(count)) {
let unwrapped = (ivarList?[i]).unsafelyUnwrapped
if let ivar = ivar_getName(unwrapped) {
let string = String(cString: ivar)
ivars.append(string)
}
}
free(ivarList)
return ivars
}
}
/// Get all selectors implemented by the class.
///
/// - Returns: An array of selectors.
public var selectors: [Selector] {
get {
var count: CUnsignedInt = 0
var selectors = [Selector]()
let methodList = class_copyMethodList(internalClass, &count)
for i in (0..<Int(count)) {
let unwrapped = (methodList?[i]).unsafelyUnwrapped
let selector = method_getName(unwrapped)
selectors.append(selector)
}
free(methodList)
return selectors
}
}
/// Get all protocols implemented by the class.
///
/// - Returns: An array of protocol names.
public var protocols: [String] {
get {
var count: CUnsignedInt = 0
var protocols = [String]()
let protocolList = class_copyProtocolList(internalClass, &count)
for i in (0..<Int(count)) {
let unwrapped = (protocolList?[i]).unsafelyUnwrapped
let protocolName = protocol_getName(unwrapped)
let string = String(cString: protocolName)
protocols.append(string)
}
return protocols
}
}
/// Get all properties implemented by the class.
///
/// - Returns: An array of property names.
public var properties: [String] {
get {
var count: CUnsignedInt = 0
var properties = [String]()
let propertyList = class_copyPropertyList(internalClass, &count)
for i in (0..<Int(count)) {
let unwrapped = (propertyList?[i]).unsafelyUnwrapped
let propretyName = property_getName(unwrapped)
let string = String(cString: propretyName)
properties.append(string)
}
free(propertyList)
return properties
}
}
}
| mit | e5e287c9a78b78e00968f4ca790fc8d9 | 25.592593 | 88 | 0.624304 | 4.432099 | false | false | false | false |
jasnig/DouYuTVMutate | DouYuTVMutate/DouYuTV/Main/Controller/MainTabBarController.swift | 1 | 2564 | //
// MainTabBarController.swift
// DouYuTVMutate
//
// Created by ZeroJ on 16/7/13.
// Copyright © 2016年 ZeroJ. All rights reserved.
//
import UIKit
class MainTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
/// 设置子控制器
setupChildVcs()
/// 设置item的字体颜色
setTabBarItemColor()
}
func setTabBarItemColor() {
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orangeColor()], forState: .Selected)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor()], forState: .Normal)
}
func setupChildVcs() {
let homeVc = addChildVc(HomeController(), title: "首页", imageName: "btn_home_normal_24x24_", selectedImageName: "btn_home_selected_24x24_")
let liveVc = addChildVc(LiveColumnController(), title: "直播", imageName: "btn_column_normal_24x24_", selectedImageName: "btn_column_selected_24x24_")
let concernVc = addChildVc(ConcernController(), title: "关注", imageName: "btn_live_normal_30x24_", selectedImageName: "btn_live_selected_30x24_")
let profileVc = addChildVc(ProfileController(), title: "我的", imageName: "btn_user_normal_24x24_", selectedImageName: "btn_user_selected_24x24_")
viewControllers = [homeVc, liveVc, concernVc, profileVc]
}
func addChildVc(childVc: UIViewController, title: String, imageName: String, selectedImageName: String) -> UINavigationController {
let navi = MainNavigationController(rootViewController: childVc)
let image = UIImage(named: imageName)?.imageWithRenderingMode(.AlwaysOriginal)
let selectedImage = UIImage(named: selectedImageName)?.imageWithRenderingMode(.AlwaysOriginal)
let tabBarItem = UITabBarItem(title: title, image: image, selectedImage: selectedImage)
navi.tabBarItem = tabBarItem
return navi
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 3c8b500cd51d58a262d3cdc10facd3f5 | 38.984127 | 156 | 0.696308 | 4.881783 | false | false | false | false |
dreamsxin/swift | test/ClangModules/availability_implicit_macosx.swift | 2 | 4383 | // RUN: %swift -parse -verify -target x86_64-apple-macosx10.51 %clang-importer-sdk -I %S/Inputs/custom-modules %s %S/Inputs/availability_implicit_macosx_other.swift
// RUN: not %swift -parse -target x86_64-apple-macosx10.51 %clang-importer-sdk -I %S/Inputs/custom-modules %s %S/Inputs/availability_implicit_macosx_other.swift 2>&1 | FileCheck %s '--implicit-check-not=<unknown>:0'
// REQUIRES: OS=macosx
// This is a temporary test for checking of availability diagnostics (explicit unavailability,
// deprecation, and potential unavailability) in synthesized code. After this checking
// is fully staged in, the tests in this file will be moved.
//
import Foundation
func useClassThatTriggersImportOfDeprecatedEnum() {
// Check to make sure that the bodies of enum methods that are synthesized
// when importing deprecated enums do not themselves trigger deprecation
// warnings in the synthesized code.
_ = NSClassWithDeprecatedOptionsInMethodSignature.sharedInstance()
}
func useClassThatTriggersImportOExplicitlyUnavailableOptions() {
_ = NSClassWithPotentiallyUnavailableOptionsInMethodSignature.sharedInstance()
}
func useClassThatTriggersImportOfPotentiallyUnavailableOptions() {
_ = NSClassWithExplicitlyUnavailableOptionsInMethodSignature.sharedInstance()
}
func directUseShouldStillTriggerDeprecationWarning() {
_ = NSDeprecatedOptions.first // expected-warning {{'NSDeprecatedOptions' was deprecated in OS X 10.51: Use a different API}}
_ = NSDeprecatedEnum.first // expected-warning {{'NSDeprecatedEnum' was deprecated in OS X 10.51: Use a different API}}
}
func useInSignature(_ options: NSDeprecatedOptions) { // expected-warning {{'NSDeprecatedOptions' was deprecated in OS X 10.51: Use a different API}}
}
class SuperClassWithDeprecatedInitializer {
@available(OSX, introduced: 10.9, deprecated: 10.51)
init() { }
}
class SubClassWithSynthesizedDesignedInitializerOverride : SuperClassWithDeprecatedInitializer {
// The synthesized designated initializer override calls super.init(), which is
// deprecated, so the synthesized initializer is marked as deprecated as well.
// This does not generate a warning here (perhaps it should?) but any call
// to Sub's initializer will cause a deprecation warning.
}
func callImplicitInitializerOnSubClassWithSynthesizedDesignedInitializerOverride() {
_ = SubClassWithSynthesizedDesignedInitializerOverride() // expected-warning {{'init()' was deprecated in OS X 10.51}}
}
@available(OSX, introduced: 10.9, deprecated: 10.51)
class DeprecatedSuperClass {
var i : Int = 7 // Causes initializer to be synthesized
}
class NotDeprecatedSubClassOfDeprecatedSuperClass : DeprecatedSuperClass { // expected-warning {{'DeprecatedSuperClass' was deprecated in OS X 10.51}}
}
func callImplicitInitializerOnNotDeprecatedSubClassOfDeprecatedSuperClass() {
// We do not expect a warning here because the synthesized initializer
// in NotDeprecatedSubClassOfDeprecatedSuperClass is not itself marked
// deprecated.
_ = NotDeprecatedSubClassOfDeprecatedSuperClass()
}
@available(OSX, introduced: 10.9, deprecated: 10.51)
class DeprecatedSubClassOfDeprecatedSuperClass : DeprecatedSuperClass {
}
// Tests synthesis of materializeForSet
class ClassWithLimitedAvailabilityAccessors {
var limitedGetter: Int {
@available(OSX, introduced: 10.52)
get { return 10 }
set(newVal) {}
}
var limitedSetter: Int {
get { return 10 }
@available(OSX, introduced: 10.52)
set(newVal) {}
}
}
@available(*, unavailable)
func unavailableFunction() -> Int { return 10 } // expected-note 3{{'unavailableFunction()' has been explicitly marked unavailable here}}
class ClassWithReferencesLazyInitializers {
var propWithUnavailableInInitializer: Int = unavailableFunction() // expected-error {{'unavailableFunction()' is unavailable}}
lazy var lazyPropWithUnavailableInInitializer: Int = unavailableFunction() // expected-error {{'unavailableFunction()' is unavailable}}
}
@available(*, unavailable)
func unavailableUseInUnavailableFunction() {
// Diagnose references to unavailable functions in non-implicit code
// as errors
unavailableFunction() // expected-error {{'unavailableFunction()' is unavailable}} expected-warning {{result of call to 'unavailableFunction()' is unused}}
}
@available(OSX 10.52, *)
func foo() {
let _ = SubOfOtherWithInit()
}
| apache-2.0 | b20531e24a0813975976d64d3ab9bccd | 39.211009 | 215 | 0.773899 | 4.391784 | false | false | false | false |
ontouchstart/swift3-playground | Learn to Code 2.playgroundbook/Contents/Sources/_AlwaysOn.swift | 2 | 3546 | //
// _AlwaysOn.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
import PlaygroundSupport
import SceneKit
private var _isLiveViewConnectionOpen = false
extension PlaygroundPage {
var isLiveViewConnectionOpen: Bool {
return _isLiveViewConnectionOpen
}
}
extension WorldViewController: PlaygroundLiveViewMessageHandler {
// MARK: PlaygroundLiveViewMessageHandler
public func liveViewMessageConnectionOpened() {
_isLiveViewConnectionOpen = true
// Mark the scene as `ready` to receive more commands.
scene.reset(duration: WorldConfiguration.Scene.resetDuration)
}
public func receive(_ message: PlaygroundValue) {
guard case let .dictionary(dict) = message else {
log(message: "Received invalid message: \(message).")
return
}
if case let .boolean(passed)? = dict[LiveViewMessageKey.finishedSendingCommands] {
// Finished sending commands.
isPassingRun = passed
startPlayback()
}
else {
// Received commands.
let world = scene.gridWorld
let decoder = CommandDecoder(world: world)
guard let command = decoder.command(from: message) else {
log(message: "Failed to decode message: \(message).")
return
}
// Directly add the performer.
world.commandQueue.append(command)
}
}
public func liveViewMessageConnectionClosed() {
_isLiveViewConnectionOpen = false
// Stop running the command queue.
scene.commandQueue.runMode = .randomAccess
scene.state = .initial
}
}
// MARK: Send Commands
public func sendCommands(for world: GridWorld) {
let liveView = PlaygroundPage.current.liveView
guard let liveViewMessageHandler = liveView as? PlaygroundLiveViewMessageHandler else {
log(message: "Attempting to send commands, but the connection is closed.")
return
}
guard world.isAnimated else {
presentAlert(title: "Failed To Send Commands.", message: "Missing call to `finalizeWorldBuilding(for: world)` in page sources.")
return
}
// Complete the queue to ensure the last command is run.
world.commandQueue.completeCommands()
// Calculate the results before the world is reset.
let results = world.calculateResults()
let passed = results.passesCriteria
assessmentObserver?.passedCriteria = passed
// Reset the queue to reset state items like Switches, Portals, etc.
world.commandQueue.rewind()
let encoder = CommandEncoder(world: world)
for command in world.commandQueue {
let message = encoder.createMessage(from: command)
liveViewMessageHandler.send(message)
#if DEBUG
// Testing in app.
let appDelegate = (UIApplication.shared.delegate as! AppDelegate).rootVC
appDelegate?.receive(message)
#endif
}
// Mark that all the commands have been sent, and pass the result of the world.
let finished = PlaygroundValue.boolean(passed)
let finalMessage = [LiveViewMessageKey.finishedSendingCommands: finished]
liveViewMessageHandler.send(.dictionary(finalMessage))
#if DEBUG
let appDelegate = (UIApplication.shared.delegate as! AppDelegate).rootVC
appDelegate?.receive(.dictionary(finalMessage))
#endif
}
| mit | ea2432dc5c56cabfc6737d1ce509813a | 30.660714 | 136 | 0.649182 | 5.080229 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/API/Requests/Emoji/CustomEmojiRequest.swift | 1 | 946 | //
// CustomEmojiRequest.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 9/10/19.
// Copyright © 2019 Rocket.Chat. All rights reserved.
//
import Foundation
import SwiftyJSON
final class CustomEmojiRequest: APIRequest {
typealias APIResourceType = CustomEmojiResource
let requiredVersion = Version(0, 75, 0)
let path = "/api/v1/emoji-custom.list"
}
final class CustomEmojiResource: APIResource {
var customEmoji: [CustomEmoji] {
var customEmoji: [CustomEmoji] = []
let customEmojiRaw = raw?["emojis"]["update"].array
customEmojiRaw?.forEach({ customEmojiJSON in
let emoji = CustomEmoji()
emoji.map(customEmojiJSON, realm: nil)
customEmoji.append(emoji)
})
return customEmoji
}
var success: Bool {
return raw?["success"].bool ?? false
}
var errorMessage: String? {
return raw?["error"].string
}
}
| mit | acb3621e93219f25eb3601ab4c41f6e8 | 22.625 | 59 | 0.64127 | 4.090909 | false | false | false | false |
m3rkus/Mr.Weather | Mr.Weather/UIStackViewExtension.swift | 1 | 1297 | //
// UIStackViewExtension.swift
// Mr.Weather
//
// Created by Роман Анистратенко on 18/09/2017.
// Copyright © 2017 m3rk edge. All rights reserved.
//
import UIKit
extension UIStackView {
func pinBackground() {
let view = UIView()
view.backgroundColor = UIColor(red:1.00, green:1.00, blue:0.97, alpha:1.0)
view.layer.cornerRadius = 10.0
view.layer.shadowColor = UIColor.black.cgColor
view.layer.shadowOpacity = 0.3
view.layer.shadowRadius = 4.0
view.layer.shadowOffset = CGSize(width: -1, height: 1)
view.translatesAutoresizingMaskIntoConstraints = false
self.insertSubview(view, at: 0)
view.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
view.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
view.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
}
func addInternalMargins(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat) {
self.layoutMargins = UIEdgeInsets(top: top, left: left, bottom: bottom, right: right)
self.isLayoutMarginsRelativeArrangement = true
}
}
| mit | 5bf5caea504359c72b6b3eb968fe121f | 34.527778 | 93 | 0.677091 | 4.139159 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/00237-swift-declrefexpr-setspecialized.swift | 1 | 3009 | // 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
func b(c) -> <d>(() -> d) {
}
struct d<f : e, g: e where g.h == f.h> {
}
protocol e {
typealias h
}
struct c<d : Sequence> {
var b: d
}
func a<d>() -> [c<d>] {
return []
}
func i(c: () -> ()) {
}
class a {
var _ = i() {
}
}
protocol A {
typealias E
}
struct B<T : A> {
let h: T
let i: T.E
}
protocol C {
typealias F
func g<T where T.E == F>(f: B<T>)
}
struct D : C {
typealias F = Int
func g<T where T.E == F>(f: B<T>) {
}
}
protocol A {
func c() -> String
}
class B {
func d() -> String {
return ""
B) {
}
}
func ^(a: Boolean, Bool) -> Bool {
return !(a)
}
func f<T : Boolean>(b: T) {
}
f(true as Boolean)
var f = 1
var e: Int -> Int = {
return $0
}
let d: Int = { c, b in
}(f, e)
func d<b: Sequence, e where Optional<e> == b.Iterator.Element>(c : b) -> e? {
for (mx : e?) in c {
}
}
protocol a {
}
protocol b : a {
}
protocol c : a {
}
protocol d {
typealias f = a
}
struct e : d {
typealias f = b
}
func i<j : b, k : d where k.f == j> (n: k) {
}
func i<l : d where l.f == c> (n: l) {
}
i(e(ass func c()
}
class b: a {
class func c() { }
}
(b() as a).dynamicType.c()
class a<f : b, g : b where f.d == g> {
}
protocol b {
typealias d
typealias e
}
struct c<h : b> : b {
typealias d = h
typealias e = a<c<h>, d>
}
class a {
typealias b = b
}
func a(b: Int = 0) {
}
let c = a
c()
enum S<T> {
case C(T, () -> ())
}
func f() {
({})
}
enum S<T> : P {
func f<T>() -> T -> T {
return { x in x }
}
}
protocol P {
func f<T>()(T) -> T
}
protocol A {
typealias B
func b(B)
}
struct X<Y> : A {
func b(b: X.Type) {
}
}
class A<T : A> {
}
protocol a {
typealias d
typealias e = d
typealias f = d
}
class b<h : c, i : c where h.g == i> : a {
}
class b<h, i> {
}
protocol c {
typealias g
}
struct A<T> {
let a: [(T, () -> ())] = []
}
struct c<d, e: b where d.c == e> {
}
func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) {
return {
(m: (Any, Any) -> Any) -> Any in
return m(x, y)
}
}
func b(z: (((Any, Any) -> Any) -> Any)) -> Any {
return z({
(p: Any, q:Any) -> Any in
return p
})
}
b(a(1, a(2, 3)))
func a<T>() -> (T, T -> T) -> T {
var b: ((T, T -> T) -> T)!
return b
}
protocol b {
class func e()
}
struct c {
var d: b.Type
func e() {
d.e()
}
}
import Foundation
class d<c>: NSObject {
var b: c
init(b: c) {
self.b = b
}
}
func a<T>() {
enum b {
case c
}
}
protocol a : a {
}
class A : A {
}
class B : C {
}
typealias C = B
| apache-2.0 | f4c3fd1851aa6ad88e5b43196cd37e8a | 14.590674 | 79 | 0.488867 | 2.563032 | false | false | false | false |
DiegoSan1895/Smartisan-Notes | Smartisan-Notes/Async.swift | 1 | 24560 | //
// Async.swift
//
// Created by Tobias DM on 15/07/14.
//
// OS X 10.10+ and iOS 8.0+
// Only use with ARC
//
// The MIT License (MIT)
// Copyright (c) 2014 Tobias Due Munk
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Foundation
// MARK: - DSL for GCD queues
/**
`GCD` is an empty struct with convenience static functions to get `dispatch_queue_t` of different quality of service classes, as provided by `dispatch_get_global_queue`.
let utilityQueue = GCD.utilityQueue()
- SeeAlso: Grand Central Dispatch
*/
private struct GCD {
/**
Convenience function for `dispatch_get_main_queue()`.
Returns the default queue that is bound to the main thread.
- Returns: The main queue. This queue is created automatically on behalf of the main thread before main() is called.
- SeeAlso: dispatch_get_main_queue
*/
static func mainQueue() -> dispatch_queue_t {
return dispatch_get_main_queue()
// Don't ever use dispatch_get_global_queue(qos_class_main(), 0) re https://gist.github.com/duemunk/34babc7ca8150ff81844
}
/**
Convenience function for dispatch_get_global_queue, with the parameter QOS_CLASS_USER_INTERACTIVE
Returns a system-defined global concurrent queue with the specified quality of service class.
- Returns: The global concurrent queue with quality of service class QOS_CLASS_USER_INTERACTIVE.
- SeeAlso: dispatch_get_global_queue
*/
static func userInteractiveQueue() -> dispatch_queue_t {
return dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0)
}
/**
Convenience function for dispatch_get_global_queue, with the parameter QOS_CLASS_USER_INITIATED
Returns a system-defined global concurrent queue with the specified quality of service class.
- Returns: The global concurrent queue with quality of service class QOS_CLASS_USER_INITIATED.
- SeeAlso: dispatch_get_global_queue
*/
static func userInitiatedQueue() -> dispatch_queue_t {
return dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)
}
/**
Convenience function for dispatch_get_global_queue, with the parameter QOS_CLASS_UTILITY
Returns a system-defined global concurrent queue with the specified quality of service class.
- Returns: The global concurrent queue with quality of service class QOS_CLASS_UTILITY.
- SeeAlso: dispatch_get_global_queue
*/
static func utilityQueue() -> dispatch_queue_t {
return dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)
}
/**
Convenience function for dispatch_get_global_queue, with the parameter QOS_CLASS_BACKGROUND
Returns a system-defined global concurrent queue with the specified quality of service class.
- Returns: The global concurrent queue with quality of service class QOS_CLASS_BACKGROUND.
- SeeAlso: dispatch_get_global_queue
*/
static func backgroundQueue() -> dispatch_queue_t {
return dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)
}
}
// MARK: - Async – Struct
/**
The **Async** struct is the main part of the Async.framework. Handles a internally `dispatch_block_t`.
Chainable dispatch blocks with GCD:
Async.background {
// Run on background queue
}.main {
// Run on main queue, after the previous block
}
All moderns queue classes:
Async.main {}
Async.userInteractive {}
Async.userInitiated {}
Async.utility {}
Async.background {}
Custom queues:
let customQueue = dispatch_queue_create("Label",
DISPATCH_QUEUE_CONCURRENT)
Async.customQueue(customQueue) {}
Dispatch block after delay:
let seconds = 0.5
Async.main(after: seconds) {}
Cancel blocks not yet dispatched
let block1 = Async.background {
// Some work
}
let block2 = block1.background {
// Some other work
}
Async.main {
// Cancel async to allow block1 to begin
block1.cancel() // First block is NOT cancelled
block2.cancel() // Second block IS cancelled
}
Wait for block to finish:
let block = Async.background {
// Do stuff
}
// Do other stuff
// Wait for "Do stuff" to finish
block.wait()
// Do rest of stuff
- SeeAlso: Grand Central Dispatch
*/
public struct Async {
// MARK: - Private properties and init
/**
Private property to hold internally on to a `dispatch_block_t`
*/
private let block: dispatch_block_t
/**
Private init that takes a `dispatch_block_t`
*/
private init(_ block: dispatch_block_t) {
self.block = block
}
// MARK: - Static methods
/**
Sends the a block to be run asynchronously on the main thread.
- parameters:
- after: After how many seconds the block should be run.
- block: The block that is to be passed to be run on the main queue
- returns: An `Async` struct
- SeeAlso: Has parity with non-static method
*/
public static func main(after after: Double? = nil, block: dispatch_block_t) -> Async {
return Async.async(after, block: block, queue: GCD.mainQueue())
}
/**
Sends the a block to be run asynchronously on a queue with a quality of service of QOS_CLASS_USER_INTERACTIVE.
- parameters:
- after: After how many seconds the block should be run.
- block: The block that is to be passed to be run on the queue
- returns: An `Async` struct
- SeeAlso: Has parity with non-static method
*/
public static func userInteractive(after after: Double? = nil, block: dispatch_block_t) -> Async {
return Async.async(after, block: block, queue: GCD.userInteractiveQueue())
}
/**
Sends the a block to be run asynchronously on a queue with a quality of service of QOS_CLASS_USER_INITIATED.
- parameters:
- after: After how many seconds the block should be run.
- block: The block that is to be passed to be run on the queue
- returns: An `Async` struct
- SeeAlso: Has parity with non-static method
*/
public static func userInitiated(after after: Double? = nil, block: dispatch_block_t) -> Async {
return Async.async(after, block: block, queue: GCD.userInitiatedQueue())
}
/**
Sends the a block to be run asynchronously on a queue with a quality of service of QOS_CLASS_UTILITY.
- parameters:
- after: After how many seconds the block should be run.
- block: The block that is to be passed to be run on queue
- returns: An `Async` struct
- SeeAlso: Has parity with non-static method
*/
public static func utility(after after: Double? = nil, block: dispatch_block_t) -> Async {
return Async.async(after, block: block, queue: GCD.utilityQueue())
}
/**
Sends the a block to be run asynchronously on a queue with a quality of service of QOS_CLASS_BACKGROUND.
- parameters:
- after: After how many seconds the block should be run.
- block: The block that is to be passed to be run on the queue
- returns: An `Async` struct
- SeeAlso: Has parity with non-static method
*/
public static func background(after after: Double? = nil, block: dispatch_block_t) -> Async {
return Async.async(after, block: block, queue: GCD.backgroundQueue())
}
/**
Sends the a block to be run asynchronously on a custom queue.
- parameters:
- after: After how many seconds the block should be run.
- block: The block that is to be passed to be run on the queue
- returns: An `Async` struct
- SeeAlso: Has parity with non-static method
*/
public static func customQueue(queue: dispatch_queue_t, after: Double? = nil, block: dispatch_block_t) -> Async {
return Async.async(after, block: block, queue: queue)
}
// MARK: - Private static methods
/**
Convenience for `asyncNow()` or `asyncAfter()` depending on if the parameter `seconds` is passed or nil.
- parameters:
- seconds: After how many seconds the block should be run.
- block: The block that is to be passed to be run on the `queue`
- queue: The queue on which the `block` is run.
- returns: An `Async` struct which encapsulates the `dispatch_block_t`
*/
private static func async(seconds: Double? = nil, block chainingBlock: dispatch_block_t, queue: dispatch_queue_t) -> Async {
if let seconds = seconds {
return asyncAfter(seconds, block: chainingBlock, queue: queue)
}
return asyncNow(chainingBlock, queue: queue)
}
/**
Convenience for dispatch_async(). Encapsulates the block in a "true" GCD block using DISPATCH_BLOCK_INHERIT_QOS_CLASS.
- parameters:
- block: The block that is to be passed to be run on the `queue`
- queue: The queue on which the `block` is run.
- returns: An `Async` struct which encapsulates the `dispatch_block_t`
*/
private static func asyncNow(block: dispatch_block_t, queue: dispatch_queue_t) -> Async {
// Create a new block (Qos Class) from block to allow adding a notification to it later (see matching regular Async methods)
// Create block with the "inherit" type
let _block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, block)
// Add block to queue
dispatch_async(queue, _block)
// Wrap block in a struct since dispatch_block_t can't be extended
return Async(_block)
}
/**
Convenience for dispatch_after(). Encapsulates the block in a "true" GCD block using DISPATCH_BLOCK_INHERIT_QOS_CLASS.
- parameters:
- seconds: After how many seconds the block should be run.
- block: The block that is to be passed to be run on the `queue`
- queue: The queue on which the `block` is run.
- returns: An `Async` struct which encapsulates the `dispatch_block_t`
*/
private static func asyncAfter(seconds: Double, block: dispatch_block_t, queue: dispatch_queue_t) -> Async {
let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC))
let time = dispatch_time(DISPATCH_TIME_NOW, nanoSeconds)
return at(time, block: block, queue: queue)
}
/**
Convenience for dispatch_after(). Encapsulates the block in a "true" GCD block using DISPATCH_BLOCK_INHERIT_QOS_CLASS.
- parameters:
- time: The specific time (`dispatch_time_t`) the block should be run.
- block: The block that is to be passed to be run on the `queue`
- queue: The queue on which the `block` is run.
- returns: An `Async` struct which encapsulates the `dispatch_block_t`
*/
private static func at(time: dispatch_time_t, block: dispatch_block_t, queue: dispatch_queue_t) -> Async {
// See Async.async() for comments
let _block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, block)
dispatch_after(time, queue, _block)
return Async(_block)
}
// MARK: - Instance methods (matches static ones)
/**
Sends the a block to be run asynchronously on the main thread, after the current block has finished.
- parameters:
- after: After how many seconds the block should be run.
- block: The block that is to be passed to be run on the main queue
- returns: An `Async` struct
- SeeAlso: Has parity with static method
*/
public func main(after after: Double? = nil, chainingBlock: dispatch_block_t) -> Async {
return chain(after, block: chainingBlock, queue: GCD.mainQueue())
}
/**
Sends the a block to be run asynchronously on a queue with a quality of service of QOS_CLASS_USER_INTERACTIVE, after the current block has finished.
- parameters:
- after: After how many seconds the block should be run.
- block: The block that is to be passed to be run on the queue
- returns: An `Async` struct
- SeeAlso: Has parity with static method
*/
public func userInteractive(after after: Double? = nil, chainingBlock: dispatch_block_t) -> Async {
return chain(after, block: chainingBlock, queue: GCD.userInteractiveQueue())
}
/**
Sends the a block to be run asynchronously on a queue with a quality of service of QOS_CLASS_USER_INITIATED, after the current block has finished.
- parameters:
- after: After how many seconds the block should be run.
- block: The block that is to be passed to be run on the queue
- returns: An `Async` struct
- SeeAlso: Has parity with static method
*/
public func userInitiated(after after: Double? = nil, chainingBlock: dispatch_block_t) -> Async {
return chain(after, block: chainingBlock, queue: GCD.userInitiatedQueue())
}
/**
Sends the a block to be run asynchronously on a queue with a quality of service of QOS_CLASS_UTILITY, after the current block has finished.
- parameters:
- after: After how many seconds the block should be run.
- block: The block that is to be passed to be run on the queue
- returns: An `Async` struct
- SeeAlso: Has parity with static method
*/
public func utility(after after: Double? = nil, chainingBlock: dispatch_block_t) -> Async {
return chain(after, block: chainingBlock, queue: GCD.utilityQueue())
}
/**
Sends the a block to be run asynchronously on a queue with a quality of service of QOS_CLASS_BACKGROUND, after the current block has finished.
- parameters:
- after: After how many seconds the block should be run.
- block: The block that is to be passed to be run on the queue
- returns: An `Async` struct
- SeeAlso: Has parity with static method
*/
public func background(after after: Double? = nil, chainingBlock: dispatch_block_t) -> Async {
return chain(after, block: chainingBlock, queue: GCD.backgroundQueue())
}
/**
Sends the a block to be run asynchronously on a custom queue, after the current block has finished.
- parameters:
- after: After how many seconds the block should be run.
- block: The block that is to be passed to be run on the queue
- returns: An `Async` struct
- SeeAlso: Has parity with static method
*/
public func customQueue(queue: dispatch_queue_t, after: Double? = nil, chainingBlock: dispatch_block_t) -> Async {
return chain(after, block: chainingBlock, queue: queue)
}
// MARK: - Instance methods
/**
Convenience function to call `dispatch_block_cancel()` on the encapsulated block.
Cancels the current block, if it hasn't already begun running to GCD.
Usage:
let block1 = Async.background {
// Some work
}
let block2 = block1.background {
// Some other work
}
Async.main {
// Cancel async to allow block1 to begin
block1.cancel() // First block is NOT cancelled
block2.cancel() // Second block IS cancelled
}
*/
public func cancel() {
dispatch_block_cancel(block)
}
/**
Convenience function to call `dispatch_block_wait()` on the encapsulated block.
Waits for the current block to finish, on any given thread.
- parameters:
- seconds: Max seconds to wait for block to finish. If value is 0.0, it uses DISPATCH_TIME_FOREVER. Default value is 0.
- SeeAlso: dispatch_block_wait, DISPATCH_TIME_FOREVER
*/
public func wait(seconds seconds: Double = 0.0) {
if seconds != 0.0 {
let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC))
let time = dispatch_time(DISPATCH_TIME_NOW, nanoSeconds)
dispatch_block_wait(block, time)
} else {
dispatch_block_wait(block, DISPATCH_TIME_FOREVER)
}
}
// MARK: Private instance methods
/**
Convenience for `chainNow()` or `chainAfter()` depending on if the parameter `seconds` is passed or nil.
- parameters:
- seconds: After how many seconds the block should be run.
- block: The block that is to be passed to be run on the `queue`
- queue: The queue on which the `block` is run.
- returns: An `Async` struct which encapsulates the `dispatch_block_t`, which is called when the current block has finished + any given amount of seconds.
*/
private func chain(seconds: Double? = nil, block chainingBlock: dispatch_block_t, queue: dispatch_queue_t) -> Async {
if let seconds = seconds {
return chainAfter(seconds, block: chainingBlock, queue: queue)
}
return chainNow(block: chainingBlock, queue: queue)
}
/**
Convenience for `dispatch_block_notify()` to
- parameters:
- block: The block that is to be passed to be run on the `queue`
- queue: The queue on which the `block` is run.
- returns: An `Async` struct which encapsulates the `dispatch_block_t`, which is called when the current block has finished.
- SeeAlso: dispatch_block_notify, dispatch_block_create
*/
private func chainNow(block chainingBlock: dispatch_block_t, queue: dispatch_queue_t) -> Async {
// See Async.async() for comments
let _chainingBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, chainingBlock)
dispatch_block_notify(block, queue, _chainingBlock)
return Async(_chainingBlock)
}
/**
Convenience for dispatch_after(). Encapsulates the block in a "true" GCD block using DISPATCH_BLOCK_INHERIT_QOS_CLASS.
- parameters:
- seconds: After how many seconds the block should be run.
- block: The block that is to be passed to be run on the `queue`
- queue: The queue on which the `block` is run.
- returns: An `Async` struct which encapsulates the `dispatch_block_t`, which is called when the current block has finished + the given amount of seconds.
*/
private func chainAfter(seconds: Double, block chainingBlock: dispatch_block_t, queue: dispatch_queue_t) -> Async {
// Create a new block (Qos Class) from block to allow adding a notification to it later (see Async)
// Create block with the "inherit" type
let _chainingBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, chainingBlock)
// Wrap block to be called when previous block is finished
let chainingWrapperBlock: dispatch_block_t = {
// Calculate time from now
let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC))
let time = dispatch_time(DISPATCH_TIME_NOW, nanoSeconds)
dispatch_after(time, queue, _chainingBlock)
}
// Create a new block (Qos Class) from block to allow adding a notification to it later (see Async)
// Create block with the "inherit" type
let _chainingWrapperBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, chainingWrapperBlock)
// Add block to queue *after* previous block is finished
dispatch_block_notify(self.block, queue, _chainingWrapperBlock)
// Wrap block in a struct since dispatch_block_t can't be extended
return Async(_chainingBlock)
}
}
// MARK: - Apply - DSL for `dispatch_apply`
/**
`Apply` is an empty struct with convenience static functions to parallelize a for-loop, as provided by `dispatch_apply`.
Apply.background(100) { i in
// Calls blocks in parallel
}
`Apply` runs a block multiple times, before returning. If you want run the block asynchronously from the current thread, wrap it in an `Async` block:
Async.background {
Apply.background(100) { i in
// Calls blocks in parallel asynchronously
}
}
- SeeAlso: Grand Central Dispatch, dispatch_apply
*/
public struct Apply {
/**
Block is run any given amount of times on a queue with a quality of service of QOS_CLASS_USER_INTERACTIVE. The block is being passed an index parameter.
- parameters:
- iterations: How many times the block should be run. Index provided to block goes from `0..<iterations`
- block: The block that is to be passed to be run on a .
*/
public static func userInteractive(iterations: Int, block: Int -> ()) {
dispatch_apply(iterations, GCD.userInteractiveQueue(), block)
}
/**
Block is run any given amount of times on a queue with a quality of service of QOS_CLASS_USER_INITIATED. The block is being passed an index parameter.
- parameters:
- iterations: How many times the block should be run. Index provided to block goes from `0..<iterations`
- block: The block that is to be passed to be run on a .
*/
public static func userInitiated(iterations: Int, block: Int -> ()) {
dispatch_apply(iterations, GCD.userInitiatedQueue(), block)
}
/**
Block is run any given amount of times on a queue with a quality of service of QOS_CLASS_UTILITY. The block is being passed an index parameter.
- parameters:
- iterations: How many times the block should be run. Index provided to block goes from `0..<iterations`
- block: The block that is to be passed to be run on a .
*/
public static func utility(iterations: Int, block: Int -> ()) {
dispatch_apply(iterations, GCD.utilityQueue(), block)
}
/**
Block is run any given amount of times on a queue with a quality of service of QOS_CLASS_BACKGROUND. The block is being passed an index parameter.
- parameters:
- iterations: How many times the block should be run. Index provided to block goes from `0..<iterations`
- block: The block that is to be passed to be run on a .
*/
public static func background(iterations: Int, block: Int -> ()) {
dispatch_apply(iterations, GCD.backgroundQueue(), block)
}
/**
Block is run any given amount of times on a custom queue. The block is being passed an index parameter.
- parameters:
- iterations: How many times the block should be run. Index provided to block goes from `0..<iterations`
- block: The block that is to be passed to be run on a .
*/
public static func customQueue(iterations: Int, queue: dispatch_queue_t, block: Int -> ()) {
dispatch_apply(iterations, queue, block)
}
}
// MARK: - Extension for `qos_class_t`
/**
Extension to add description string for each quality of service class.
*/
public extension qos_class_t {
/**
Description of the `qos_class_t`. E.g. "Main", "User Interactive", etc. for the given Quality of Service class.
*/
var description: String {
get {
switch self {
case qos_class_main(): return "Main"
case QOS_CLASS_USER_INTERACTIVE: return "User Interactive"
case QOS_CLASS_USER_INITIATED: return "User Initiated"
case QOS_CLASS_DEFAULT: return "Default"
case QOS_CLASS_UTILITY: return "Utility"
case QOS_CLASS_BACKGROUND: return "Background"
case QOS_CLASS_UNSPECIFIED: return "Unspecified"
default: return "Unknown"
}
}
}
}
| mit | 0b53884b038c95b009cd650b08fbaa32 | 36.265554 | 169 | 0.657871 | 4.347318 | false | false | false | false |
webim/webim-client-sdk-ios | Example/WebimClientLibrary/Extensions/String.swift | 1 | 6237 | //
// String.swift
// WebimClientLibrary_Example
//
// Created by Nikita Lazarev-Zubov on 24.01.18.
// Copyright © 2018 Webim. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import UIKit
import CommonCrypto
extension String {
func MD5() -> String? {
let length = Int(CC_MD5_DIGEST_LENGTH)
var digest = [UInt8](repeating: 0, count: length)
if let d = self.data(using: String.Encoding.utf8) {
_ = d.withUnsafeBytes { (body: UnsafePointer<UInt8>) in
CC_MD5(body, CC_LONG(d.count), &digest)
}
}
return (0..<length).reduce("") {
$0 + String(format: "%02x", digest[$1])
}
}
// MARK: - Properties
var localized: String {
return NSLocalizedString(self, comment: "")
}
func nsRange(from range: Range<String.Index>) -> NSRange {
let from = range.lowerBound.samePosition(in: utf16)
let to = range.upperBound.samePosition(in: utf16)
return NSRange(location: utf16.distance(from: utf16.startIndex, to: from!),
length: utf16.distance(from: from!, to: to!))
}
func substring(_ nsrange: NSRange) -> Substring? {
guard let range = Range(nsrange, in: self) else { return nil }
return self[range]
}
func addHttpsPrefix() -> String {
if self.lowercased().hasPrefix("https://") || self.lowercased().hasPrefix("http://") {
return self
}
return "https://" + self
}
static func unwarpOrEmpty(_ str: String?) -> String {
if let str = str {
return str
}
return ""
}
}
// MARK: -
extension String {
// MARK: - Methods
public func decodePercentEscapedLinksIfPresent() -> String {
var convertedString = String()
let checkingTypes: NSTextCheckingResult.CheckingType = [.link]
if let linksDetector = try? NSDataDetector(types: checkingTypes.rawValue) {
// swiftlint:disable legacy_constructor
let linkMatches = linksDetector.matches(in: self,
range: NSMakeRange(0,
self.count))
// swiftlint:enable legacy_constructor
if !linkMatches.isEmpty {
var position = 0
for linkMatch in linkMatches {
let linkMatchRange = linkMatch.range
if let url = linkMatch.url {
let beforeLinkStringSliceRangeStart = self.index(self.startIndex,
offsetBy: position)
let beforeLinkStringSliceRangeEnd = self.index(self.startIndex,
offsetBy: linkMatchRange.location)
let beforeLinkStringSlice = String(self[beforeLinkStringSliceRangeStart ..< beforeLinkStringSliceRangeEnd])
convertedString += beforeLinkStringSlice
position = linkMatchRange.location + linkMatchRange.length
let urlString = url.absoluteString.removingPercentEncoding
if let urlString = urlString {
convertedString += urlString
} else {
let linkStringSliceRangeStart = self.index(self.startIndex,
offsetBy: linkMatchRange.location)
let linkStringSliceRangeEnd = self.index(self.startIndex,
offsetBy: linkMatchRange.length)
convertedString += String(self[linkStringSliceRangeStart ..< linkStringSliceRangeEnd])
}
}
}
let closingStringSliceRangeStart = self.index(self.startIndex,
offsetBy: position)
let closingStringSliceRangeEnd = self.index(self.startIndex,
offsetBy: self.count)
let closingStringSlice = String(self[closingStringSliceRangeStart ..< closingStringSliceRangeEnd])
convertedString += closingStringSlice
} else {
return self
}
}
return convertedString
}
public func trimWhitespacesIn() -> String {
let components = self.components(separatedBy: .whitespaces)
return components.filter { !$0.isEmpty }.joined(separator: " ")
}
public func validateURLString() -> Bool {
for char in self {
if char.isWhitespace || !char.isASCII {
return false
}
}
return NSURL(string: self) != nil
}
}
| mit | 1ba2ac42180e63d3fd64b028f7a59f21 | 40.298013 | 131 | 0.547466 | 5.284746 | false | false | false | false |
nicolastinkl/CardDeepLink | CardDeepLinkKit/CardDeepLinkKit/UIGitKit/Alamofire/Manager.swift | 1 | 34179 | // Manager.swift
//
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`.
*/
internal class Manager {
// MARK: - Properties
/**
A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly
for any ad hoc requests.
*/
internal static let sharedInstance: Manager = {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
return Manager(configuration: configuration)
}()
/**
Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers.
*/
internal static let defaultHTTPHeaders: [String: String] = {
// Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3
let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5"
// Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5
let acceptLanguage = NSLocale.preferredLanguages().prefix(6).enumerate().map { index, languageCode in
let quality = 1.0 - (Double(index) * 0.1)
return "\(languageCode);q=\(quality)"
}.joinWithSeparator(", ")
// User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3
let userAgent: String = {
if let info = NSBundle.mainBundle().infoDictionary {
let executable: AnyObject = info[kCFBundleExecutableKey as String] ?? "Unknown"
let bundle: AnyObject = info[kCFBundleIdentifierKey as String] ?? "Unknown"
let version: AnyObject = info[kCFBundleVersionKey as String] ?? "Unknown"
let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown"
var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString
let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
if CFStringTransform(mutableUserAgent, UnsafeMutablePointer<CFRange>(nil), transform, false) {
return mutableUserAgent as String
}
}
return "Alamofire"
}()
return [
"Accept-Encoding": acceptEncoding,
"Accept-Language": acceptLanguage,
"User-Agent": userAgent
]
}()
let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)
/// The underlying session.
internal let session: NSURLSession
/// The session delegate handling all the task and session delegate callbacks.
internal let delegate: SessionDelegate
/// Whether to start requests immediately after being constructed. `true` by default.
internal var startRequestsImmediately: Bool = true
/**
The background completion handler closure provided by the UIApplicationDelegate
`application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background
completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation
will automatically call the handler.
If you need to handle your own events before the handler is called, then you need to override the
SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished.
`nil` by default.
*/
internal var backgroundCompletionHandler: (() -> Void)?
// MARK: - Lifecycle
/**
Initializes the `Manager` instance with the specified configuration, delegate and server trust policy.
- parameter configuration: The configuration used to construct the managed session.
`NSURLSessionConfiguration.defaultSessionConfiguration()` by default.
- parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by
default.
- parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
challenges. `nil` by default.
- returns: The new `Manager` instance.
*/
internal init(
configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate: SessionDelegate = SessionDelegate(),
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
self.delegate = delegate
self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
/**
Initializes the `Manager` instance with the specified session, delegate and server trust policy.
- parameter session: The URL session.
- parameter delegate: The delegate of the URL session. Must equal the URL session's delegate.
- parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
challenges. `nil` by default.
- returns: The new `Manager` instance if the URL session's delegate matches the delegate parameter.
*/
internal init?(
session: NSURLSession,
delegate: SessionDelegate,
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
self.delegate = delegate
self.session = session
guard delegate === session.delegate else { return nil }
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
private func commonInit(serverTrustPolicyManager serverTrustPolicyManager: ServerTrustPolicyManager?) {
session.serverTrustPolicyManager = serverTrustPolicyManager
delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in
guard let strongSelf = self else { return }
dispatch_async(dispatch_get_main_queue()) { strongSelf.backgroundCompletionHandler?() }
}
}
deinit {
session.invalidateAndCancel()
}
// MARK: - Request
/**
Creates a request for the specified method, URL string, parameters, parameter encoding and headers.
- parameter method: The HTTP method.
- parameter URLString: The URL string.
- parameter parameters: The parameters. `nil` by default.
- parameter encoding: The parameter encoding. `.URL` by default.
- parameter headers: The HTTP headers. `nil` by default.
- returns: The created request.
*/
func request(
method: Method,
_ URLString: URLStringConvertible,
parameters: [String: AnyObject]? = nil,
encoding: ParameterEncoding = .URL,
headers: [String: String]? = nil)
-> Request
{
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0
return request(encodedURLRequest)
}
/**
Creates a request for the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter URLRequest: The URL request
- returns: The created request.
*/
func request(URLRequest: URLRequestConvertible) -> Request {
var dataTask: NSURLSessionDataTask!
dispatch_sync(queue) { dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest) }
let request = Request(session: session, task: dataTask)
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
// MARK: - SessionDelegate
/**
Responsible for handling all delegate callbacks for the underlying session.
*/
internal final class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
private var subdelegates: [Int: Request.TaskDelegate] = [:]
private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
get {
var subdelegate: Request.TaskDelegate?
dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] }
return subdelegate
}
set {
dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue }
}
}
/**
Initializes the `SessionDelegate` instance.
- returns: The new `SessionDelegate` instance.
*/
internal override init() {
super.init()
}
// MARK: - NSURLSessionDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didBecomeInvalidWithError:`.
internal var sessionDidBecomeInvalidWithError: ((NSURLSession, NSError?) -> Void)?
/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`.
internal var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
/// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`.
internal var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)?
// MARK: Delegate Methods
/**
Tells the delegate that the session has been invalidated.
- parameter session: The session object that was invalidated.
- parameter error: The error that caused invalidation, or nil if the invalidation was explicit.
*/
internal func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
sessionDidBecomeInvalidWithError?(session, error)
}
/**
Requests credentials from the delegate in response to a session-level authentication request from the remote server.
- parameter session: The session containing the task that requested authentication.
- parameter challenge: An object that contains the request for authentication.
- parameter completionHandler: A handler that your delegate method must call providing the disposition and credential.
*/
internal func URLSession(
session: NSURLSession,
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
{
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
if let sessionDidReceiveChallenge = sessionDidReceiveChallenge {
(disposition, credential) = sessionDidReceiveChallenge(session, challenge)
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let host = challenge.protectionSpace.host
if let
serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host),
serverTrust = challenge.protectionSpace.serverTrust
{
if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) {
disposition = .UseCredential
credential = NSURLCredential(forTrust: serverTrust)
} else {
disposition = .CancelAuthenticationChallenge
}
}
}
completionHandler(disposition, credential)
}
/**
Tells the delegate that all messages enqueued for a session have been delivered.
- parameter session: The session that no longer has any outstanding requests.
*/
internal func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
sessionDidFinishEventsForBackgroundURLSession?(session)
}
// MARK: - NSURLSessionTaskDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`.
internal var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`.
internal var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`.
internal var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream!)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
internal var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didCompleteWithError:`.
internal var taskDidComplete: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)?
// MARK: Delegate Methods
/**
Tells the delegate that the remote server requested an HTTP redirect.
- parameter session: The session containing the task whose request resulted in a redirect.
- parameter task: The task whose request resulted in a redirect.
- parameter response: An object containing the server’s response to the original request.
- parameter request: A URL request object filled out with the new location.
- parameter completionHandler: A closure that your handler should call with either the value of the request
parameter, a modified URL request object, or NULL to refuse the redirect and
return the body of the redirect response.
*/
internal func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
willPerformHTTPRedirection response: NSHTTPURLResponse,
newRequest request: NSURLRequest,
completionHandler: ((NSURLRequest?) -> Void))
{
var redirectRequest: NSURLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
}
completionHandler(redirectRequest)
}
/**
Requests credentials from the delegate in response to an authentication request from the remote server.
- parameter session: The session containing the task whose request requires authentication.
- parameter task: The task whose request requires authentication.
- parameter challenge: An object that contains the request for authentication.
- parameter completionHandler: A handler that your delegate method must call providing the disposition and credential.
*/
internal func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
{
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
completionHandler(taskDidReceiveChallenge(session, task, challenge))
} else if let delegate = self[task] {
delegate.URLSession(
session,
task: task,
didReceiveChallenge: challenge,
completionHandler: completionHandler
)
} else {
URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler)
}
}
/**
Tells the delegate when a task requires a new request body stream to send to the remote server.
- parameter session: The session containing the task that needs a new body stream.
- parameter task: The task that needs a new body stream.
- parameter completionHandler: A completion handler that your delegate method should call with the new body stream.
*/
internal func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
needNewBodyStream completionHandler: ((NSInputStream?) -> Void))
{
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
completionHandler(taskNeedNewBodyStream(session, task))
} else if let delegate = self[task] {
delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
}
}
/**
Periodically informs the delegate of the progress of sending body content to the server.
- parameter session: The session containing the data task.
- parameter task: The data task.
- parameter bytesSent: The number of bytes sent since the last time this delegate method was called.
- parameter totalBytesSent: The total number of bytes sent so far.
- parameter totalBytesExpectedToSend: The expected length of the body data.
*/
internal func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64)
{
if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else if let delegate = self[task] as? Request.UploadTaskDelegate {
delegate.URLSession(
session,
task: task,
didSendBodyData: bytesSent,
totalBytesSent: totalBytesSent,
totalBytesExpectedToSend: totalBytesExpectedToSend
)
}
}
/**
Tells the delegate that the task finished transferring data.
- parameter session: The session containing the task whose request finished transferring data.
- parameter task: The task whose request finished transferring data.
- parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil.
*/
internal func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if let taskDidComplete = taskDidComplete {
taskDidComplete(session, task, error)
} else if let delegate = self[task] {
delegate.URLSession(session, task: task, didCompleteWithError: error)
}
self[task] = nil
}
// MARK: - NSURLSessionDataDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
internal var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`.
internal var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveData:`.
internal var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`.
internal var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse!)?
// MARK: Delegate Methods
/**
Tells the delegate that the data task received the initial reply (headers) from the server.
- parameter session: The session containing the data task that received an initial reply.
- parameter dataTask: The data task that received an initial reply.
- parameter response: A URL response object populated with headers.
- parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a
constant to indicate whether the transfer should continue as a data task or
should become a download task.
*/
internal func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
didReceiveResponse response: NSURLResponse,
completionHandler: ((NSURLSessionResponseDisposition) -> Void))
{
var disposition: NSURLSessionResponseDisposition = .Allow
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
}
completionHandler(disposition)
}
/**
Tells the delegate that the data task was changed to a download task.
- parameter session: The session containing the task that was replaced by a download task.
- parameter dataTask: The data task that was replaced by a download task.
- parameter downloadTask: The new download task that replaced the data task.
*/
internal func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask)
{
if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask {
dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask)
} else {
let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask)
self[downloadTask] = downloadDelegate
}
}
/**
Tells the delegate that the data task has received some of the expected data.
- parameter session: The session containing the data task that provided data.
- parameter dataTask: The data task that provided data.
- parameter data: A data object containing the transferred data.
*/
internal func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
}
}
/**
Asks the delegate whether the data (or upload) task should store the response in the cache.
- parameter session: The session containing the data (or upload) task.
- parameter dataTask: The data (or upload) task.
- parameter proposedResponse: The default caching behavior. This behavior is determined based on the current
caching policy and the values of certain received headers, such as the Pragma
and Cache-Control headers.
- parameter completionHandler: A block that your handler must call, providing either the original proposed
response, a modified version of that response, or NULL to prevent caching the
response. If your delegate implements this method, it must call this completion
handler; otherwise, your app leaks memory.
*/
internal func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
willCacheResponse proposedResponse: NSCachedURLResponse,
completionHandler: ((NSCachedURLResponse?) -> Void))
{
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse))
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
delegate.URLSession(
session,
dataTask: dataTask,
willCacheResponse: proposedResponse,
completionHandler: completionHandler
)
} else {
completionHandler(proposedResponse)
}
}
// MARK: - NSURLSessionDownloadDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didFinishDownloadingToURL:`.
internal var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> Void)?
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`.
internal var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`.
internal var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)?
// MARK: Delegate Methods
/**
Tells the delegate that a download task has finished downloading.
- parameter session: The session containing the download task that finished.
- parameter downloadTask: The download task that finished.
- parameter location: A file URL for the temporary file. Because the file is temporary, you must either
open the file for reading or move it to a permanent location in your app’s sandbox
container directory before returning from this delegate method.
*/
internal func URLSession(
session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didFinishDownloadingToURL location: NSURL)
{
if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL {
downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location)
}
}
/**
Periodically informs the delegate about the download’s progress.
- parameter session: The session containing the download task.
- parameter downloadTask: The download task.
- parameter bytesWritten: The number of bytes transferred since the last time this delegate
method was called.
- parameter totalBytesWritten: The total number of bytes transferred so far.
- parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length
header. If this header was not provided, the value is
`NSURLSessionTransferSizeUnknown`.
*/
internal func URLSession(
session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64)
{
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(
session,
downloadTask: downloadTask,
didWriteData: bytesWritten,
totalBytesWritten: totalBytesWritten,
totalBytesExpectedToWrite: totalBytesExpectedToWrite
)
}
}
/**
Tells the delegate that the download task has resumed downloading.
- parameter session: The session containing the download task that finished.
- parameter downloadTask: The download task that resumed. See explanation in the discussion.
- parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the
existing content, then this value is zero. Otherwise, this value is an
integer representing the number of bytes on disk that do not need to be
retrieved again.
- parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header.
If this header was not provided, the value is NSURLSessionTransferSizeUnknown.
*/
internal func URLSession(
session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64)
{
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(
session,
downloadTask: downloadTask,
didResumeAtOffset: fileOffset,
expectedTotalBytes: expectedTotalBytes
)
}
}
// MARK: - NSURLSessionStreamDelegate
var _streamTaskReadClosed: Any?
var _streamTaskWriteClosed: Any?
var _streamTaskBetterRouteDiscovered: Any?
var _streamTaskDidBecomeInputStream: Any?
// MARK: - NSObject
internal override func respondsToSelector(selector: Selector) -> Bool {
switch selector {
case "URLSession:didBecomeInvalidWithError:":
return sessionDidBecomeInvalidWithError != nil
case "URLSession:didReceiveChallenge:completionHandler:":
return sessionDidReceiveChallenge != nil
case "URLSessionDidFinishEventsForBackgroundURLSession:":
return sessionDidFinishEventsForBackgroundURLSession != nil
case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:":
return taskWillPerformHTTPRedirection != nil
case "URLSession:dataTask:didReceiveResponse:completionHandler:":
return dataTaskDidReceiveResponse != nil
default:
return self.dynamicType.instancesRespondToSelector(selector)
}
}
}
}
| bsd-2-clause | c612e378b5a34f55b61cc5106851af98 | 48.308802 | 171 | 0.645255 | 6.676631 | false | false | false | false |
khizkhiz/swift | test/decl/class/override.swift | 2 | 16493 | // RUN: %target-parse-verify-swift -parse-as-library
class A {
func ret_sametype() -> Int { return 0 }
func ret_subclass() -> A { return self }
func ret_subclass_rev() -> B { return B() }
func ret_nonclass_optional() -> Int? { return .none }
func ret_nonclass_optional_rev() -> Int { return 0 }
func ret_class_optional() -> B? { return .none }
func ret_class_optional_rev() -> A { return self }
func ret_class_uoptional() -> B! { return B() }
func ret_class_uoptional_rev() -> A { return self }
func ret_class_optional_uoptional() -> B? { return .none }
func ret_class_optional_uoptional_rev() -> A! { return self }
func param_sametype(x : Int) {}
func param_subclass(x : B) {}
func param_subclass_rev(x : A) {}
func param_nonclass_optional(x : Int) {}
func param_nonclass_optional_rev(x : Int?) {}
func param_class_optional(x : B) {}
func param_class_optional_rev(x : B?) {}
func param_class_uoptional(x : B) {}
func param_class_uoptional_rev(x : B!) {}
func param_class_optional_uoptional(x : B!) {}
func param_class_optional_uoptional_rev(x : B?) {}
}
class B : A {
override func ret_sametype() -> Int { return 1 }
override func ret_subclass() -> B { return self }
func ret_subclass_rev() -> A { return self }
override func ret_nonclass_optional() -> Int { return 0 }
func ret_nonclass_optional_rev() -> Int? { return 0 }
override func ret_class_optional() -> B { return self }
func ret_class_optional_rev() -> A? { return self }
override func ret_class_uoptional() -> B { return self }
func ret_class_uoptional_rev() -> A! { return self }
override func ret_class_optional_uoptional() -> B! { return self }
override func ret_class_optional_uoptional_rev() -> A? { return self }
override func param_sametype(x : Int) {}
override func param_subclass(x : A) {}
func param_subclass_rev(x : B) {}
override func param_nonclass_optional(x : Int?) {}
func param_nonclass_optional_rev(x : Int) {}
override func param_class_optional(x : B?) {}
func param_class_optional_rev(x : B) {}
override func param_class_uoptional(x : B!) {}
func param_class_uoptional_rev(x : B) {}
override func param_class_optional_uoptional(x : B?) {}
override func param_class_optional_uoptional_rev(x : B!) {}
}
class C<T> {
func ret_T() -> T {}
}
class D<T> : C<[T]> {
override func ret_T() -> [T] {}
}
class E {
var var_sametype: Int { get { return 0 } set {} }
var var_subclass: E { get { return self } set {} } // expected-note{{attempt to override property here}}
var var_subclass_rev: F { get { return F() } set {} } // expected-note{{attempt to override property here}}
var var_nonclass_optional: Int? { get { return .none } set {} } // expected-note{{attempt to override property here}}
var var_nonclass_optional_rev: Int { get { return 0 } set {} } // expected-note{{attempt to override property here}}
var var_class_optional: F? { get { return .none } set {} } // expected-note{{attempt to override property here}}
var var_class_optional_rev: E { get { return self } set {} } // expected-note{{attempt to override property here}}
var var_class_uoptional: F! { get { return F() } set {} } // expected-note{{attempt to override property here}}
var var_class_uoptional_rev: E { get { return self } set {} } // expected-note{{attempt to override property here}}
var var_class_optional_uoptional: F? { get { return .none } set {} }
var var_class_optional_uoptional_rev: E! { get { return self } set {} }
var ro_sametype: Int { return 0 }
var ro_subclass: E { return self }
var ro_subclass_rev: F { return F() }
var ro_nonclass_optional: Int? { return 0 }
var ro_nonclass_optional_rev: Int { return 0 } // expected-note{{attempt to override property here}}
var ro_class_optional: F? { return .none }
var ro_class_optional_rev: E { return self } // expected-note{{attempt to override property here}}
var ro_class_uoptional: F! { return F() }
var ro_class_uoptional_rev: E { return self } // expected-note{{attempt to override property here}}
var ro_class_optional_uoptional: F? { return .none }
var ro_class_optional_uoptional_rev: E! { return self }
}
class F : E {
override var var_sametype: Int { get { return 0 } set {} }
override var var_subclass: F { get { return self } set {} } // expected-error{{cannot override mutable property 'var_subclass' of type 'E' with covariant type 'F'}}
override var var_subclass_rev: E { get { return F() } set {} } // expected-error{{property 'var_subclass_rev' with type 'E' cannot override a property with type 'F}}
override var var_nonclass_optional: Int { get { return 0 } set {} } // expected-error{{cannot override mutable property 'var_nonclass_optional' of type 'Int?' with covariant type 'Int'}}
override var var_nonclass_optional_rev: Int? { get { return 0 } set {} } // expected-error{{property 'var_nonclass_optional_rev' with type 'Int?' cannot override a property with type 'Int'}}
override var var_class_optional: F { get { return self } set {} } // expected-error{{cannot override mutable property 'var_class_optional' of type 'F?' with covariant type 'F'}}
override var var_class_optional_rev: E? { get { return self } set {} } // expected-error{{property 'var_class_optional_rev' with type 'E?' cannot override a property with type 'E'}}
override var var_class_uoptional: F { get { return F() } set {} } // expected-error{{cannot override mutable property 'var_class_uoptional' of type 'F!' with covariant type 'F'}}
override var var_class_uoptional_rev: E! { get { return self } set {} } // expected-error{{property 'var_class_uoptional_rev' with type 'E!' cannot override a property with type 'E'}}
override var var_class_optional_uoptional: F! { get { return .none } set {} }
override var var_class_optional_uoptional_rev: E? { get { return self } set {} }
override var ro_sametype: Int { return 0 }
override var ro_subclass: E { return self }
override var ro_subclass_rev: F { return F() }
override var ro_nonclass_optional: Int { return 0 }
override var ro_nonclass_optional_rev: Int? { return 0 } // expected-error{{property 'ro_nonclass_optional_rev' with type 'Int?' cannot override a property with type 'Int'}}
override var ro_class_optional: F { return self }
override var ro_class_optional_rev: E? { return self } // expected-error{{property 'ro_class_optional_rev' with type 'E?' cannot override a property with type 'E'}}
override var ro_class_uoptional: F { return F() }
override var ro_class_uoptional_rev: E! { return self } // expected-error{{property 'ro_class_uoptional_rev' with type 'E!' cannot override a property with type 'E'}}
override var ro_class_optional_uoptional: F! { return .none }
override var ro_class_optional_uoptional_rev: E? { return self }
}
class G {
func f1(_: Int, int: Int) { }
func f2(_: Int, int: Int) { }
func f3(_: Int, int: Int) { }
func f4(_: Int, int: Int) { }
func f5(_: Int, int: Int) { }
func f6(_: Int, int: Int) { }
func f7(_: Int, int: Int) { }
func g1(_: Int, string: String) { } // expected-note{{potential overridden method 'g1(_:string:)' here}} {{28-28=string }}
func g1(_: Int, path: String) { } // expected-note{{potential overridden method 'g1(_:path:)' here}} {{28-28=path }}
}
class H : G {
override func f1(_: Int, _: Int) { } // expected-error{{argument names for method 'f1' do not match those of overridden method 'f1(_:int:)'}}{{28-28=int }}
override func f2(_: Int, value: Int) { } // expected-error{{argument names for method 'f2(_:value:)' do not match those of overridden method 'f2(_:int:)'}}{{28-28=int }}
override func f3(_: Int, value int: Int) { } // expected-error{{argument names for method 'f3(_:value:)' do not match those of overridden method 'f3(_:int:)'}}{{28-34=}}
override func f4(_: Int, _ int: Int) { } // expected-error{{argument names for method 'f4' do not match those of overridden method 'f4(_:int:)'}}{{28-30=}}
override func f5(_: Int, value inValue: Int) { } // expected-error{{argument names for method 'f5(_:value:)' do not match those of overridden method 'f5(_:int:)'}}{{28-33=int}}
override func f6(_: Int, _ inValue: Int) { } // expected-error{{argument names for method 'f6' do not match those of overridden method 'f6(_:int:)'}}{{28-29=int}}
override func f7(_: Int, int value: Int) { } // okay
override func g1(_: Int, s: String) { } // expected-error{{declaration 'g1(_:s:)' has different argument names from any potential overrides}}
}
@objc class IUOTestBaseClass {
func none() {}
func oneA(_: AnyObject) {}
func oneB(x x: AnyObject) {}
func oneC(var x x: AnyObject) {} // expected-error {{parameters may not have the 'var' specifier}} expected-warning {{parameter 'x' was never mutated; consider changing to 'let' constant}}
func oneD(x: AnyObject) {}
func manyA(_: AnyObject, _: AnyObject) {}
func manyB(a: AnyObject, b: AnyObject) {}
func manyC(var a: AnyObject, // expected-error {{parameters may not have the 'var' specifier}} expected-warning {{parameter 'a' was never mutated; consider changing to 'let' constant}}
var b: AnyObject) {} // expected-error {{parameters may not have the 'var' specifier}} expected-warning {{parameter 'b' was never mutated; consider changing to 'let' constant}}
func result() -> AnyObject? { return nil }
func both(x: AnyObject) -> AnyObject? { return x }
init(_: AnyObject) {}
init(one: AnyObject) {}
init(a: AnyObject, b: AnyObject) {}
}
class IUOTestSubclass : IUOTestBaseClass {
override func oneA(_: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}}
override func oneB(x x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{36-37=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{27-27=(}} {{37-37=)}}
override func oneC(var x x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} expected-warning {{parameter 'x' was never mutated; consider changing to 'let' constant}} expected-error {{parameters may not have the 'var' specifier}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{40-41=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{31-31=(}} {{41-41=)}}
override func oneD(x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}}
override func manyA(_: AnyObject!, _: AnyObject!) {} // expected-warning 2 {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 2 {{remove '!' to make the parameter required}}
// expected-note@-2 2 {{add parentheses to silence this warning}}
override func manyB(a: AnyObject!, b: AnyObject!) {} // expected-warning 2 {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 2 {{remove '!' to make the parameter required}}
// expected-note@-2 2 {{add parentheses to silence this warning}}
override func manyC(var a: AnyObject!, var b: AnyObject!) {} // expected-warning 2 {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} expected-warning {{parameter 'a' was never mutated; consider changing to 'let' constant}} expected-warning {{parameter 'b' was never mutated; consider changing to 'let' constant}} expected-error {{parameters may not have the 'var' specifier}} expected-error {{parameters may not have the 'var' specifier}}
// expected-note@-1 2 {{remove '!' to make the parameter required}}
// expected-note@-2 2 {{add parentheses to silence this warning}}
override func result() -> AnyObject! { return nil } // expected-warning {{overriding instance method optional result type 'AnyObject?' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 {{use '?' to make the result optional}} {{38-39=?}}
// expected-note@-2 {{add parentheses to silence this warning}} {{29-29=(}} {{39-39=)}}
override func both(x: AnyObject!) -> AnyObject! { return x } // expected-warning {{overriding instance method optional result type 'AnyObject?' with implicitly unwrapped optional type 'AnyObject!'}} expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 {{use '?' to make the result optional}} {{49-50=?}} expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}}
// expected-note@-2 2 {{add parentheses to silence this warning}}
override init(_: AnyObject!) {} // expected-warning {{overriding initializer parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{29-30=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{20-20=(}} {{30-30=)}}
override init(one: AnyObject!) {} // expected-warning {{overriding initializer parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{31-32=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{22-22=(}} {{32-32=)}}
override init(a: AnyObject!, b: AnyObject!) {} // expected-warning 2 {{overriding initializer parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 2 {{remove '!' to make the parameter required}}
// expected-note@-2 2 {{add parentheses to silence this warning}}
}
class IUOTestSubclass2 : IUOTestBaseClass {
override func oneA(x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}}
override func oneB(var x x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} expected-warning {{parameter 'x' was never mutated; consider changing to 'let' constant}} expected-error {{parameters may not have the 'var' specifier}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{40-41=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{31-31=(}} {{41-41=)}}
override func oneD(_: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}}
// expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}}
// expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}}
override func oneC(x x: ImplicitlyUnwrappedOptional<AnyObject>) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'ImplicitlyUnwrappedOptional<AnyObject>'}}
// expected-note@-1 {{add parentheses to silence this warning}} {{27-27=(}} {{65-65=)}}
}
class IUOTestSubclassOkay : IUOTestBaseClass {
override func oneA(_: AnyObject?) {}
override func oneB(x x: (AnyObject!)) {}
override func oneC(x x: AnyObject) {}
override func result() -> (AnyObject!) { return nil }
}
class GenericBase<T> {}
class ConcreteDerived: GenericBase<Int> {}
class OverriddenWithConcreteDerived<T> {
func foo() -> GenericBase<T> {}
}
class OverridesWithMismatchedConcreteDerived<T>:
OverriddenWithConcreteDerived<T> {
override func foo() -> ConcreteDerived {} //expected-error{{does not override}}
}
class OverridesWithConcreteDerived:
OverriddenWithConcreteDerived<Int> {
override func foo() -> ConcreteDerived {}
}
| apache-2.0 | 1459e7237c58129afaf70cfdfc81560b | 67.435685 | 504 | 0.684775 | 3.875235 | false | false | false | false |
SoCM/iOS-FastTrack-2014-2015 | 03-Single View App/Swift 3/Playgrounds/Variables/Variables.playground/Pages/Topic 2 - Types are Objects.xcplaygroundpage/Contents.swift | 3 | 1688 | //: [Previous](@previous)
import UIKit
//: ### TOPIC 2: Types are Objects
let p : Double = 10.1234567890123
//: Try uncommenting this line
//var fVal : Float = p
/*:
You cannot simply equate variables of different types. The next line creates a new Float with `p` passed to it's constructor.
(Yes, all datatypes are objects and they have constructors!)
*/
var fVal : Float = Float(p) //This will create a float (and loose precision of course)
var iVal : Int = Int(floor(p + 0.5)) //This performs a round then a conversion
/*:
Note how data types are objects. Don't worry about this having any impact on the perforamance of compiled code.
You can trust the compiler to optimise this.
It's not just constructors. There are properties as well. Some properties are backed by storage. Others might be computed at run time.
For a simple string representation, you can use the *computed property* description:
*/
let strNum = "The number is " + p.description + "."
print(" \(strNum)")
//: This one is useful. String has an initialiser that takes a C-like format string
var strNumber = String(format: "%4.1f", p);
print("The number rounded down is \(strNumber)")
/*:
You can even add your own functions using Swift "extensions" (getting ahead of myself here).
As everything is an object, then with Swift we can extend it!
Constant `p` is of type `Double` (a struct) - we can extend the object Double to include a new method
*/
extension Double {
func asSinglePrecisionString() -> String {
let strOfNumber = String(format: "%4.1f", self)
return strOfNumber
}
}
//: Now apply this function
let strOfP = p.asSinglePrecisionString()
//: [Next](@next)
| mit | cf48c8883058c8835847d9a3cc8f5191 | 30.849057 | 134 | 0.712678 | 3.810384 | false | false | false | false |
dsoisson/SwiftLearningExercises | Exercise14-JSON.playground/Sources/New File.swift | 1 | 950 | import Foundation
import Foundation
public protocol Container {
associatedtype ItemType
func addItem(item: ItemType)
func removeItem(item: ItemType) -> ItemType?
var count: Int { get }
subscript(i: Int) -> ItemType { get }
}
public class Database<Element: Equatable> {
public typealias ItemType = Element
public var items: [ItemType]
public init() {
items = [ItemType]()
}
}
extension Database: Container {
public func addItem(item: ItemType) {
items.append(item)
}
public func removeItem(item: ItemType) -> ItemType? {
let index = items.indexOf { $0 == item }
if index != nil {
return items.removeAtIndex(index!)
}
return nil
}
public var count: Int {
return items.count
}
public subscript(i: Int) -> ItemType {
return items[i]
}
}
| mit | c3821676fdb5c3a9e5f958bebe71978c | 17.627451 | 57 | 0.565263 | 4.634146 | false | false | false | false |
GMSLabs/Hyber-SDK-iOS | Example/Hyber/Notification.swift | 1 | 961 | //
// Notification.swift
// Hyber
//
// Created by Taras Markevych on 3/23/17.
// Copyright © 2017 Incuube. All rights reserved.
//
import UIKit
//
import UIKit
internal let UILayoutPriorityNotificationPadding: Float = 999
internal struct NotificationName {
static let titleFont = UIFont.boldSystemFont(ofSize: 14)
static let subtitleFont = UIFont.systemFont(ofSize: 13)
static let animationDuration: TimeInterval = 0.3 // second(s)
static let exhibitionDuration: TimeInterval = 5.0 // second(s)
}
internal struct NotificationLayout {
static let height: CGFloat = 64.0
static var width: CGFloat { return UIScreen.main.bounds.size.width }
static var labelMessageHeight: CGFloat = 35
static var dragViewHeight: CGFloat = 3
static let iconSize = CGSize(width: 36, height: 36)
static let labelPadding: CGFloat = 45
static let accessoryViewTrailing: CGFloat = 15
}
| apache-2.0 | 89cca74f21b94ebfb2d41c4a6d76a98b | 21.857143 | 72 | 0.69375 | 4.304933 | false | false | false | false |
CalebeEmerick/Checkout | Source/Checkout/DatePicker.swift | 1 | 767 | //
// DatePicker.swift
// Checkout
//
// Created by Calebe Emerick on 08/12/16.
// Copyright © 2016 CalebeEmerick. All rights reserved.
//
import UIKit
final class DatePicker : UIView {
@IBOutlet fileprivate weak var picker: UIPickerView!
fileprivate let dataSource = DatePickerDataSource()
let delegate = DatePickerDelegate()
// var valityDate: ((ValityDate) -> Void)?
}
extension DatePicker {
override func awakeFromNib() {
super.awakeFromNib()
// delegate.selectedValityDate = { [weak self] valityDate in }
picker.dataSource = dataSource
picker.delegate = delegate
picker.selectRow(5, inComponent: 0, animated: true)
picker.selectRow(5, inComponent: 1, animated: true)
}
}
| mit | 2b1ce32885fe7d1b1b1edb9721381dac | 23.709677 | 70 | 0.667102 | 4.185792 | false | false | false | false |
tluquet3/MonTennis | MonTennis/Simulation/SimulationTableViewController.swift | 1 | 11206 | //
// SimulationTableViewController.swift
// MonTennis
//
// Created by Thomas Luquet on 02/06/2015.
// Copyright (c) 2015 Thomas Luquet. All rights reserved.
//
import UIKit
class SimulationTableViewController: UITableViewController {
private var newClassement : Classement!
private var classementSup : Classement!
private var strTestPass : String!
private var barCtrl : TabBarController!
private var score1 : Int!
private var score2 : Int!
private var maxVictoires: Int!
private var nbVictoiresPrises : Int!
private var VE2I5G : Int!
override func viewDidLoad() {
super.viewDidLoad()
self.barCtrl = self.tabBarController as! TabBarController
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
newClassement = barCtrl.user.calculerClassement()
classementSup = Classement(value: self.newClassement.value + 1)
maxVictoires = barCtrl.user.calcNbVPrisesEnCompte(newClassement)
score1 = barCtrl.user.calcBilanA(newClassement,nbVictoiresPrises: maxVictoires)
score2 = barCtrl.user.calcBilanA(classementSup,nbVictoiresPrises:barCtrl.user.calcNbVPrisesEnCompte(classementSup))
nbVictoiresPrises = min(maxVictoires, barCtrl.user.getNbVictoires()-barCtrl.user.getNbVictoiresWO())
VE2I5G = barCtrl.user.calcVE2I5G(newClassement)
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func imgForFutur()->UIImage? {
let img: UIImage?
if(newClassement.value>self.barCtrl.user.classement.value){
img = UIImage(named: "UpArrow")
}else if(newClassement.value<self.barCtrl.user.classement.value){
img = UIImage(named: "DownArrow")
}else{
img = UIImage(named: "EqualSign")
}
return img
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 4
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
let result:Int
if(section == 0){
result = 1
}else if(section == 1){
result = 4 + self.barCtrl.user.getNbMalus(newClassement)
}
else if(section == 2){
result = nbVictoiresPrises
}
else if(section == 3){
result = 4
}
else{
result = 0
}
return result
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if(indexPath.section == 0){
let cell = tableView.dequeueReusableCellWithIdentifier("futurClassementCell", forIndexPath: indexPath) as! FuturClassementCell
cell.futurClassement.text = newClassement.string
cell.bilan1Label.text = "Bilan à " + newClassement.string + ":"
cell.bilan2Label.text = "Bilan à " + classementSup.string + ":"
cell.score1.text = String(score1) + "/" + String(barCtrl.user.norme[newClassement.value].0) + " pts"
cell.score2.text = String(score2) + "/" + String(barCtrl.user.norme[classementSup.value].0) + " pts"
cell.progress1.progress = min(Float(score1)/Float(barCtrl.user.norme[newClassement.value].0),1.0)
cell.progress2.progress = min(Float(score2)/Float(barCtrl.user.norme[classementSup.value].0),1.0)
cell.imgView.image = self.imgForFutur()
return cell
}
else if(indexPath.section == 1){
let cell = tableView.dequeueReusableCellWithIdentifier("detailCalculCell", forIndexPath: indexPath) as! DetailCalculCell
cell.option.text = ""
switch indexPath.row{
case 0:
cell.titre.text = "Bilan total:"
cell.resultat.text = String(score1) + " pts"
case 1:
cell.titre.text = "Victoires:"
cell.option.text = "Max: " + String(self.maxVictoires) + " prises en compte"
cell.resultat.text = String(barCtrl.user.calcGainVictoires(newClassement, nbVictoires: maxVictoires)) + " pts"
case 2:
cell.titre.text = "Bonus:"
cell.option.text = "Championnat"
cell.resultat.text = String(barCtrl.user.calculerBonusChampionnat()) + " pts"
case 3:
cell.titre.text = "Bonus:"
cell.option.text = "Pas de défaites significatives"
cell.resultat.text = String(barCtrl.user.calculerBonusAbsenceDefaitesSign(newClassement.value)) + " pts"
case 4:
cell.titre.text = "Malus:"
if(barCtrl.user.getNbWO()>=5){
cell.option.text = "Nb defaites par W0 supérieur à 5"
}else{
cell.option.text = "V-E-2I-5G < -100"
}
if(barCtrl.user.getNbMalus(newClassement) == 1){
cell.resultat.text = Classement(value: newClassement.value+1).string + "->" + newClassement.string
}else{
cell.resultat.text = Classement(value: newClassement.value+2).string + "->" + Classement(value: newClassement.value+1).string
}
case 5:
cell.titre.text = "Malus:"
cell.option.text = "V-E-2I-5G < -100"
cell.resultat.text = Classement(value: newClassement.value+1).string + "->" + newClassement.string
default:
cell.textLabel?.text = ""
}
return cell
}
else if(indexPath.section == 2){
let cell = tableView.dequeueReusableCellWithIdentifier("detailCalculCell", forIndexPath: indexPath) as! DetailCalculCell
let victoire = barCtrl.user.victoires[indexPath.row]
cell.titre.text = victoire.lastName + " " + victoire.firstName
cell.option.text = victoire.classement.string
cell.resultat.text = String(barCtrl.user.calcGainMatch(newClassement, victoire: victoire)) + " pts"
return cell
}
else if(indexPath.section == 3){
let cell = tableView.dequeueReusableCellWithIdentifier("detailCalculCell", forIndexPath: indexPath) as! DetailCalculCell
switch indexPath.row{
case 0:
cell.titre.text = "Nb Victoires de base:"
cell.option.text = "A " + newClassement.string
cell.resultat.text = String(barCtrl.user.norme[newClassement.value].1)
case 1:
cell.titre.text = "V-E-2I-5G:"
cell.resultat.text = String(VE2I5G)
let V = barCtrl.user.getNbVictoires()
let E = barCtrl.user.getNbDefaitesA(newClassement.value)
let I = barCtrl.user.getNbDefaitesA(newClassement.value-1)
let G = barCtrl.user.getNbDefaitesInfA(newClassement.value-2)
cell.option.text = "V="+String(V)+", E="+String(E)+", I="+String(I)+", G="+String(G)
case 2:
cell.titre.text = "Victoires Supp"
cell.option.text = ""
let supp = barCtrl.user.getVfromVE2I5G(newClassement, VE2I5G: VE2I5G)
var sign = "+"
if(supp<0){
sign = ""
}
cell.resultat.text = sign+String(supp)
case 3:
cell.titre.text = "Total:"
cell.option.text = "Max Victoires Prises En Compte"
cell.resultat.text = String(maxVictoires)
default:
cell.titre.text = ""
cell.resultat.text = ""
cell.option.text = ""
}
return cell
}
else{
let cell = tableView.dequeueReusableCellWithIdentifier("detailCalculCell", forIndexPath: indexPath) as! DetailCalculCell
return cell
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if(indexPath.section == 0){
return 150
}
else{
return 44
}
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
var title = ""
if(section == 0){
title = "Bilan"
}
else if(section == 1){
title = "Détail"
}
else if( section == 2){
title = "Victoires Prises en Compte (" + String(self.nbVictoiresPrises) + ")"
}
else if(section == 3){
title = "Détail Victoires Prises en Compte"
}
return title
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | dd9feecc81e9aba99c747969b23fa202 | 41.101504 | 157 | 0.604518 | 4.149315 | false | false | false | false |
xmartlabs/XLForm | Examples/Swift/SwiftExample/DynamicSelector/UsersTableViewController.swift | 1 | 7917 | //
// UsersTableViewController.swift
// XLForm ( https://github.com/xmartlabs/XLForm )
//
// Copyright (c) 2014-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.
class UserCell : UITableViewCell {
lazy var userImage : UIImageView = {
let tempUserImage = UIImageView()
tempUserImage.translatesAutoresizingMaskIntoConstraints = false
tempUserImage.layer.masksToBounds = true
tempUserImage.layer.cornerRadius = 10.0
return tempUserImage
}()
lazy var userName : UILabel = {
let tempUserName = UILabel()
tempUserName.translatesAutoresizingMaskIntoConstraints = false
tempUserName.font = UIFont.systemFont(ofSize: 15.0)
return tempUserName
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// Initialization code
contentView.addSubview(userImage)
contentView.addSubview(userName)
contentView.addConstraints(layoutConstraints())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
// MARK: - Layout Constraints
func layoutConstraints() -> [NSLayoutConstraint]{
let views = ["image": self.userImage, "name": self.userName ] as [String : Any]
let metrics = [ "imgSize": 50.0, "margin": 12.0]
var result = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(margin)-[image(imgSize)]-[name]", options:.alignAllTop, metrics: metrics, views: views)
result += NSLayoutConstraint.constraints(withVisualFormat: "V:|-(margin)-[image(imgSize)]", options:NSLayoutConstraint.FormatOptions(), metrics:metrics, views: views)
return result
}
}
private let _UsersJSONSerializationSharedInstance = UsersJSONSerialization()
class UsersJSONSerialization {
lazy var userData : Array<AnyObject>? = {
let dataString =
"[" +
"{\"id\":1,\"name\":\"Apu Nahasapeemapetilon\",\"imageName\":\"Apu_Nahasapeemapetilon.png\"}," +
"{\"id\":7,\"name\":\"Bart Simpsons\",\"imageName\":\"Bart_Simpsons.png\"}," +
"{\"id\":8,\"name\":\"Homer Simpsons\",\"imageName\":\"Homer_Simpsons.png\"}," +
"{\"id\":9,\"name\":\"Lisa Simpsons\",\"imageName\":\"Lisa_Simpsons.png\"}," +
"{\"id\":2,\"name\":\"Maggie Simpsons\",\"imageName\":\"Maggie_Simpsons.png\"}," +
"{\"id\":3,\"name\":\"Marge Simpsons\",\"imageName\":\"Marge_Simpsons.png\"}," +
"{\"id\":4,\"name\":\"Montgomery Burns\",\"imageName\":\"Montgomery_Burns.png\"}," +
"{\"id\":5,\"name\":\"Ned Flanders\",\"imageName\":\"Ned_Flanders.png\"}," +
"{\"id\":6,\"name\":\"Otto Mann\",\"imageName\":\"Otto_Mann.png\"}]"
let jsonData = dataString.data(using: String.Encoding.utf8, allowLossyConversion: true)
do {
let result = try JSONSerialization.jsonObject(with: jsonData!, options: JSONSerialization.ReadingOptions()) as! Array<AnyObject>
return result
}
catch let error as NSError {
print("\(error)")
}
return nil
}()
class var sharedInstance: UsersJSONSerialization {
return _UsersJSONSerializationSharedInstance
}
}
class User: NSObject, XLFormOptionObject {
let userId: Int
let userName : String
let userImage: String
init(userId: Int, userName: String, userImage: String){
self.userId = userId
self.userImage = userImage
self.userName = userName
}
func formDisplayText() -> String {
return self.userName
}
func formValue() -> Any {
return self.userId as Any
}
}
class UsersTableViewController : UITableViewController, XLFormRowDescriptorViewController {
var rowDescriptor : XLFormRowDescriptor?
var userCell : UserCell?
fileprivate let kUserCellIdentifier = "UserCell"
override init(style: UITableView.Style) {
super.init(style: style);
}
override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: Bundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UserCell.self, forCellReuseIdentifier: kUserCellIdentifier)
tableView.tableFooterView = UIView(frame: CGRect.zero)
}
// MARK: UITableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return UsersJSONSerialization.sharedInstance.userData!.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UserCell = tableView.dequeueReusableCell(withIdentifier: self.kUserCellIdentifier, for: indexPath) as! UserCell
let usersData = UsersJSONSerialization.sharedInstance.userData! as! Array<Dictionary<String, AnyObject>>
let userData = usersData[(indexPath as NSIndexPath).row] as Dictionary<String, AnyObject>
let userId = userData["id"] as! Int
cell.userName.text = userData["name"] as? String
cell.userImage.image = UIImage(named: (userData["imageName"] as? String)!)
if let value = rowDescriptor?.value {
cell.accessoryType = ((value as? XLFormOptionObject)?.formValue() as? Int) == userId ? .checkmark : .none
}
return cell;
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 73.0
}
//MARK: UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let usersData = UsersJSONSerialization.sharedInstance.userData! as! Array<Dictionary<String, AnyObject>>
let userData = usersData[(indexPath as NSIndexPath).row] as Dictionary<String, AnyObject>
let user = User(userId: (userData["id"] as! Int), userName: userData["name"] as! String, userImage: userData["imageName"] as! String)
self.rowDescriptor!.value = user;
if let popOver = self.presentedViewController, popOver.modalPresentationStyle == .popover {
dismiss(animated: true, completion: nil)
}
else if parent is UINavigationController {
navigationController?.popViewController(animated: true)
}
}
}
| mit | 89563c669ca961dc508712480e281e53 | 37.432039 | 174 | 0.661741 | 4.795276 | false | false | false | false |
sugar2010/arcgis-runtime-samples-ios | ClosestFacilitySample/swift/ClosestFacility/Controllers/ClosestFacilityViewController.swift | 4 | 21993 | //
// Copyright 2014 ESRI
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// You may freely redistribute and use this sample code, with or
// without modification, provided you include the original copyright
// notice and use restrictions.
//
// See the use restrictions at http://help.arcgis.com/en/sdk/10.0/usageRestrictions.htm
//
//
import UIKit
import ArcGIS
let kBaseMap = "http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer"
let kFacilitiesLayerURL = "http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Louisville/LOJIC_PublicSafety_Louisville/MapServer/1"
let kCFTask = "http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Network/USA/NAServer/Closest%20Facility"
let kSettingsSegueName = "SettingsSegue"
class ClosestFacilityViewController: UIViewController, AGSMapViewLayerDelegate, AGSMapViewTouchDelegate, AGSCalloutDelegate, AGSClosestFacilityTaskDelegate {
@IBOutlet weak var mapView:AGSMapView!
@IBOutlet weak var statusMessageLabel:UILabel!
@IBOutlet weak var addButton:UIBarButtonItem!
@IBOutlet weak var clearSketchButton:UIBarButtonItem!
@IBOutlet weak var findCFButton:UIBarButtonItem!
@IBOutlet weak var sketchModeSegCtrl:UISegmentedControl!
var facilitiesLayer:AGSFeatureLayer!
var sketchLayer:AGSSketchGraphicsLayer!
var selectedGraphic:AGSGraphic!
var graphicsLayer:AGSGraphicsLayer!
var cfTask:AGSClosestFacilityTask!
var cfOp:NSOperation!
var settingsViewController:SettingsViewController!
var numIncidents:Int = 0
var numBarriers:Int = 0
var deleteCalloutView:UIView!
var parameters:Parameters!
override func prefersStatusBarHidden() -> Bool {
return false
}
override func viewDidLoad() {
super.viewDidLoad()
//Add the basemap - the tiled layer
let mapUrl = NSURL(string: kBaseMap)
let tiledLyr = AGSTiledMapServiceLayer(URL: mapUrl)
self.mapView.addMapLayer(tiledLyr, withName:"Tiled Layer")
//Zooming to an initial envelope with the specified spatial reference of the map.
let sr = AGSSpatialReference(WKID: 102100)
let env = AGSEnvelope(xmin: -9555545.779983964, ymin:4593330.340739982, xmax:-9531085.930932742, ymax:4628491.373751115,
spatialReference:sr)
self.mapView.zoomToEnvelope(env, animated:true)
//important step in detecting the touch events on the map
self.mapView.touchDelegate = self
//step to call the mapViewDidLoad method to do the initiation of Closest Facility Task.
self.mapView.layerDelegate = self
//add graphics layer for showing results of the closest facility analysis
self.graphicsLayer = AGSGraphicsLayer()
self.mapView.addMapLayer(self.graphicsLayer, withName:"ClosestFacility")
// set the callout delegate so we can display callouts
// updated the callout to the map instead of the layer.
self.mapView.callout.delegate = self
//creating the facilities (fire stations) layer
self.facilitiesLayer = AGSFeatureLayer(URL: NSURL(string: kFacilitiesLayerURL), mode: .Snapshot)
//specifying the symbol for the fire stations.
let renderer = AGSSimpleRenderer(symbol: AGSPictureMarkerSymbol(imageNamed: "FireStation"))
self.facilitiesLayer.renderer = renderer
self.facilitiesLayer.outFields = ["*"]
//adding the fire stations feature layer to the map view.
self.mapView.addMapLayer(self.facilitiesLayer, withName:"Facilities")
// // add sketch layer to the map
// let mp = AGSMutablePoint(spatialReference: AGSSpatialReference.webMercatorSpatialReference())
// self.sketchLayer = AGSSketchGraphicsLayer(geometry: mp)
// self.mapView.addMapLayer(self.sketchLayer, withName:"sketchLayer")
//
// //Register for "Geometry Changed" notifications
// //We want to enable/disable UI elements when sketch geometry is modified
// NSNotificationCenter.defaultCenter().addObserver(self, selector: "respondToGeomChanged:", name: AGSSketchGraphicsLayerGeometryDidChangeNotification, object: nil)
//
//// // set the mapView's touchDelegate to the sketchLayer so we get points symbolized when sketching
// self.mapView.touchDelegate = self.sketchLayer
// create a custom callout view using a button with an image
// this is to remove incidents and barriers after we add them to the map
let customView = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 24))
let deleteBtn = UIButton.buttonWithType(.Custom) as! UIButton
deleteBtn.frame = CGRect(x: 8, y: 0, width: 24, height: 24)
deleteBtn.setImage(UIImage(named: "remove24.png"), forState:.Normal)
deleteBtn.addTarget(self, action: "removeIncidentBarrierClicked", forControlEvents: .TouchUpInside)
customView.addSubview(deleteBtn)
self.deleteCalloutView = customView
//instantiate the parameters object
self.parameters = Parameters()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - AGSMapViewLayerDelegate
func mapViewDidLoad(mapView: AGSMapView!) {
// add sketch layer to the map
let mp = AGSMutablePoint(spatialReference: AGSSpatialReference.webMercatorSpatialReference())
self.sketchLayer = AGSSketchGraphicsLayer(geometry: mp)
self.mapView.addMapLayer(self.sketchLayer, withName:"sketchLayer")
//Register for "Geometry Changed" notifications
//We want to enable/disable UI elements when sketch geometry is modified
NSNotificationCenter.defaultCenter().addObserver(self, selector: "respondToGeomChanged:", name: AGSSketchGraphicsLayerGeometryDidChangeNotification, object: nil)
//set the mapView's touchDelegate to the sketchLayer so we get points symbolized when sketching
self.mapView.touchDelegate = self.sketchLayer
//set up the cf task
self.cfTask = AGSClosestFacilityTask(URL: NSURL(string: kCFTask))
self.cfTask.delegate = self //required to respond to the cf task.
}
//MARK: - AGSCalloutDelegate
func callout(callout: AGSCallout!, willShowForFeature feature: AGSFeature!, layer: AGSLayer!, mapPoint: AGSPoint!) -> Bool {
let graphic = feature as! AGSGraphic
let incidentNum = graphic.attributeAsStringForKey("incidentNumber")
let barrierNum = graphic.attributeAsStringForKey("barrierNumber")
self.selectedGraphic = graphic
if self.sketchLayer != nil {
self.sketchLayer.clear()
}
if incidentNum != nil || barrierNum != nil {
self.mapView.callout.customView = self.deleteCalloutView
return true
}
else{
return false
}
}
//MARK: - AGSClosestFacilityTaskDelegate
//if the solveClosestFacilityWithResult operation completed successfully
func closestFacilityTask(closestFacilityTask: AGSClosestFacilityTask!, operation op: NSOperation!, didSolveClosestFacilityWithResult closestFacilityTaskResult: AGSClosestFacilityTaskResult!) {
//remove previous graphics from the graphics layer
//if "barrierNumber" exists in the attributes, we know it is a barrier graphic
//if "incidentNumber" exists in the attributes, we know it is an incident graphic
//so leave that graphic and go to the next one
//careful not to attempt to mutate the graphics array while
//it is being enumerated
let graphics = self.graphicsLayer.graphics
for g in graphics as! [AGSGraphic] {
if !(g.attributeAsStringForKey("barrierNumber") == nil ||
g.attributeAsStringForKey("incidentNumber") == nil) {
self.graphicsLayer.removeGraphic(g)
}
}
//iterate through the closest facility results array in the closestFacilityTaskResult returned by the task
for cfResult in closestFacilityTaskResult.closestFacilityResults as! [AGSClosestFacilityResult] {
//symbolize the returned route graphic
cfResult.routeGraphic.symbol = self.routeSymbol()
//add the route graphic to the graphics layer
self.graphicsLayer.addGraphic(cfResult.routeGraphic)
}
//stop activity indicator
// SVProgressHUD.dismiss()
//changing the status message label.
self.statusMessageLabel.text = "Tap reset to start over"
//zoom to graphics layer extent
var env = self.graphicsLayer.fullEnvelope as! AGSMutableEnvelope
env.expandByFactor(1.2)
self.mapView.zoomToEnvelope(env, animated:true)
}
//if error encountered while executing cf task
func closestFacilityTask(closestFacilityTask: AGSClosestFacilityTask!, operation op: NSOperation!, didFailSolveWithError error: NSError!) {
//stop activity indicator
// SVProgressHUD.dismiss()
//show error message
UIAlertView(title: "Error", message: error.localizedDescription, delegate: nil, cancelButtonTitle: "Ok").show()
}
func closestFacilityTask(closestFacilityTask: AGSClosestFacilityTask!, operation op: NSOperation!, didRetrieveDefaultClosestFacilityTaskParameters closestFacilityParams: AGSClosestFacilityTaskParameters!) {
//specify some custom parameters
//Number of facilities to be returned
closestFacilityParams.defaultTargetFacilityCount = self.parameters.facilityCount
//The kind of the cuttoff attribute - Time, Length etc. We are using Time
closestFacilityParams.impedanceAttributeName = "Time"
//Specify the cuttoff travelling time to the facility. In minutes.
closestFacilityParams.defaultCutoffValue = self.parameters.cutoffTime
//Specify the travel direction.
closestFacilityParams.travelDirection = AGSNATravelDirection.FromFacility
//specifying the spatial reference output
closestFacilityParams.outSpatialReference = self.mapView.spatialReference
//setting the incidents for the CF task. We have only one here - the tapped location.
var incidents = [AGSGraphic]()
var polygonBarriers = [AGSGraphic]()
// get the incidents, barriers for the cf task
for g in self.graphicsLayer.graphics as! [AGSGraphic] {
// if it's a incident graphic, add the object to incidents
if g.attributeAsStringForKey("incidentNumber") != nil {
incidents.append(g)
}
// if "barrierNumber" exists in the attributes, we know it is a barrier
// so add the object to our barriers
else if g.attributeAsStringForKey("barrierNumber") != nil {
polygonBarriers.append(g)
}
}
// set the incidents and polygon barriers on the parameters object
if incidents.count > 0 {
closestFacilityParams.setIncidentsWithFeatures(incidents)
}
if polygonBarriers.count > 0 {
closestFacilityParams.setPolygonBarriersWithFeatures(polygonBarriers)
}
//specify the features that need to be used as the facilities. We use the fire stations layer features.
closestFacilityParams.setFacilitiesWithFeatures(self.facilitiesLayer.graphics)
//calls the solveClosestFacilityWithParameters with modified params.
self.cfOp = self.cfTask.solveClosestFacilityWithParameters(closestFacilityParams)
}
func closestFacilityTask(closestFacilityTask: AGSClosestFacilityTask!, operation op: NSOperation!, didFailToRetrieveDefaultClosestFacilityTaskParametersWithError error: NSError!) {
//stop activity indicator
// SVProgressHUD.dismiss()
UIAlertView(title: "Error", message: error.localizedDescription, delegate: nil, cancelButtonTitle: "OK")
}
//MARK: - Action Methods
// reset button clicked
@IBAction func resetBtnClicked(sender:AnyObject) {
self.reset()
}
//
// add a incident or barrier depending on the sketch layer's current geometry
//
@IBAction func addIncidentOrBarrier(sender:AnyObject) {
//grab the geometry, then clear the sketch
let geometry : AGSGeometry = self.sketchLayer.geometry.copy() as! AGSGeometry
self.sketchLayer.clear()
//Prepare symbol and attributes for the Incident/Barrier
var attributes = [String:AnyObject]()
var symbol:AGSSymbol!
var g:AGSGraphic!
switch (AGSGeometryTypeForGeometry(geometry)) {
//Incident
case .Point:
self.numIncidents++
//ading an attribute for the incident graphic
attributes["incidentNumber"] = self.numIncidents
//getting the symbol for the incident graphic
symbol = self.incidentSymbol()
g = AGSGraphic(geometry: geometry, symbol: symbol, attributes: attributes)
//You can set additional properties on the incident here
self.graphicsLayer.addGraphic(g)
//enable the findFCButton
self.findCFButton.enabled = true
//Barrier
case .Polygon:
self.numBarriers++
attributes["barrierNumber"] = self.numBarriers
//getting the symbol for the incident graphic
symbol = self.barrierSymbol()
g = AGSGraphic(geometry: geometry, symbol: symbol, attributes: attributes)
self.graphicsLayer.addGraphic(g)
default:
break
}
}
//
// if our segment control was changed, then the sketch layer geometry needs to
// be updated to reflect that (point for incidents and polygon for barriers)
//
@IBAction func incidentsBarriersValChanged(segCtrl:UISegmentedControl) {
if self.sketchLayer == nil {
return
}
switch (segCtrl.selectedSegmentIndex) {
case 0:
self.sketchLayer.clear()
//geometry for sketching incident points
self.sketchLayer.geometry = AGSMutablePoint(spatialReference: self.mapView.spatialReference)
case 1:
self.sketchLayer.clear()
//geometry for sketching barrier polygons
self.sketchLayer.geometry = AGSMutablePolygon(spatialReference: self.mapView.spatialReference)
default:
break
}
}
// perform the cf task's retrieve default parameters operation
@IBAction func findCFButtonClicked(sender:AnyObject) {
// update the status message
self.statusMessageLabel.text = "Finding closest facilities"
// if we have a sketch layer on the map, remove it
if self.sketchLayer != nil {
if contains(self.mapView.mapLayers as! [AGSLayer], self.sketchLayer) {
self.mapView.removeMapLayerWithName(self.sketchLayer.name)
self.mapView.touchDelegate = nil
self.sketchLayer = nil
//also disable the sketch control so that user cannot sketch
self.sketchModeSegCtrl.selectedSegmentIndex = -1
for (var i = 0 ; i < self.sketchModeSegCtrl.numberOfSegments; i++) {
self.sketchModeSegCtrl.setEnabled(false, forSegmentAtIndex: i)
}
}
}
//retrieves the default parameters for the closest facility task from the server
//the caOp property will keep tract of the operation in case we need to cancel it at any point.
self.cfOp = self.cfTask.retrieveDefaultClosestFacilityTaskParameters()
// SVProgressHUD.showWithStatus("Search for closest facilities")
}
// clear the sketch layer
@IBAction func clearSketchLayer(sender:AnyObject) {
self.sketchLayer.clear()
}
@IBAction func resetButttonClicked(sender:AnyObject) {
self.reset()
}
//MARK: - Helper Methods
func respondToGeomChanged(notification:NSNotification) {
//Enable/disable UI elements appropriately
self.addButton.enabled = self.sketchLayer.geometry.isValid()
self.clearSketchButton.enabled = !self.sketchLayer.geometry.isEmpty()
}
// reset the sample so we can perform another analysis
func reset() {
// set incident counter back to 0
self.numIncidents = 0
// set barrier counter back to 0
self.numBarriers = 0
// remove all graphics
self.graphicsLayer.removeAllGraphics()
// reset sketchModeSegCtrl to point
self.sketchModeSegCtrl.selectedSegmentIndex = 0
for (var i = 0; i < self.sketchModeSegCtrl.numberOfSegments; i++) {
self.sketchModeSegCtrl.setEnabled(true, forSegmentAtIndex: i)
}
//disable the findCFButton
self.findCFButton.enabled = false
// reset directions label
self.statusMessageLabel.text = "Tap on the map to create incidents"
// if the sketch layer was removed/nil'd out, re-add it
if self.sketchLayer == nil {
var geometry:AGSGeometry!
if self.sketchModeSegCtrl.selectedSegmentIndex == 0 {
geometry = AGSMutablePoint(spatialReference: self.mapView.spatialReference)
}
else {
geometry = AGSMutablePolygon(spatialReference: self.mapView.spatialReference)
}
self.sketchLayer = AGSSketchGraphicsLayer(geometry: geometry)
self.mapView.insertMapLayer(self.sketchLayer, withName:"sketchLayer", atIndex:1)
self.mapView.touchDelegate = self.sketchLayer
}
else {
// clear the sketch layer and reset it to a point
self.sketchLayer.clear()
}
self.statusMessageLabel.text = "Add incidents and barriers"
}
func removeIncidentBarrierClicked() {
//redunce the incident number is the removed item is an incident point
if let incidentNum = self.selectedGraphic.attributeAsStringForKey("incidentNumber") {
self.numIncidents--
if self.numIncidents == 0 {
//disable the findCFButton
self.findCFButton.enabled = false
}
}
//redunce the barrier number is the removed item is a barrier polygon
if let let barrierNum = self.selectedGraphic.attributeAsStringForKey("barrierNumber") {
self.numBarriers--
}
//remove the selected graphic from the layer
self.graphicsLayer.removeGraphic(self.selectedGraphic)
//nil out the selected graphic property.
self.selectedGraphic = nil
// hide the callout
self.mapView.callout.hidden = true
}
// create a composite symbol with a number
func incidentSymbol() -> AGSCompositeSymbol {
let cs = AGSCompositeSymbol()
// create outline
let sls = AGSSimpleLineSymbol()
sls.color = UIColor.blackColor()
sls.width = 2
sls.style = .Solid
cs.addSymbol(sls)
// create main circle
let sms = AGSSimpleMarkerSymbol()
sms.color = UIColor.greenColor()
sms.outline = sls
sms.size = CGSizeMake(20, 20)
sms.style = .Circle
cs.addSymbol(sms)
return cs
}
//generates the symbol for the routes.
func routeSymbol() -> AGSCompositeSymbol {
let cs = AGSCompositeSymbol()
//the outline symbol
let sls1 = AGSSimpleLineSymbol()
sls1.color = UIColor(red: 1.0, green:1.0, blue:1.0, alpha:0.5)
sls1.style = .Solid
sls1.width = 8
cs.addSymbol(sls1)
//the color of the route.
let sls2 = AGSSimpleLineSymbol()
sls2.color = UIColor(red:0.3, green:0.3, blue:1.0, alpha:0.5)
sls2.style = .Solid
sls2.width = 4
cs.addSymbol(sls2)
return cs
}
// default symbol for the barriers
//
func barrierSymbol() -> AGSCompositeSymbol {
let cs = AGSCompositeSymbol()
let sls = AGSSimpleLineSymbol()
sls.color = UIColor.redColor()
sls.style = .Solid
sls.width = 2
let sfs = AGSSimpleFillSymbol()
sfs.outline = sls
sfs.style = .Solid
sfs.color = UIColor.redColor().colorWithAlphaComponent(0.45)
cs.addSymbol(sfs)
return cs
}
//MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == kSettingsSegueName {
let controller = segue.destinationViewController as! SettingsViewController
controller.parameters = self.parameters
//if ipad show formsheet
if AGSDevice.currentDevice().isIPad() {
controller.modalPresentationStyle = .FormSheet
}
}
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
| apache-2.0 | a725fd134a0f6e4f164d87e3b59719f0 | 38.770344 | 210 | 0.647797 | 5.018941 | false | false | false | false |
sclark01/Swift_VIPER_Demo | VIPER_Demo/VIPER_DemoTests/ModulesTests/PersonDetailsTests/PresenterTests/PersonDetailsPresenterTests.swift | 1 | 1458 | import Foundation
import Quick
import Nimble
@testable import VIPER_Demo
class PersonDetailsPresenterTests : QuickSpec {
override func spec() {
describe("person details presenter") {
var presenter: PersonDetailsPresenter!
var mockInteractor: PersonDetailsInteractorMock!
var mockUI: PersonDetailsViewMock!
beforeEach {
presenter = PersonDetailsPresenter()
mockInteractor = PersonDetailsInteractorMock()
mockUI = PersonDetailsViewMock()
presenter.interactor = mockInteractor
presenter.userInterface = mockUI
}
it("should update view by calling get person with ID") {
let id = 10
presenter.updateViewFor(id: id)
expect(mockInteractor.getPersonByIdCalled).to(beTrue())
expect(mockInteractor.getPersonByIdCalledWithId) == id
}
it("should notify UI when a person is found") {
let personData = PersonDetailsData(person: Person(id: 1, name: "aName", phone: "aPhone", age: "anAge"))
let expectedPerson = PersonDetailsDataModel(person: personData)
presenter.got(person: personData)
expect(mockUI.calledDisplayWithPerson).toNot(beNil())
expect(mockUI.calledDisplayWithPerson) == expectedPerson
}
}
}
}
| mit | a05d0b5d33561a8eebccac1d5dc79e66 | 32.906977 | 119 | 0.603567 | 5.301818 | false | false | false | false |
VicFrolov/Markit | iOS/Markit/Markit/TagListViewController.swift | 1 | 1066 | //
// TagListViewController.swift
// Markit
//
// Created by Bryan Ku on 11/30/16.
// Copyright © 2016 Victor Frolov. All rights reserved.
//
import UIKit
class TagListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var items = [String]()
override func viewDidLoad() {
super.viewDidLoad()
}
private func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "itemCell", for: indexPath) as! SellingListTableViewCell
let itemName = items[indexPath.row]
cell.itemNameLabel?.text = itemName
cell.itemImageView?.image = UIImage(named: itemName)
return cell
}}
| apache-2.0 | 9ab58798ec4bf5405e93201b97258a09 | 28.583333 | 121 | 0.668545 | 5.144928 | false | false | false | false |
victorchee/DynamicAnimator | DynamicAnimator/DynamicAnimator/CollisionGravitySpringViewController.swift | 1 | 1647 | //
// CollisionGravitySpringViewController.swift
// DynamicAnimator
//
// Created by qihaijun on 12/24/15.
// Copyright © 2015 VictorChee. All rights reserved.
//
import UIKit
class CollisionGravitySpringViewController: UIViewController {
@IBOutlet weak var attachmentView: UIView!
@IBOutlet weak var itemView: UIView!
@IBOutlet weak var itemAttachmentView: UIView!
var animator: UIDynamicAnimator!
var attachmentBehavior: UIAttachmentBehavior!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
animator = UIDynamicAnimator(referenceView: view)
let gravityBehavior = UIGravityBehavior(items: [itemView])
let collisionBehavior = UICollisionBehavior(items: [itemView])
collisionBehavior.translatesReferenceBoundsIntoBoundary = true
let anchorPoint = CGPoint(x: itemView.center.x, y: itemView.center.y - 100)
attachmentBehavior = UIAttachmentBehavior(item: itemView, attachedToAnchor: anchorPoint)
attachmentBehavior.frequency = 1
attachmentBehavior.damping = 0.1
attachmentView.center = attachmentBehavior.anchorPoint
itemAttachmentView.center = CGPoint(x: 44, y: 44)
animator.addBehavior(attachmentBehavior)
animator.addBehavior(collisionBehavior)
animator.addBehavior(gravityBehavior)
}
@IBAction func pan(_ sender: UIPanGestureRecognizer) {
attachmentBehavior.anchorPoint = sender.location(in: view)
attachmentView.center = attachmentBehavior.anchorPoint
}
}
| mit | a595431fd46d9c67332ea0a46b44c4b2 | 34.021277 | 96 | 0.705346 | 5.414474 | false | false | false | false |
skedgo/tripkit-ios | TripKit.playground/section-1.swift | 1 | 4775 | // Playground - noun: a place where people can play
import Cocoa
struct Operator {
let name: String
let services: Int
let isRealTime: Bool
let transitTypes: [String]
static func loadOperator(fromJSON JSON: [String: AnyObject]) -> Operator? {
guard let name = JSON["name"] as? String,
let services = JSON["numberOfServices"] as? Int,
let realTimeRaw = JSON["realTimeStatus"] as? String,
let transitTypes = JSON["types"] as? [String] else {
return nil
}
let isRealTime = realTimeRaw != "INCAPABLE"
return Operator(name: name.localizedCapitalizedString, services: services, isRealTime: isRealTime, transitTypes: transitTypes)
}
}
struct Region {
let country: String
let state: String?
let name: String
let code: String
let operators: [Operator]
let extras: [String]
static func loadRegion(fromJSON JSON: [String: AnyObject]) -> Region? {
guard let centerJSON = JSON["center"] as? [String: AnyObject],
let title = (centerJSON["title"] as? String),
let code = JSON["code"] as? String,
let operatorJSON = JSON["operators"] as? [[String: AnyObject]],
let extraJSON = JSON["extraModes"] as? [[String: AnyObject]] else {
return nil
}
let titleParts = title.characters.split(",").map { String($0).stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: " ")) }
guard let city = titleParts.first,
let country = titleParts.last else {
return nil
}
let state: String? = titleParts.count >= 3 ? titleParts[1] : nil
var name = city
if let others = centerJSON["subtitle"] as? String {
name += " (\(others))"
}
let operators = operatorJSON.flatMap { Operator.loadOperator(fromJSON: $0) }
let extras = extraJSON.flatMap { $0["title"] as? String }
return Region(country: country, state: state, name: name, code: code, operators: operators, extras: extras)
}
func operatorsString(maxOperatorCount: Int = Int.max) -> String {
return operators
.map { $0.name + ($0.isRealTime ? " *" : "") }
.suffix(maxOperatorCount)
.joinWithSeparator(", ")
}
func modesString() -> String {
return extras.joinWithSeparator(", ")
}
}
extension Region: Comparable {
}
func ==(x: Region, y: Region) -> Bool {
return x.country == y.country && x.state == y.state && x.name == y.name
}
func <(x: Region, y: Region) -> Bool {
if x.country != y.country {
return x.country < y.country
}
if let xs = x.state, let ys = y.state where xs != ys {
return xs < ys
}
return x.name < y.name
}
extension Region: Hashable {
var hashValue: Int { return "\(country).\(state).\(name)".hashValue }
}
func getJSON(url: NSURL) -> [String: AnyObject]? {
guard let data = NSData(contentsOfURL: url),
let JSON = try? NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers),
let dictionary = JSON as? [String: AnyObject] else {
return nil
}
return dictionary
}
// download the data from the specified server
let servers = ["baryogenesis", "inflationary", "hadron", "bigbang", "granduni"]
let operatorCount = 0
let filter: [String] = [] // ["FI_"]
let includeOperators = false
var allRegions: Set<Region> = []
for server in servers {
guard let URL = NSURL(string: "https://\(server).buzzhives.com/satapp/regionInfo.json"),
let json = getJSON(URL),
let regionsJSON = json["regions"] as? [[String: AnyObject]] else {
print("\(server) has issues.")
continue
}
let serverRegions = regionsJSON.flatMap { Region.loadRegion(fromJSON: $0) }
allRegions.unionInPlace(serverRegions)
// break
}
let sorted = Array(allRegions).sort()
// construct the output
var string = ""
var lastCountry = ""
var hasState = false
for region in sorted {
if filter.count > 0 {
var good = false
for needle in filter {
if let _ = region.code.rangeOfString(needle) {
good = true
break
}
}
if !good {
continue
}
}
if region.country != lastCountry {
if string.utf16.count > 0 {
string += "\n"
}
string += "\(region.country): "
lastCountry = region.country
hasState = region.state != nil
} else {
string += hasState ? "; " : ", "
}
string += region.name
if let state = region.state {
string += ", \(state)"
}
if includeOperators {
let ops = region.operatorsString(operatorCount)
if ops.utf16.count > 0 {
string += ": " + ops
}
let exs = region.modesString()
if exs.utf16.count > 0 {
if ops.utf16.count == 0 {
string += ": "
} else {
string += " + "
}
string += exs
}
}
}
print(string)
| apache-2.0 | a9ade6718b74f5d9099f7c1c64c10553 | 25.825843 | 140 | 0.61822 | 3.838424 | false | false | false | false |
yeziahehe/Gank | Gank/Helpers/GankNetworking.swift | 1 | 6740 | //
// GankNetworking.swift
// Gank
//
// Created by 叶帆 on 2016/10/31.
// Copyright © 2016年 Suzhou Coryphaei Information&Technology Co., Ltd. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
public enum resourceMode: String {
case url
case json
case auth
}
public struct Resource<A>: CustomStringConvertible {
let path: String
let method: HTTPMethod
let headers: HTTPHeaders?
let requestParameters: Parameters?
let encoding: ParameterEncoding
let mode: resourceMode
let username: String?
let password: String?
let parse: (JSON) -> A?
public var description: String {
return "Resource(Method: \(method), path: \(path), headers: \(String(describing: headers)), requestParamters: \(String(describing: requestParameters))), resourceMode: \(mode)"
}
public init(path: String, method: HTTPMethod, headers: HTTPHeaders?, requestParameters: Parameters?, encoding: ParameterEncoding, mode: resourceMode, username: String?, password: String?, parse: @escaping (JSON) -> A?) {
self.path = path
self.method = method
self.headers = headers
self.requestParameters = requestParameters
self.encoding = encoding
self.mode = mode
self.username = username
self.password = password
self.parse = parse
}
}
public enum Reason: CustomStringConvertible {
case error
case couldNotParseJSON
case noData
case other(Error?)
public var description: String {
switch self {
case .error:
return "Error"
case .couldNotParseJSON:
return "CouldNotParseJSON"
case .noData:
return "NoData"
case .other(let error):
return "Other, Error: \(String(describing: error))"
}
}
}
public typealias FailureHandler = (_ reason: Reason, _ errorMessage: String?) -> Void
public let defaultFailureHandler: FailureHandler = { (reason, errorMessage) in
print("\n***************************** GankNetworking Failure *****************************")
print("Reason: \(reason)")
if let errorMessage = errorMessage {
print("errorMessage: >>>\(errorMessage)<<<\n")
}
}
public func apiRequest<A>(_ modifyRequest: (URLRequest) -> (), baseURL: URL, resource: Resource<A>?, failure: FailureHandler?, completion: @escaping (A) -> Void) {
let failure: FailureHandler = { (reason, errorMessage) in
defaultFailureHandler(reason, errorMessage)
failure?(reason, errorMessage)
}
guard let resource = resource else {
failure(.other(nil), "No resource")
return
}
let url = baseURL.appendingPathComponent(resource.path)
let method = resource.method
switch resource.mode {
case .json:
Alamofire.request(url, method: method, parameters: resource.requestParameters, encoding: resource.encoding, headers: resource.headers).responseJSON { response in
switch response.result {
case .success(let value):
if let result = resource.parse(JSON(value)) {
completion(result)
} else {
failure(.couldNotParseJSON, errorMessageInData(value))
}
case .failure(let error):
failure(.noData, errorMessageInData(error))
}
}
return
case .url:
Alamofire.request(url, method: method, parameters: resource.requestParameters, encoding: resource.encoding).validate().responseJSON { response in
switch response.result {
case .success(let value):
let error = isErrorInData(value)
if error {
failure(.error, errorMessageInData(value))
} else {
if let result = resource.parse(JSON(value)) {
completion(result)
} else {
failure(.couldNotParseJSON, errorMessageInData(value))
}
}
case .failure(let error):
failure(.noData, errorMessageInData(error))
}
}
return
case .auth:
Alamofire.request(url, method: method, encoding: resource.encoding, headers: resource.headers).responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
if let errorMessage = json["message"].string {
failure(.error, errorMessage)
} else {
if let result = resource.parse(JSON(value)) {
completion(result)
} else {
failure(.couldNotParseJSON, errorMessageInData(value))
}
}
case .failure(let error):
failure(.noData, errorMessageInData(error))
}
}
}
}
func isErrorInData(_ data: Any) -> Bool {
let json = JSON(data)
if let isError = json["error"].bool {
return isError
}
return true
}
func errorMessageInData(_ data: Any) -> String? {
let json = JSON(data)
if let errorMessage = json["msg"].string {
return errorMessage
}
return nil
}
public func urlResource<A>(path: String, method: HTTPMethod, requestParameters: Parameters?, parse: @escaping (JSON) -> A?) -> Resource<A> {
return Resource(path: path, method: method, headers: nil, requestParameters: requestParameters, encoding: URLEncoding.default, mode: .url, username: nil, password: nil, parse: parse)
}
public func jsonResource<A>(path: String, method: HTTPMethod, requestParameters: Parameters?, parse: @escaping (JSON) -> A?) -> Resource<A> {
let headers = [
"Content-Type": "application/json; charset=UTF-8",
"X-Accept": "application/json",
]
return Resource(path: path, method: method, headers: headers, requestParameters: requestParameters, encoding: JSONEncoding.default, mode: .json, username: nil, password: nil, parse: parse)
}
public func authJsonResource<A>(username: String, password: String, path: String, method: HTTPMethod, parse: @escaping (JSON) -> A?) -> Resource<A> {
var headers: HTTPHeaders = [:]
if let authorizationHeader = Request.authorizationHeader(user: username, password: password) {
headers[authorizationHeader.key] = authorizationHeader.value
}
return Resource(path: path, method: method, headers: headers, requestParameters: nil, encoding: JSONEncoding.default, mode: .auth, username: username, password: password, parse: parse)
}
| gpl-3.0 | 6ee924a085b85056df5566670d46ede2 | 35.394595 | 224 | 0.606862 | 4.816166 | false | false | false | false |
djflsdl08/BasicIOS | DropIt/DropIt/FallingObjectBehavior.swift | 1 | 1333 | //
// FallingObjectBehavior.swift
// DropIt
//
// Created by 김예진 on 2017. 10. 16..
// Copyright © 2017년 Kim,Yejin. All rights reserved.
//
import UIKit
class FallingObjectBehavior: UIDynamicBehavior {
let gravity = UIGravityBehavior()
private let collider : UICollisionBehavior = {
let collider = UICollisionBehavior()
collider.translatesReferenceBoundsIntoBoundary = true
return collider
}()
private let itemBehavior : UIDynamicItemBehavior = {
let dib = UIDynamicItemBehavior()
dib.allowsRotation = false
dib.elasticity = 0.75
return dib
}()
func addBarrier(path : UIBezierPath, named name : String) {
collider.removeBoundary(withIdentifier: name as NSCopying)
collider.addBoundary(withIdentifier: name as NSCopying, for: path)
}
override init() {
super.init()
addChildBehavior(gravity)
addChildBehavior(collider)
addChildBehavior(itemBehavior)
}
func addItem(item : UIDynamicItem) {
gravity.addItem(item)
collider.addItem(item)
itemBehavior.addItem(item)
}
func removeItem(item : UIDynamicItem) {
gravity.removeItem(item)
collider.removeItem(item)
itemBehavior.removeItem(item)
}
}
| mit | b824429ff41066fdad64c4de8a85db2a | 24.960784 | 74 | 0.646526 | 4.678445 | false | false | false | false |
SnowdogApps/Project-Needs-Partner | CooperationFinder/Controllers/SDRegisterViewController.swift | 1 | 5919 | //
// SDRegisterViewController.swift
// CooperationFinder
//
// Created by Radoslaw Szeja on 25.02.2015.
// Copyright (c) 2015 Snowdog. All rights reserved.
//
import UIKit
@IBDesignable
class SDRegisterViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var emailField: UITextField?
@IBOutlet weak var passwordField: UITextField?
@IBOutlet weak var fullNameField: UITextField?
@IBOutlet weak var serviceNameField: UITextField?
@IBOutlet weak var phoneNumberField: UITextField?
@IBOutlet weak var registerButton: UIButton?
@IBOutlet weak var _scrollView: UIScrollView?
var _restorationContentOffset: CGPoint?
var backTapped : (() -> ())?
var completion: (() -> ())?
override var scrollView: UIScrollView! {
get { return _scrollView! }
set { }
}
override var restorationContentOffset: CGPoint {
get {
if let offset = _restorationContentOffset {
return offset
}
return CGPointZero
}
set { _restorationContentOffset = newValue }
}
override func viewDidLoad() {
super.viewDidLoad()
var color = UIColor(red: 113/255.0, green: 145/255.0, blue: 145/255.0, alpha: 1.0)
if let placeholder = emailField?.placeholder {
emailField?.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName: color])
}
if let placeholder = passwordField?.placeholder {
passwordField?.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName: color])
}
if let placeholder = fullNameField?.placeholder {
fullNameField?.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName: color])
}
if let placeholder = serviceNameField?.placeholder {
serviceNameField?.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName: color])
}
if let placeholder = phoneNumberField?.placeholder {
phoneNumberField?.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName: color])
}
registerButton?.layer.cornerRadius = 5.0
registerButton?.layer.borderColor = UIColor(red: 6/255.0, green: 39/255.0, blue: 23/255.0, alpha: 1.0).CGColor
registerButton?.layer.borderWidth = 1.0
}
@IBAction func registerButtonTapped(sender: UIButton) {
if !self.allFieldsNotEmpty() {
let alert = UIAlertView(title: NSLocalizedString("Oops", comment:""), message: NSLocalizedString("All fields cannot be empty", comment:""), delegate: nil, cancelButtonTitle: "OK")
alert.show()
return
}
sender.addActivityIndicatorWithStyle(UIActivityIndicatorViewStyle.White)
var user: User = User()
user.email = emailField?.text
user.company = serviceNameField?.text
user.fullname = fullNameField?.text
user.password = passwordField?.text
user.phone = phoneNumberField?.text
User.saveUser(user, completion: { (user, error) -> Void in
sender.removeActivityIndicator()
if user != nil {
println("user id is: \(user?.id)")
Defaults["user_id"] = user?.id
Defaults.synchronize()
self.dismissViewControllerAnimated(true) {
if let _completion = self.completion {
_completion()
}
}
} else {
println("register error: \(error)")
}
})
}
@IBAction func dismissSelf(sender: UIButton) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func backButtonTapped(sender: AnyObject) {
if let _backTapped = self.backTapped {
_backTapped()
}
}
func allFieldsNotEmpty() -> Bool {
if let emailText = emailField?.text {
if let passwordText = passwordField?.text {
if let fullNameText = fullNameField?.text {
if let serviceNameText = serviceNameField?.text {
if let phoneNumberText = phoneNumberField?.text {
return !(emailText.isEmpty ||
passwordText.isEmpty ||
fullNameText.isEmpty ||
serviceNameText.isEmpty ||
phoneNumberText.isEmpty
)
}
}
}
}
}
return false
}
func textFieldDidBeginEditing(textField: UITextField) {
self.moveUpForTextfield(textField)
}
func textFieldDidEndEditing(textField: UITextField) {
self.moveToOriginalPosition()
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField == emailField {
fullNameField?.becomeFirstResponder()
} else if textField == fullNameField {
phoneNumberField?.becomeFirstResponder()
} else if textField == phoneNumberField {
serviceNameField?.becomeFirstResponder()
} else if textField == serviceNameField {
passwordField?.becomeFirstResponder()
} else if textField == passwordField {
self.view.endEditing(true)
if let registerButton = self.registerButton {
self.registerButtonTapped(registerButton)
}
}
return true
}
}
| apache-2.0 | 936adfc3f533cf773c9e0576329e5091 | 35.99375 | 191 | 0.592161 | 5.780273 | false | false | false | false |
wcharysz/BJSS-iOS-basket-assignment-source-code | ShoppingList/ShoppingListDataSource.swift | 1 | 4516 | //
// ShoppingListDataSource.swift
// ShoppingList
//
// Created by Slawomir Trybus
// Copyright (c) 2015 SlawekTrybus. All rights reserved.
//
import UIKit
enum ShoppingListItemState: String {
case TODO = "new items"
case DONE = "collected already"
}
class ShoppingListItem: NSCoder {
var name: String
var price: String?
var currency: Currency?
override init() {
name = ""
}
init(name: String, price: String) {
self.name = name
self.price = price
}
// MARK: NSCoding
required convenience init(coder decoder: NSCoder) {
self.init()
self.name = decoder.decodeObjectForKey("name") as! String
if let price = decoder.decodeObjectForKey("price") as? String {
self.price = price
}
if let money = decoder.decodeObjectForKey("currency") as? String {
self.currency = Currency(rawValue: money)
}
}
func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(self.name, forKey: "name")
coder.encodeObject(self.price, forKey: "price")
coder.encodeObject(self.currency?.rawValue, forKey: "currency")
}
}
class ShoppingListDataSource: TableViewDataSource {
private var sectionsAndItems: [Int: [ShoppingListItem]] = [:]
var numberOfSections: Int {
return sectionsAndItems.count
}
var sectionTitles: [String] {
let titles = [ShoppingListItemState.TODO.rawValue, ShoppingListItemState.DONE.rawValue]
return titles
}
init() {
reloadData()
}
func numberOfItemsInSection(section: Int) -> Int? {
return sectionsAndItems[section]?.count
}
func itemsInSection(section: Int) -> [ShoppingListItem]? {
return sectionsAndItems[section]
}
subscript(section: Int) -> [ShoppingListItem]? {
return itemsInSection(section)
}
func itemAtIndexPath(indexPath: NSIndexPath) -> ShoppingListItem? {
let items: [ShoppingListItem]? = self[indexPath.section]
return items?[indexPath.row]
}
func insertItem(item: ShoppingListItem, atIndexPath indexPath: NSIndexPath) {
let section = indexPath.section
let row = indexPath.row
_ = self.sectionTitles[indexPath.section]
sectionsAndItems[section]?.insert(item, atIndex: row)
archiveData()
}
func removeItemAtIndexPath(indexPath: NSIndexPath) {
let section = indexPath.section
let row = indexPath.row
_ = self.sectionTitles[indexPath.section]
sectionsAndItems[section]?.removeAtIndex(row)
archiveData()
}
func moveItemFromIndexPath(beginIndexPath: NSIndexPath, toIndexPath endIndexPath: NSIndexPath) {
let beginSection = beginIndexPath.section
let beginIndex = beginIndexPath.row
let endSection = endIndexPath.section
let endIndex = endIndexPath.row
if beginSection == endSection {
if var items = sectionsAndItems[beginSection] {
let item = items[beginIndex]
if beginIndex < endIndex {
items.removeAtIndex(beginIndex)
items.insert(item, atIndex: endIndex)
} else {
items.removeAtIndex(beginIndex)
items.insert(item, atIndex: endIndex)
}
sectionsAndItems[beginSection] = items
}
} else {
if var items = sectionsAndItems[beginSection], var _ = sectionsAndItems[endSection] {
let item = items[beginIndex]
removeItemAtIndexPath(beginIndexPath)
insertItem(item, atIndexPath: endIndexPath)
}
}
archiveData()
}
func reloadData() -> Void {
if let arch = unarchiveData() {
sectionsAndItems = arch
} else {
//sectionsAndItems = [0: [ShoppingListItem(name: "An item to take")],
// 1: [ShoppingListItem(name: "Collected item")]]
sectionsAndItems = [0: [ShoppingListItem(name: "Peas", price: "95p per bag"),
ShoppingListItem(name: "Eggs", price: "£2.10 per dozen"),
ShoppingListItem(name: "Milk", price: "£1.30 per bottle"),
ShoppingListItem(name: "Beans", price: "73p per can")]]
}
}
private func archiveData() {
NSKeyedArchiver.archiveRootObject(sectionsAndItems, toFile: archivedDataFilePath())
}
private func unarchiveData() -> [Int: [ShoppingListItem]]? {
return NSKeyedUnarchiver.unarchiveObjectWithFile(archivedDataFilePath()) as? [Int: [ShoppingListItem]]
}
private func archivedDataFilePath() -> String {
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
return documentsDirectory + "/data"
}
}
| apache-2.0 | aaae2e79b7b517ad85472a54655bdbf1 | 24.647727 | 109 | 0.673903 | 4.10737 | false | false | false | false |
onevcat/Kingfisher | Tests/KingfisherTests/Utils/StubHelpers.swift | 2 | 2112 | //
// StubHelpers.swift
// Kingfisher
//
// Created by Wei Wang on 2018/10/12.
//
// Copyright (c) 2019 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
@discardableResult
func stub(_ url: URL, data: Data, statusCode: Int = 200, length: Int? = nil) -> LSStubResponseDSL {
var stubResult = stubRequest("GET", url.absoluteString as NSString).andReturn(statusCode)?.withBody(data as NSData)
if let length = length {
stubResult = stubResult?.withHeader("Content-Length", "\(length)")
}
return stubResult!
}
func delayedStub(_ url: URL, data: Data, statusCode: Int = 200, length: Int? = nil) -> LSStubResponseDSL {
let result = stub(url, data: data, statusCode: statusCode, length: length)
return result.delay()!
}
func stub(_ url: URL, errorCode: Int) {
let error = NSError(domain: "stubError", code: errorCode, userInfo: nil)
stub(url, error: error)
}
func stub(_ url: URL, error: Error) {
return stubRequest("GET", url.absoluteString as NSString).andFailWithError(error)
}
| mit | 95b618704ffac99c91b56a8ffad405ae | 41.24 | 119 | 0.722064 | 4.022857 | false | false | false | false |
DallasMcNeil/Overflow | Overflow/AppDelegate.swift | 1 | 7418 | //
// AppDelegate.swift
// Overflow
//
// Created by Dallas McNeil on 8/05/2015.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
/// Status bar item of the application
var statusItem:NSStatusItem?
/// The menu contained by the status bar item
var menu:NSMenu = NSMenu()
/// Whether the trash will be checked and moved or not
var working:Bool = true
/// File manager to manage trash and desktop files
var manager:FileManager = FileManager()
/// List of files located inside the trash folder
var files:[NSString] = []
/// File path to the trash
var trashPath:String = "/Users/\(NSUserName())/.Trash"
/// File path to the desktop
var desktopPath:String = "/Users/\(NSUserName())/Desktop"
/// The minimum number of files in trash before Overflow will take action
var minLoad:Int = 50
/// The maximum number of files in the trash before Overflow will always take action
var maxLoad:Int = 250
/// The maximum number of files that can overflow when the maximum is reached
var magnitude:Int = 10
/// Time between each update to check for trash changing. Smaller time intervals will cause worse performance
let updateTime:TimeInterval = 1
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Create status bar with icon
statusItem = NSStatusBar.system().statusItem(withLength: 24)
statusItem!.image = NSImage(named: "recycle")
// Create menu items for stauts bar
let title = NSMenuItem(title:"Overflow: Ver 1.0", action: nil, keyEquivalent: "")
let onOrOff = NSMenuItem(title: "Turn Overflow Off", action: #selector(AppDelegate.turnOff(_:)), keyEquivalent: "")
let about = NSMenuItem(title:"About", action: #selector(AppDelegate.about(_:)), keyEquivalent: "")
let quit = NSMenuItem(title:"Quit", action: #selector(AppDelegate.quit(_:)), keyEquivalent: "")
// Add menu items to menu
menu.addItem(title)
menu.addItem(NSMenuItem.separator())
menu.addItem(onOrOff)
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem.separator())
menu.addItem(about)
menu.addItem(quit)
NSWorkspace.shared()
// Set menu to be status bars menu
statusItem!.menu = menu
// Get path of all files in trash
let tempFiles = (try! manager.contentsOfDirectory(atPath: trashPath))
for file in tempFiles {
files.append(NSString(string:file))
}
// Set a timer to call 'update' after a period of time
Timer.scheduledTimer(timeInterval: updateTime, target: self, selector: #selector(AppDelegate.update), userInfo: nil, repeats: true)
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
/// Disable overflow taking action
func turnOff(_ sender:AnyObject) {
let item = menu.item(withTitle: "Turn Overflow Off")
item!.title = "Turn Overflow On"
item!.action = #selector(AppDelegate.turnOn(_:))
working = false
}
/// Enable overflow taking action
func turnOn(_ sender:AnyObject) {
let item = menu.item(withTitle: "Turn Overflow On")
item!.title = "Turn Overflow Off"
item!.action = #selector(AppDelegate.turnOff(_:))
working = true
}
/// Quit the application
func quit(_ sender:AnyObject) {
NSApplication.shared().terminate(self)
}
/// Present information about Overflow
func about(_ sender:AnyObject) {
let alert:NSAlert = NSAlert()
alert.alertStyle = NSAlertStyle.informational
alert.informativeText = "Overflow treats your trash like it should be. Pile too much up and it's bound to fall out. Keep your trash under control or your dektop will be full of clutter. For best results, add this application to your Login Items in System Preferences under the Users and Groups section. Made by Dallas McNeil"
alert.messageText = "Overflow Version 1.0"
alert.runModal()
}
/// Called every updateTime and will see if it needs to move files to the desktop
func update() {
// Check if application is allowed to move files
if working {
// Check files in trash and see if there are more than before
var trashFiles:[NSString] = []
var tempFiles = (try! manager.contentsOfDirectory(atPath: trashPath))
for file in tempFiles {
trashFiles.append(NSString(string:file))
}
if trashFiles.count > files.count {
// Calculate the chance that files will be moved based on current load
let theChance = Int(arc4random()%UInt32(maxLoad-minLoad))
if theChance < trashFiles.count-minLoad {
// Multiplier based on the amount of files in the trash
var multiplier = (trashFiles.count-minLoad)/(maxLoad-minLoad)
if multiplier > 1 {
multiplier = 1
}
// Calculate the number of files that will be moved
let theMagnitude = Int(arc4random()%UInt32(magnitude*multiplier))
print(theMagnitude)
// Choose randomly which files will be moved by sorting files randomly and picking first ones
trashFiles = trashFiles.sorted {_, _ in arc4random() % 2 == 0}
// Use index to manage how many files have moved and stop if exceeded
var currentIndex = 0
// Iterate over files and move first ones
for file in trashFiles {
// Break loop if exceeded file limit
if currentIndex >= theMagnitude {
break
}
// If file is not .DS_Store then move the file
if file != ".DS_Store" {
// Try to move file and if not possible, print error
do {
try manager.moveItem(atPath: "\(trashPath)/\(file)", toPath: "\(desktopPath)/CRUMPLED-\(file)")
} catch let error as NSError {
print(error)
}
NSWorkspace.shared()
// Iterate current index to represent move
currentIndex += 1
}
}
}
// Update files to represent changes to trash
files = []
tempFiles = (try! manager.contentsOfDirectory(atPath: trashPath))
for file in tempFiles {
files.append(NSString(string:file))
}
}
}
}
}
| mit | d14e0de37ad9448e5ccec7dd25b043de | 38.668449 | 333 | 0.558372 | 5.383164 | false | false | false | false |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/LifetimeTracker/Sources/iOS/UI/Constants+UIKit.swift | 1 | 1093 | //
// Constants.swift
// LifetimeTracker
//
// Created by Hans Seiffert on 09.11.17.
// Copyright © 2017 LifetimeTracker. All rights reserved.
//
import UIKit
extension Constants {
struct Layout {
static let animationDuration: TimeInterval = 0.3
struct Dashboard {
static let headerHeight: CGFloat = 44.0
static let cellHeight: CGFloat = 44
static let minTotalHeight: CGFloat = headerHeight + cellHeight
static let sectionHeaderHeight: CGFloat = 30
}
}
enum Segue {
case embedDashboardTableView
var identifier: String {
switch self {
case .embedDashboardTableView: return "embedDashboardTableViewController"
}
}
}
enum Storyboard {
case circularDashboard
case barDashbaord
var name: String {
switch self {
case .circularDashboard: return "CircularDashboard"
case .barDashbaord: return "BarDashboard"
}
}
}
}
| mit | 36fd42b0869d85486ae79857484d1436 | 23.266667 | 85 | 0.576923 | 5.300971 | false | false | false | false |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/LayoutKit/Sources/Views/StackView.swift | 1 | 5853 | // Copyright 2016 LinkedIn Corp.
// 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.
import UIKit
/**
A view that stacks its subviews along a single axis.
It is similar to UIStackView except that it uses StackLayout instead of Auto Layout, which means layout is much faster.
Although StackView is faster than UIStackView, it still does layout on the main thread.
If you want to get the full benefit of LayoutKit, use StackLayout directly.
Unlike UIStackView, if you position StackView with Auto Layout, you must call invalidateIntrinsicContentSize on that StackView
whenever any of its subviews' intrinsic content sizes change (e.g. changing the text of a UILabel that is positioned by the StackView).
Otherwise, Auto Layout won't recompute the layout of the StackView.
Subviews MUST implement sizeThatFits so StackView can allocate space correctly.
If a subview uses Auto Layout, then the subview may implement sizeThatFits by calling systemLayoutSizeFittingSize.
*/
open class StackView: UIView {
/// The axis along which arranged views are stacked.
public let axis: Axis
/**
The distance in points between adjacent edges of sublayouts along the axis.
For Distribution.EqualSpacing, this is a minimum spacing. For all other distributions it is an exact spacing.
*/
public let spacing: CGFloat
/// The distribution of space along the stack's axis.
public let distribution: StackLayoutDistribution
/// The distance that the arranged views are inset from the stack view. Defaults to 0.
public let contentInsets: UIEdgeInsets
/// The stack's alignment inside its parent.
public let alignment: Alignment
/// The stack's flexibility.
public let flexibility: Flexibility?
private var arrangedSubviews: [UIView] = []
public init(axis: Axis,
spacing: CGFloat = 0,
distribution: StackLayoutDistribution = .leading,
contentInsets: UIEdgeInsets = .zero,
alignment: Alignment = .fill,
flexibility: Flexibility? = nil) {
self.axis = axis
self.spacing = spacing
self.distribution = distribution
self.contentInsets = contentInsets
self.alignment = alignment
self.flexibility = flexibility
super.init(frame: .zero)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/**
Adds a subview to the stack.
Subviews MUST implement sizeThatFits so StackView can allocate space correctly.
If a subview uses Auto Layout, then the subview can implement sizeThatFits by calling systemLayoutSizeFittingSize.
*/
open func addArrangedSubviews(_ subviews: [UIView]) {
arrangedSubviews.append(contentsOf: subviews)
for subview in subviews {
addSubview(subview)
}
invalidateIntrinsicContentSize()
setNeedsLayout()
}
/**
Deletes all subviews from the stack.
*/
open func removeArrangedSubviews() {
for subview in arrangedSubviews {
subview.removeFromSuperview()
}
arrangedSubviews.removeAll()
invalidateIntrinsicContentSize()
setNeedsLayout()
}
open override func sizeThatFits(_ size: CGSize) -> CGSize {
return stackLayout.measurement(within: size).size
}
open override var intrinsicContentSize: CGSize {
return sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
}
open override func layoutSubviews() {
stackLayout.measurement(within: bounds.size).arrangement(within: bounds).makeViews(in: self)
}
private var stackLayout: Layout {
let sublayouts = arrangedSubviews.map { view -> Layout in
return ViewLayout(view: view)
}
let stack = StackLayout(
axis: axis,
spacing: spacing,
distribution: distribution,
alignment: alignment,
flexibility: flexibility,
sublayouts: sublayouts,
config: nil)
return InsetLayout(insets: contentInsets, sublayout: stack)
}
}
/// Wraps a UIView so that it conforms to the Layout protocol.
private struct ViewLayout: ConfigurableLayout {
let needsView = true
let view: UIView
let viewReuseId: String? = nil
func measurement(within maxSize: CGSize) -> LayoutMeasurement {
let size = view.sizeThatFits(maxSize)
return LayoutMeasurement(layout: self, size: size, maxSize: maxSize, sublayouts: [])
}
func arrangement(within rect: CGRect, measurement: LayoutMeasurement) -> LayoutArrangement {
return LayoutArrangement(layout: self, frame: rect, sublayouts: [])
}
func makeView() -> UIView {
return view
}
func configure(view: UIView) {
// Nothing to configure.
}
var flexibility: Flexibility {
let horizontal = flexForAxis(.horizontal)
let vertical = flexForAxis(.vertical)
return Flexibility(horizontal: horizontal, vertical: vertical)
}
private func flexForAxis(_ axis: UILayoutConstraintAxis) -> Flexibility.Flex {
switch view.contentHuggingPriority(for: .horizontal) {
case UILayoutPriority.required:
return nil
case let priority:
return -Int32(priority.rawValue)
}
}
}
| mit | 1f30288b9ad8f6aa875ec981eb174fe8 | 34.472727 | 136 | 0.68341 | 5.282491 | false | false | false | false |
RoverPlatform/rover-ios | Sources/Location/Extensions/Location.CLBeaconRegion.swift | 1 | 647 | //
// CLBeaconRegion.swift
// RoverLocation
//
// Created by Sean Rucker on 2018-08-21.
// Copyright © 2018 Rover Labs Inc. All rights reserved.
//
import CoreLocation
#if !COCOAPODS
import RoverFoundation
#endif
extension CLBeaconRegion {
public var attributes: Attributes {
var attributes: [String: Any] = [
"uuid": proximityUUID.uuidString
]
if let major = major {
attributes["major"] = major.intValue
}
if let minor = minor {
attributes["minor"] = minor.intValue
}
return Attributes(rawValue: attributes)
}
}
| apache-2.0 | f9be41403a63cad3c1b431f2b0e9b3d4 | 20.533333 | 57 | 0.586687 | 4.58156 | false | false | false | false |
AssistoLab/FloatingLabel | FloatingLabel/src/fields/FloatingTextField.swift | 2 | 3277 | //
// FloatingTextField.swift
// FloatingLabel
//
// Created by Kevin Hirsch on 4/08/15.
// Copyright (c) 2015 Kevin Hirsch. All rights reserved.
//
import UIKit
import DropDown
public class FloatingTextField: FloatingField {
internal override var input: InputType! {
get {
return textField
}
set {
if let newValue = newValue as? FloatingFieldTextField {
textField = newValue
}
}
}
public var textField = FloatingFieldTextField()
public weak var delegate: UITextFieldDelegate? {
get { return textField.delegate }
set { textField.delegate = newValue }
}
//MARK: - Deinit
deinit {
stopListeningToTextField()
}
}
//MARK: - Initialization
public extension FloatingTextField {
override func setup() {
super.setup()
listenToTextField()
}
}
//MARK: - Update UI
public extension FloatingTextField {
override func updateUI(animated animated: Bool) {
super.updateUI(animated: animated)
let changes: Closure = {
self.rightView?.tintColor = self.separatorLine.backgroundColor
}
applyChanges(changes, animated)
}
}
//MARK: - TextField
private var textFieldKVOContext = 0
extension FloatingTextField {
@objc
public func textFieldTextDidChangeNotification() {
updateUI(animated: true)
valueChangedAction?(value)
}
@objc
public func textFieldTextDidBeginEditingNotification() {
updateUI(animated: true)
hasBeenEdited = true
}
@objc
public func textFieldTextDidEndEditingNotification() {
updateUI(animated: true)
}
//MARK: - KVO
func listenToTextField() {
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(textFieldTextDidBeginEditingNotification),
name: UITextFieldTextDidBeginEditingNotification,
object: textField)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(textFieldTextDidChangeNotification),
name: UITextFieldTextDidChangeNotification,
object: textField)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(textFieldTextDidEndEditingNotification),
name: UITextFieldTextDidEndEditingNotification,
object: textField)
self.addObserver(self, forKeyPath: "textField.text", options: .New, context: &textFieldKVOContext)
}
func stopListeningToTextField() {
NSNotificationCenter.defaultCenter().removeObserver(
self,
name: UITextFieldTextDidBeginEditingNotification,
object: textField)
NSNotificationCenter.defaultCenter().removeObserver(
self,
name: UITextFieldTextDidChangeNotification,
object: textField)
NSNotificationCenter.defaultCenter().removeObserver(
self,
name: UITextFieldTextDidEndEditingNotification,
object: textField)
self.removeObserver(self, forKeyPath: "textField.text", context: &textFieldKVOContext)
}
}
//MARK: - KVO
public extension FloatingField {
override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if context == &textFieldKVOContext
&& (change?[NSKeyValueChangeNewKey] as? String) != nil
{
updateUI(animated: true)
} else {
super.observeValueForKeyPath(keyPath!, ofObject: object!, change: change!, context: context)
}
}
} | mit | 1f2fcc4f03fab4470d00c75b43432ba9 | 20.853333 | 161 | 0.740922 | 4.311842 | false | false | false | false |
MakeSchool/TripPlanner | Carthage/Checkouts/Argo/Carthage/Checkouts/Runes/Tests/Tests/ArraySpec.swift | 3 | 2959 | import SwiftCheck
import XCTest
import Runes
class ArraySpec: XCTestCase {
func testFunctor() {
// fmap id = id
property("identity law") <- forAll { (xs: [Int]) in
let lhs = id <^> xs
let rhs = xs
return lhs == rhs
}
// fmap (f . g) = (fmap f) . (fmap g)
property("function composition law") <- forAll { (a: ArrayOf<Int>, fa: ArrowOf<Int, Int>, fb: ArrowOf<Int, Int>) in
let xs = a.getArray
let f = fa.getArrow
let g = fb.getArrow
let lhs = compose(f, g) <^> xs
let rhs = compose(curry(<^>)(f), curry(<^>)(g))(xs)
return lhs == rhs
}
}
func testApplicative() {
// pure id <*> x = x
property("identity law") <- forAll { (xs: [Int]) in
let lhs = pure(id) <*> xs
let rhs = xs
return lhs == rhs
}
// pure f <*> pure x = pure (f x)
property("homomorphism law") <- forAll { (x: Int, fa: ArrowOf<Int, Int>) in
let f = fa.getArrow
let lhs: [Int] = pure(f) <*> pure(x)
let rhs: [Int] = pure(f(x))
return rhs == lhs
}
// f <*> pure x = pure ($ x) <*> f
property("interchange law") <- forAll { (x: Int, fa: ArrayOf<ArrowOf<Int, Int>>) in
let f = fa.getArray.map { $0.getArrow }
let lhs = f <*> pure(x)
let rhs = pure({ $0(x) }) <*> f
return lhs == rhs
}
// f <*> (g <*> x) = pure (.) <*> f <*> g <*> x
property("composition law") <- forAll { (a: ArrayOf<Int>, fa: ArrayOf<ArrowOf<Int, Int>>, fb: ArrayOf<ArrowOf<Int, Int>>) in
let x = a.getArray
let f = fa.getArray.map { $0.getArrow }
let g = fb.getArray.map { $0.getArrow }
let lhs = f <*> (g <*> x)
let rhs = pure(curry(compose)) <*> f <*> g <*> x
return lhs == rhs
}
}
func testMonad() {
// return x >>= f = f x
property("left identity law") <- forAll { (x: Int, fa: ArrowOf<Int, Int>) in
let f: Int -> [Int] = compose(fa.getArrow, pure)
let lhs = pure(x) >>- f
let rhs = f(x)
return lhs == rhs
}
// m >>= return = m
property("right identity law") <- forAll { (x: [Int]) in
let lhs = x >>- pure
let rhs = x
return lhs == rhs
}
// (m >>= f) >>= g = m >>= (\x -> f x >>= g)
property("associativity law") <- forAll { (a: ArrayOf<Int>, fa: ArrowOf<Int, Int>, fb: ArrowOf<Int, Int>) in
let m = a.getArray
let f: Int -> [Int] = compose(fa.getArrow, pure)
let g: Int -> [Int] = compose(fb.getArrow, pure)
let lhs = (m >>- f) >>- g
let rhs = m >>- { x in f(x) >>- g }
return lhs == rhs
}
}
}
| mit | 9418161df85c7f1d213ab61e74a6dc1b | 28.29703 | 132 | 0.438324 | 3.774235 | false | false | false | false |
justinhester/hacking-with-swift | src/Project33/Project33/ViewController.swift | 1 | 6781 | //
// ViewController.swift
// Project33
//
// Created by Justin Lawrence Hester on 2/18/16.
// Copyright © 2016 Justin Lawrence Hester. All rights reserved.
//
import UIKit
import CloudKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
static var dirty = true
var tableView: UITableView!
var whistles = [Whistle]()
override func loadView() {
super.loadView()
view.backgroundColor = UIColor.whiteColor()
tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.dataSource = self
tableView.delegate = self
view.addSubview(tableView)
view.addConstraints(
NSLayoutConstraint
.constraintsWithVisualFormat(
"H:|[tableView]|",
options: .AlignAllCenterX,
metrics: nil,
views: ["tableView": tableView]
)
)
view.addConstraints(
NSLayoutConstraint
.constraintsWithVisualFormat(
"V:|[guide][tableView]|",
options: .AlignAllCenterX,
metrics: nil,
views: ["guide": topLayoutGuide, "tableView": tableView]
)
)
}
override func viewDidLoad() {
super.viewDidLoad()
title = "What's that Whistle?"
navigationItem.leftBarButtonItem = UIBarButtonItem(
title: "Genres",
style: .Plain,
target: self,
action: "selectGenre"
)
navigationItem.rightBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .Add,
target: self,
action: "addWhistle"
)
navigationItem.backBarButtonItem = UIBarButtonItem(
title: "Home",
style: .Plain,
target: nil,
action: nil
)
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let indexPath = tableView.indexPathForSelectedRow {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
if ViewController.dirty {
loadWhistles()
}
}
func loadWhistles() {
let pred = NSPredicate(value: true)
let sort = NSSortDescriptor(key: "creationDate", ascending: false)
let query = CKQuery(recordType: "Whistles", predicate: pred)
query.sortDescriptors = [sort]
let operation = CKQueryOperation(query: query)
operation.desiredKeys = ["genre", "comments"]
operation.resultsLimit = 50
var newWhistles = [Whistle]()
operation.recordFetchedBlock = { (record) in
let whistle = Whistle()
whistle.recordID = record.recordID
whistle.genre = record["genre"] as! String
whistle.comments = record["comments"] as! String
newWhistles.append(whistle)
}
operation.queryCompletionBlock = { [unowned self] (cursor, error) in
dispatch_async(dispatch_get_main_queue()) {
if error == nil {
ViewController.dirty = false
self.whistles = newWhistles
self.tableView.reloadData()
} else {
let ac = UIAlertController(
title: "Fetch failed",
message: "There was a problem fetching "
+ "the list of whistles; "
+ "please try again: \(error!.localizedDescription)",
preferredStyle: .Alert
)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(ac, animated: true, completion: nil)
}
}
}
CKContainer
.defaultContainer()
.publicCloudDatabase
.addOperation(operation)
}
func selectGenre() {
let vc = MyGenresViewController()
navigationController?.pushViewController(vc, animated: true)
}
func addWhistle() {
let vc = RecordWhistleViewController()
navigationController?.pushViewController(vc, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func makeAttributedString(title title: String, subtitle: String) -> NSAttributedString {
let titleAttributes = [
NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline),
NSForegroundColorAttributeName: UIColor.purpleColor()
]
let subtitleAttributes = [
NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
]
let titleString = NSMutableAttributedString(string: "\(title)", attributes: titleAttributes)
if subtitle.characters.count > 0 {
let subtitleString = NSAttributedString(string: "\n\(subtitle)", attributes: subtitleAttributes)
titleString.appendAttributedString(subtitleString)
}
return titleString
}
// MARK: - table view data source and delegate methods
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.accessoryType = .DisclosureIndicator
cell.textLabel?.attributedText = makeAttributedString(
title: whistles[indexPath.row].genre,
subtitle: whistles[indexPath.row].comments
)
cell.textLabel?.numberOfLines = 0
return cell
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.whistles.count
}
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let vc = ResultsViewController()
vc.whistle = whistles[indexPath.row]
navigationController?.pushViewController(vc, animated: true)
}
}
| gpl-3.0 | 76b8c2c52a178c12a1be52758420f262 | 32.731343 | 112 | 0.60649 | 5.875217 | false | false | false | false |
StevenDXC/SwiftDemo | SwifExample/ViewController.swift | 1 | 3376 | //
// ViewController.swift
// SwiftExample
//
// Created by Miutrip on 2016/12/7.
// Copyright © 2016年 dx. All rights reserved.
//
import UIKit
import LoadingHUD
import Alamofire
import RxSwift
import RxAlamofire
import ObjectMapper
import SnapKit
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{
let disposeBag = DisposeBag()
var tableView:UITableView!;
var loadingView:LoadingContentView!;
var dataSource:Array<RepoItemModel>?;
var didSetupConstraints = false;
override func viewDidLoad() {
super.viewDidLoad()
self.title = "github/StevenDXC"
tableView = UITableView(frame:view.bounds,style:.plain);
tableView.delegate = self;
tableView.dataSource = self;
view.addSubview(tableView);
loadingView = LoadingContentView(frame:view.bounds);
loadingView.backgroundColor = UIColor.white;
loadingView.setLoadingText(text: "Loading...")
view.addSubview(loadingView);
view.setNeedsUpdateConstraints();
APIService.listRepos().subscribe(
onNext: {(response:Array<RepoItemModel>) in
self.dataSource = response;
self.tableView.reloadData();
self.loadingView.loadingSuccessful(msg: "successful");
}, onError: {(error) in
self.loadingView.loadingFailed(msg: error.localizedDescription);
}
).addDisposableTo(disposeBag);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func updateViewConstraints() {
if(!didSetupConstraints){
tableView.snp.makeConstraints({ (make) in
make.edges.equalTo(view);
})
loadingView.snp.makeConstraints { (make) in
make.edges.equalTo(view);
}
didSetupConstraints = true;
}
super.updateViewConstraints();
}
//MARK:---------tableview datasource and delefate
func numberOfSections(in tableView: UITableView) -> Int {
return 1;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource == nil ? 0 : (dataSource?.count)!;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "cell";
var cell = tableView.dequeueReusableCell(withIdentifier: identifier);
if cell == nil {
cell = UITableViewCell.init(style: .default, reuseIdentifier: identifier);
cell?.accessoryType = .disclosureIndicator;
}
let repo:RepoItemModel = dataSource![indexPath.row];
cell?.textLabel?.text = repo.name;
return cell!;
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let repo:RepoItemModel = dataSource![indexPath.row];
self.navigationController?.pushViewController(RepoInfoViewController(repoName:repo.name!), animated: true);
self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"",style:.plain, target: nil, action: nil);
tableView.deselectRow(at: indexPath, animated: true);
}
}
| mit | 80d2f57a150faf2ba1e112e1658060bd | 30.523364 | 115 | 0.628521 | 5.414125 | false | false | false | false |
apple/swift-llbuild | products/llbuildSwift/NinjaManifest.swift | 1 | 5767 | // This source file is part of the Swift.org open source project
//
// Copyright 2021 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 Swift project authors
// This file contains Swift bindings for the llbuild C API.
import Foundation
#if !LLBUILD_FRAMEWORK
import llbuild
#endif
public enum NinjaError: Error {
case invalidManifest(errors: String)
}
public struct NinjaRule: Codable, Equatable {
public let name: String
public let variables: [String: String]
public init(name: String, variables: [String: String]) {
self.name = name
self.variables = variables
}
}
public struct NinjaBuildStatement: Codable, Equatable {
public let rule: NinjaRule
public let command: String
public let description: String
public var allInputs: [String] {
return explicitInputs + implicitInputs + orderOnlyInputs
}
public let explicitInputs: [String]
public let implicitInputs: [String]
public let orderOnlyInputs: [String]
public let outputs: [String]
public let variables: [String: String]
public let generator: Bool
public let restat: Bool
public init(rule: NinjaRule, command: String,
description: String, explicitInputs: [String],
implicitInputs: [String], orderOnlyInputs: [String],
outputs: [String], variables: [String: String],
generator: Bool, restat: Bool) {
self.rule = rule
self.command = command
self.description = description
self.explicitInputs = explicitInputs
self.implicitInputs = implicitInputs
self.orderOnlyInputs = orderOnlyInputs
self.outputs = outputs
self.variables = variables
self.generator = generator
self.restat = restat
}
}
public struct NinjaManifest: Codable, Equatable {
public let rules: [String: NinjaRule]
public let statements: [NinjaBuildStatement]
public let defaultTargets: [String]
public init(rules: [String: NinjaRule], statements: [NinjaBuildStatement],
defaultTargets: [String]) {
self.rules = rules
self.statements = statements
self.defaultTargets = defaultTargets
}
}
extension NinjaManifest {
public init(path: String, workingDirectory: String) throws {
let (manifest, errors) = Self.createNonThrowing(
path: path, workingDirectory: workingDirectory)
if let errors = errors {
throw NinjaError.invalidManifest(errors: errors)
}
self = manifest
}
public static func createNonThrowing(path: String, workingDirectory: String) -> (NinjaManifest, String?) {
var cManifest = llb_manifest_fs_load(path, workingDirectory)
defer {
llb_manifest_destroy(&cManifest)
}
var rules = [String: NinjaRule]()
let statements: [NinjaBuildStatement] = makeArray(
cArray: cManifest.statements,
count: cManifest.num_statements) { raw in
let rule: NinjaRule
let rawRule = raw.rule.pointee
let ruleName = ownedString(rawRule.name)
let foundRule = rules[ruleName]
if let foundRule = foundRule {
rule = foundRule
} else {
rule = NinjaRule(
name: ruleName,
variables: makeMap(
cArray: rawRule.variables,
count: rawRule.num_variables,
transform: ownedVar))
rules[ruleName] = rule
}
return NinjaBuildStatement(
rule: rule,
command: ownedString(raw.command),
description: ownedString(raw.description),
explicitInputs: makeArray(cArray: raw.explicit_inputs,
count: raw.num_explicit_inputs,
transform: ownedString),
implicitInputs: makeArray(cArray: raw.implicit_inputs,
count: raw.num_implicit_inputs,
transform: ownedString),
orderOnlyInputs: makeArray(cArray: raw.order_only_inputs,
count: raw.num_order_only_inputs,
transform: ownedString),
outputs: makeArray(cArray: raw.outputs, count: raw.num_outputs,
transform: ownedString),
variables: makeMap(cArray: raw.variables, count: raw.num_variables,
transform: ownedVar),
generator: raw.generator,
restat: raw.restat)
}
let defaultTargets = makeArray(cArray: cManifest.default_targets,
count: cManifest.num_default_targets,
transform: ownedString)
let error: String?
if cManifest.error.length > 0 {
error = ownedString(cManifest.error)
} else {
error = nil
}
return (NinjaManifest(rules: rules, statements: statements,
defaultTargets: defaultTargets), error)
}
}
private func ownedString(_ ref: CStringRef) -> String {
return String(data: Data(bytes: ref.data, count: Int(ref.length)),
encoding: .utf8)!
}
private func ownedVar(_ ref: CNinjaVariable) -> (String, String) {
return (ownedString(ref.key), ownedString(ref.value))
}
private func makeArray<T, R>(cArray: UnsafePointer<T>, count: UInt64,
transform: (T) -> R) -> [R] {
return UnsafeBufferPointer(start: cArray, count: Int(count)).map(transform)
}
private func makeMap<T, K, V>(cArray: UnsafePointer<T>, count: UInt64,
transform: @escaping (T) -> (K, V)) -> [K: V] {
return Dictionary(
UnsafeBufferPointer(start: cArray, count: Int(count))
.lazy.map { transform($0) }, uniquingKeysWith: { first, _ in first })
}
| apache-2.0 | 768af358ae8b91c5484a9707274a2e17 | 32.725146 | 108 | 0.641928 | 4.31985 | false | false | false | false |
cpuu/OTT | OTT/Peripheral/PeripheralManagerServicesCharacteristicValuesViewController.swift | 1 | 5503 | //
// PeripheralManagerServicesCharacteristicValuesViewController.swift
// BlueCap
//
// Created by Troy Stribling on 8/20/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import UIKit
import BlueCapKit
import CoreBluetooth
class PeripheralManagerServicesCharacteristicValuesViewController : UITableViewController {
var characteristic: BCMutableCharacteristic!
var peripheralManagerViewController: PeripheralManagerViewController?
struct MainStoryboard {
static let peripheralManagerServiceCharacteristicEditValueSegue = "PeripheralManagerServiceCharacteristicEditValue"
static let peripheralManagerServiceCharacteristicEditDiscreteValuesSegue = "PeripheralManagerServiceCharacteristicEditDiscreteValues"
static let peripheralManagerServicesCharacteristicValueCell = "PeripheralManagerServicesCharacteristicValueCell"
}
required init?(coder aDecoder:NSCoder) {
super.init(coder:aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated:Bool) {
super.viewWillAppear(animated)
self.tableView.reloadData()
if let characteristic = self.characteristic {
self.navigationItem.title = characteristic.name
}
let future = self.characteristic.startRespondingToWriteRequests(10)
future.onSuccess {(request, _) in
if let value = request.value where value.length > 0 {
self.characteristic.value = request.value
self.characteristic.respondToRequest(request, withResult: CBATTError.Success)
self.updateWhenActive()
} else {
self.characteristic.respondToRequest(request, withResult :CBATTError.InvalidAttributeValueLength)
}
}
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PeripheralManagerServicesCharacteristicValuesViewController.didEnterBackground), name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.navigationItem.title = ""
NSNotificationCenter.defaultCenter().removeObserver(self)
self.characteristic.stopRespondingToWriteRequests()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == MainStoryboard.peripheralManagerServiceCharacteristicEditValueSegue {
let viewController = segue.destinationViewController as! PeripheralManagerServiceCharacteristicEditValueViewController
viewController.characteristic = self.characteristic
let selectedIndex = sender as! NSIndexPath
if let stringValues = self.characteristic?.stringValue {
let values = Array(stringValues.keys)
viewController.valueName = values[selectedIndex.row]
}
if let peripheralManagerViewController = self.peripheralManagerViewController {
viewController.peripheralManagerViewController = peripheralManagerViewController
}
} else if segue.identifier == MainStoryboard.peripheralManagerServiceCharacteristicEditDiscreteValuesSegue {
let viewController = segue.destinationViewController as! PeripheralManagerServiceCharacteristicEditDiscreteValuesViewController
viewController.characteristic = self.characteristic
if let peripheralManagerViewController = self.peripheralManagerViewController {
viewController.peripheralManagerViewController = peripheralManagerViewController
}
}
}
func didEnterBackground() {
BCLogger.debug()
if let peripheralManagerViewController = self.peripheralManagerViewController {
self.navigationController?.popToViewController(peripheralManagerViewController, animated: false)
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
if let values = self.characteristic?.stringValue {
return values.count
} else {
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(MainStoryboard.peripheralManagerServicesCharacteristicValueCell, forIndexPath: indexPath) as! CharacteristicValueCell
if let values = self.characteristic?.stringValue {
let characteristicValueNames = Array(values.keys)
let characteristicValues = Array(values.values)
cell.valueNameLabel.text = characteristicValueNames[indexPath.row]
cell.valueLable.text = characteristicValues[indexPath.row]
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if self.characteristic.stringValues.isEmpty {
self.performSegueWithIdentifier(MainStoryboard.peripheralManagerServiceCharacteristicEditValueSegue, sender:indexPath)
} else {
self.performSegueWithIdentifier(MainStoryboard.peripheralManagerServiceCharacteristicEditDiscreteValuesSegue, sender:indexPath)
}
}
}
| mit | e484923d202c866bed090d8effa7f4ee | 45.635593 | 227 | 0.72415 | 6.413753 | false | false | false | false |
rpistorello/rp-game-engine | rp-game-engine-src/Components/Component.swift | 1 | 1899 | //
// Component.swift
// rp-game-engine
//
// Created by Ricardo Pistorello on 02/12/15.
// Copyright © 2015 Ricardo Pistorello. All rights reserved.
//
import GameplayKit
@objc protocol ComponentProtocol {
var gameObject: GameObject? { get }
var transform: Transform? { get }
optional func Awake()
optional func Start()
}
extension GKComponent: ComponentProtocol {
var gameObject: GameObject? {
get{
guard let gameObject = self.entity as? GameObject else {
return nil
}
return gameObject
}
}
var transform: Transform? {
get {
return gameObject?.transform
}
}
internal func OnComponentAdded() {
}
}
extension GKEntity {
}
class Component: GKComponent {
var tag: String {
get{
return gameObject.tag
}
set {
gameObject.tag = newValue
}
}
internal var system: GKComponentSystem?
var active: Bool = true {
didSet {
}
}
override var gameObject: GameObject {
get{
guard let gameObject = self.entity as? GameObject else {
fatalError("Bad access component \(self.classForCoder)")
}
return gameObject
}
}
override var transform: Transform {
get {
return gameObject.transform
}
}
func detach() -> Component{
detachFromEntity()
detachFromSystem()
return self
}
func detachFromEntity() -> Component{
gameObject.removeComponentForClass(self.classForCoder)
return self
}
func detachFromSystem() -> Component{
system?.removeComponent(self)
system = nil
return self
}
override init() {
super.init()
}
}
| mit | 8914c0e48411fcd62f450bbf15c1d8f5 | 19.408602 | 72 | 0.549526 | 4.756892 | false | false | false | false |
cdtschange/SwiftMKit | SwiftMKit/Extension/NSLayoutConstraint+Extension.swift | 1 | 941 | //
// NSLayoutConstraint+Extension.swift
// SwiftMKitDemo
//
// Created by Mao on 4/20/16.
// Copyright © 2016 cdts. All rights reserved.
//
import Foundation
import UIKit
extension NSLayoutConstraint {
func setMultiplier(_ multiplier:CGFloat) -> NSLayoutConstraint {
let newConstraint = NSLayoutConstraint(
item: firstItem,
attribute: firstAttribute,
relatedBy: relation,
toItem: secondItem,
attribute: secondAttribute,
multiplier: multiplier,
constant: constant)
newConstraint.priority = priority
// newConstraint.shouldBeArchived = self.shouldBeArchived
// newConstraint.identifier = self.identifier
// newConstraint.active = self.active
NSLayoutConstraint.deactivate([self])
NSLayoutConstraint.activate([newConstraint])
return newConstraint
}
}
| mit | cf6ae941454694fdc8e6289cfdc49865 | 26.647059 | 68 | 0.639362 | 5.595238 | false | false | false | false |
phatblat/3DTouchDemo | 3DTouchDemo/MasterViewController+UIViewControllerPreviewing.swift | 1 | 2671 | //
// MasterViewController.swift
// 3DTouchDemo
//
// Created by Ben Chatelain on 9/28/15.
// Copyright © 2015 Ben Chatelain. All rights reserved.
//
import UIKit
extension MasterViewController: UIViewControllerPreviewingDelegate {
// MARK: - UIViewControllerPreviewingDelegate
/// Create a previewing view controller to be shown as a "Peek".
func previewingContext(previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
// Obtain the index path and the cell that was pressed.
guard let indexPath = tableView.indexPathForRowAtPoint(location),
cell = tableView.cellForRowAtIndexPath(indexPath) else { return nil }
if #available(iOS 9, *) {
// Set the source rect to the cell frame, so surrounding elements are blurred.
previewingContext.sourceRect = cell.frame
}
return viewControllerForIndexPath(indexPath)
}
/// Present the view controller for the "Pop" action.
func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit: UIViewController) {
// Reuse the "Peek" view controller for presentation.
showViewController(viewControllerToCommit, sender: self)
}
}
extension MasterViewController {
private func viewControllerForIndexPath(indexPath: NSIndexPath) -> UIViewController? {
switch indexPath.row {
case 0..<touchCanvasRow:
// Create a detail view controller and set its properties.
guard let detailViewController = storyboard?.instantiateViewControllerWithIdentifier("DetailViewController") as? DetailViewController else { return nil }
let previewDetail = sampleData[indexPath.row]
detailViewController.detailItemTitle = previewDetail.title
if let color = previewDetail.color {
detailViewController.view.backgroundColor = color
}
// Set the height of the preview by setting the preferred content size of the detail view controller.
// Width should be zero, because it's not used in portrait.
detailViewController.preferredContentSize = CGSize(width: 0.0, height: previewDetail.preferredHeight)
return detailViewController
case touchCanvasRow:
return storyboard?.instantiateViewControllerWithIdentifier("TouchCanvasViewController")
case touchCanvasRow + 1:
return storyboard?.instantiateViewControllerWithIdentifier("ForceProgressViewController")
default:
return nil
}
}
}
| mit | 4a3b75272d9df536b84b2d47b739ee6b | 37.695652 | 165 | 0.702996 | 6.040724 | false | false | false | false |
samodom/TestableCoreLocation | TestableCoreLocation/MutableVisit.swift | 1 | 3341 | //
// MutableVisit.swift
// TestableCoreLocation
//
// Created by Sam Odom on 3/6/17.
// Copyright © 2017 Swagger Soft. All rights reserved.
//
import CoreLocation
open class MutableVisit: CLVisit {
/// Mutable coordinate of a visit.
private var _coordinate: CLLocationCoordinate2D
open override var coordinate: CLLocationCoordinate2D {
get {
return _coordinate
}
set {
_coordinate = newValue
}
}
/// Mutable horizontal accuracy of a visit.
private var _horizontalAccuracy: CLLocationDistance
open override var horizontalAccuracy: CLLocationAccuracy {
get {
return _horizontalAccuracy
}
set {
_horizontalAccuracy = newValue
}
}
/// Mutable arrival date of a visit.
private var _arrivalDate = Date()
open override var arrivalDate: Date {
get {
return _arrivalDate
}
set {
guard newValue.compare(departureDate) != .orderedDescending else { return }
_arrivalDate = newValue
}
}
/// Mutable departure date of a visit.
private var _departureDate = Date()
open override var departureDate: Date {
get {
return _departureDate
}
set {
guard newValue.compare(arrivalDate) != .orderedAscending else { return }
_departureDate = newValue
}
}
public init(
coordinate: CLLocationCoordinate2D,
horizontalAccuracy: CLLocationDistance,
arrivalDate: Date,
departureDate: Date
) {
_coordinate = coordinate
_horizontalAccuracy = horizontalAccuracy
_arrivalDate = arrivalDate
_departureDate = departureDate
super.init()
}
private enum MutableVisitEncodingKey {
static let latitude = "latitude"
static let longitude = "longitude"
static let horizontalAccuracy = "horizontalAccuracy"
static let arrivalDate = "arrivalDate"
static let departureDate = "departureDate"
}
public required init?(coder: NSCoder) {
let latitude = coder.decodeDouble(forKey: MutableVisitEncodingKey.latitude)
let longitude = coder.decodeDouble(forKey: MutableVisitEncodingKey.longitude)
_coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
_horizontalAccuracy = coder.decodeDouble(forKey: MutableVisitEncodingKey.horizontalAccuracy)
if let arrival = coder.decodeObject(forKey: MutableVisitEncodingKey.arrivalDate) as? Date {
_arrivalDate = arrival
}
if let departure = coder.decodeObject(forKey: MutableVisitEncodingKey.departureDate) as? Date {
_departureDate = departure
}
super.init(coder: coder)
}
open override func encode(with coder: NSCoder) {
coder.encode(coordinate.latitude, forKey: MutableVisitEncodingKey.latitude)
coder.encode(coordinate.longitude, forKey: MutableVisitEncodingKey.longitude)
coder.encode(horizontalAccuracy, forKey: MutableVisitEncodingKey.horizontalAccuracy)
coder.encode(arrivalDate, forKey: MutableVisitEncodingKey.arrivalDate)
coder.encode(departureDate, forKey: MutableVisitEncodingKey.departureDate)
}
}
| mit | 7b83c0819b58fae9ebe6cfae25b06de6 | 29.363636 | 103 | 0.652096 | 5.276461 | false | false | false | false |
dinhchitrung/SAParallaxViewControllerSwift | SAParallaxViewControllerSwiftExample/Pods/SAParallaxViewControllerSwift/SAParallaxViewControllerSwift/SATransitionContainerView.swift | 2 | 4379 | //
// SATransitionContainerView.swift
// SAParallaxViewControllerSwiftExample
//
// Created by 鈴木大貴 on 2015/02/05.
// Copyright (c) 2015年 鈴木大貴. All rights reserved.
//
import UIKit
public class SATransitionContainerView: UIView {
public var views = [UIView]()
public var viewInitialPositions = [CGPoint]()
public var imageViewInitialFrame: CGRect!
public var blurImageViewInitialFrame: CGRect!
public var containerViewInitialFrame: CGRect!
public var containerView: SAParallaxContainerView!
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override init(frame: CGRect) {
super.init(frame: frame)
}
public override init() {
super.init()
}
public func setViews(#cells: [SAParallaxViewCell], view: UIView) {
for cell in cells {
let point = cell.superview!.convertPoint(cell.frame.origin, toView:view)
self.viewInitialPositions.append(point)
if cell.selected {
self.containerView = SAParallaxContainerView(frame: cell.containerView.bounds)
self.containerView.frame.origin = point
self.containerView.clipsToBounds = true
self.containerView.backgroundColor = .whiteColor()
self.containerViewInitialFrame = self.containerView.frame
self.containerView.setImage(cell.containerView.imageView.image!)
if let image = self.containerView.imageView.image {
self.containerView.imageView.frame = cell.containerView.imageView.frame
self.imageViewInitialFrame = self.containerView.imageView.frame
}
if let bluredImage = self.containerView.blurImageView.image {
self.containerView.blurImageView.frame = cell.containerView.blurImageView.frame
self.blurImageViewInitialFrame = self.containerView.blurImageView.frame;
}
self.views.append(self.containerView)
self.addSubview(self.containerView)
} else {
let imageView = cell.screenShot()
imageView.frame.origin = point
self.views.append(imageView)
self.addSubview(imageView)
}
}
}
public func openAnimation() {
let yPositionContainer = self.containerView.frame.origin.y
let containerViewHeight = self.containerView.frame.size.height
let height = self.frame.size.height
let distanceToTop = yPositionContainer
let distanceToBottom = height - (yPositionContainer + containerViewHeight)
for view in self.views {
if view != self.containerView {
var frame = view.frame
if frame.origin.y < yPositionContainer {
frame.origin.y -= distanceToTop
view.frame = frame
} else {
frame.origin.y += distanceToBottom
view.frame = frame
}
} else {
self.containerView.frame = self.bounds
self.containerView.imageView.frame = self.containerView.imageView.bounds
var rect = self.containerView.blurContainerView.frame
rect.origin.y = height - rect.size.height
self.containerView.blurContainerView.frame = rect
}
}
}
public func closeAnimation() {
for (index, view) in enumerate(self.views) {
if view != self.containerView {
let point = self.viewInitialPositions[index]
view.frame.origin = point
} else {
self.containerView.frame = self.containerViewInitialFrame
self.containerView.imageView.frame = self.imageViewInitialFrame
self.containerView.blurImageView.frame = self.blurImageViewInitialFrame
var rect = self.containerView.blurContainerView.frame
rect.origin.y = self.containerView.frame.size.height - rect.size.height
self.containerView.blurContainerView.frame = rect
}
}
}
}
| mit | 41219075af9fc551756f9cfce5360437 | 38.645455 | 99 | 0.595506 | 5.324786 | false | false | false | false |
baiyidjp/SwiftWB | SwiftWeibo/SwiftWeibo/Classes/View(视图和控制器)/Main/JPNavigationController.swift | 1 | 1776 | //
// JPNavigationController.swift
// SwiftWeibo
//
// Created by Keep丶Dream on 16/11/19.
// Copyright © 2016年 dongjiangpeng. All rights reserved.
//
import UIKit
class JPNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//隐藏系统 navigationBar
navigationBar.isHidden = true
}
/// 重写push方法 所有的push动作都会调用此方法
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
if childViewControllers.count > 0 {
//隐藏底部的tabBar
viewController.hidesBottomBarWhenPushed = true
//设置返回的按钮
if let vc = viewController as? JPBaseViewController {
var backTitle = "返回"
if childViewControllers.count == 1 {
backTitle = childViewControllers.first?.title ?? "返回"
}
let backItem = UIBarButtonItem(title: backTitle, target: self, action: #selector(popBack),isBackButton: true)
//为了向左缩进
let spaceItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
spaceItem.width = -10
vc.JPNavigationItem.leftBarButtonItems = [spaceItem,backItem]
}
}
super.pushViewController(viewController, animated: animated)
}
@objc fileprivate func popBack() {
popViewController(animated: true)
}
}
| mit | 127cb9927a2e5d0673d0307aec7987d5 | 28.086207 | 125 | 0.558388 | 5.623333 | false | false | false | false |
aslanyanhaik/Quick-Chat | QuickChat/Presenter/UIObjects/UIViewExtension.swift | 1 | 2205 | // MIT License
// Copyright (c) 2019 Haik Aslanyan
// 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
extension UIView {
@IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
@IBInspectable var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
@IBInspectable var borderColor: UIColor? {
get {
if let color = layer.borderColor {
return UIColor(cgColor: color)
}
return nil
}
set {
layer.borderColor = newValue?.cgColor
}
}
@IBInspectable var shadowColor: UIColor? {
get {
if let color = layer.shadowColor {
return UIColor(cgColor: color)
}
return nil
}
set {
layer.shadowColor = newValue?.cgColor
}
}
@IBInspectable var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
layer.shadowOffset = CGSize.zero
layer.shadowRadius = newValue
layer.shadowOpacity = 0.2
}
}
}
| mit | 39d37ed5985d966352a6d26f60576b1c | 26.5625 | 82 | 0.67483 | 4.509202 | false | false | false | false |
kousun12/RxSwift | RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift | 4 | 2196 | //
// RxScrollViewDelegateProxy.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/19/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
import UIKit
// Please take a look at `DelegateProxyType.swift`
class RxScrollViewDelegateProxy : DelegateProxy
, UIScrollViewDelegate
, DelegateProxyType {
private var _contentOffsetSubject: ReplaySubject<CGPoint>?
weak var scrollView: UIScrollView?
var contentOffsetSubject: Observable<CGPoint> {
if _contentOffsetSubject == nil {
let replaySubject = ReplaySubject<CGPoint>.create(bufferSize: 1)
_contentOffsetSubject = replaySubject
replaySubject.on(.Next(self.scrollView?.contentOffset ?? CGPointZero))
}
return _contentOffsetSubject!
}
required init(parentObject: AnyObject) {
self.scrollView = (parentObject as! UIScrollView)
super.init(parentObject: parentObject)
}
// delegate methods
func scrollViewDidScroll(scrollView: UIScrollView) {
if let contentOffset = _contentOffsetSubject {
contentOffset.on(.Next(scrollView.contentOffset))
}
self._forwardToDelegate?.scrollViewDidScroll?(scrollView)
}
// delegate proxy
override class func createProxyForObject(object: AnyObject) -> AnyObject {
let scrollView = (object as! UIScrollView)
return castOrFatalError(scrollView.rx_createDelegateProxy())
}
class func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) {
let collectionView: UIScrollView = castOrFatalError(object)
collectionView.delegate = castOptionalOrFatalError(delegate)
}
class func currentDelegateFor(object: AnyObject) -> AnyObject? {
let collectionView: UIScrollView = castOrFatalError(object)
return collectionView.delegate
}
deinit {
if let contentOffset = _contentOffsetSubject {
contentOffset.on(.Completed)
}
}
}
#endif
| mit | f8904a5c694f924015f7abb9be026715 | 28.675676 | 85 | 0.658015 | 5.573604 | false | false | false | false |
brentdax/swift | test/stdlib/simd_diagnostics.swift | 4 | 1696 | // RUN: %target-typecheck-verify-swift
// FIXME: No simd module on linux rdar://problem/20795411
// XFAIL: linux
import simd
let a = int4(0) + int4(0) // expected-error{{'+' has been renamed to '&+': integer vector types do not support checked arithmetic; use the wrapping operations instead}} {{17-18=&+}}
let b = int4(0) - int4(0) // expected-error{{'-' has been renamed to '&-': integer vector types do not support checked arithmetic; use the wrapping operations instead}} {{17-18=&-}}
let c = int4(0) * int4(0) // expected-error{{'*' has been renamed to '&*': integer vector types do not support checked arithmetic; use the wrapping operations instead}} {{17-18=&*}}
let x = int4(0) * (0 as Int32) // expected-error{{'*' has been renamed to '&*': integer vector types do not support checked arithmetic; use the wrapping operations instead}} {{17-18=&*}}
let y = (0 as Int32) * int4(0) // expected-error{{'*' has been renamed to '&*': integer vector types do not support checked arithmetic; use the wrapping operations instead}} {{22-23=&*}}
var d = int4(0)
d += int4(0) // expected-error{{'+=' is unavailable: integer vector types do not support checked arithmetic; use the wrapping operation 'x = x &+ y' instead}}
d -= int4(0) // expected-error{{'-=' is unavailable: integer vector types do not support checked arithmetic; use the wrapping operation 'x = x &- y' instead}}
d *= int4(0) // expected-error{{'*=' is unavailable: integer vector types do not support checked arithmetic; use the wrapping operation 'x = x &* y' instead}}
d *= 0 // expected-error{{'*=' is unavailable: integer vector types do not support checked arithmetic; use the wrapping operation 'x = x &* y' instead}}
| apache-2.0 | 6580d0336b7051f3e0b7e691422b836d | 88.263158 | 186 | 0.693396 | 3.743929 | false | false | false | false |
nakau1/NeroBlu | NeroBlu/NB+CGGeometry.swift | 1 | 9672 | // =============================================================================
// NerobluCore
// Copyright (C) NeroBlu. All rights reserved.
// =============================================================================
import UIKit
/// CGRectZeroの短縮形
public let cr0 = CGRect.zero
/// CGPointZeroの短縮形
public let cp0 = CGPoint.zero
/// CGSizeZeroの短縮形
public let cs0 = CGSize.zero
// MARK: - CGRect拡張 -
public extension CGRect {
// MARK: 値の設定/取得
/// 値を設定する
/// - parameter x: X座標
/// - parameter y: Y座標
/// - parameter w: 幅
/// - parameter h: 高さ
public mutating func update<T>(x: T? = nil, y: T? = nil, w: T? = nil, h: T? = nil) {
self.origin = CGPoint(
x: (x != nil) ? CGFloat.cast(x!) : self.origin.x,
y: (y != nil) ? CGFloat.cast(y!) : self.origin.y
)
self.size = CGSize(
width: (w != nil) ? CGFloat.cast(w!) : self.size.width,
height: (h != nil) ? CGFloat.cast(h!) : self.size.height
)
}
/// サイズをCGSizeZeroに変更する
/// - returns: 変更後のCGRect
public mutating func toSizeZero() -> CGRect {
self.size = CGSize.zero
return self
}
/// 位置をCGPointZeroに変更する
/// - returns: 変更後のCGRect
public mutating func toOriginZero() -> CGRect {
self.origin = CGPoint.zero
return self
}
/// CGSize (sizeのエイリアス)
public var s: CGSize {
get { return self.size }
set(v) { self.size = v }
}
/// CGPoint (originのエイリアス)
public var o: CGPoint {
get { return self.origin }
set(v) { self.origin = v }
}
/// CGPoint (originのエイリアス)
public var p: CGPoint {
get { return self.origin }
set(v) { self.origin = v }
}
/// X座標 (leftのエイリアス)
public var x: CGFloat {
get { return self.origin.x }
set(v) { self.update(x: v) }
}
/// Y座標 (topのエイリアス)
public var y: CGFloat {
get { return self.origin.y }
set(v) { self.update(y: v) }
}
/// 幅 (widthのエイリアス)
public var w: CGFloat {
get { return self.size.width }
set(v) { self.update(w: v) }
}
/// 高さ (heightのエイリアス)
public var h: CGFloat {
get { return self.size.height }
set(v) { self.update(h: v) }
}
/// 右端座標 (rightのエイリアス)
public var r: CGFloat {
get { return self.maxX }
set(v) { self.update(w: v - self.x) }
}
/// 下端座標 (bottomのエイリアス)
public var b: CGFloat {
get { return self.maxY }
set(v) { self.update(h: v - self.y) }
}
/// 水平中央座標 (centerXのエイリアス)
public var cx: CGFloat {
get { return self.midX }
set(v) { self.update(x: v - (self.width / 2)) }
}
/// 垂直中央座標 (centerYのエイリアス)
public var cy: CGFloat {
get { return self.midY }
set(v) { self.update(y: v - (self.height / 2)) }
}
/// X座標
public var left: CGFloat { get { return self.x } set(v) { self.x = v } }
/// Y座標
public var top: CGFloat { get { return self.y } set(v) { self.y = v } }
/// 右端座標
public var right: CGFloat { get { return self.r } set(v) { self.r = v } }
/// 下端座標
public var bottom: CGFloat { get { return self.b } set(v) { self.b = v } }
/// 水平中央座標
public var centerX: CGFloat { get { return self.cx } set(v) { self.cx = v } }
/// 垂直中央座標
public var centerY: CGFloat { get { return self.cy } set(v) { self.cy = v } }
// MARK: イニシャライザ
/// イニシャライザ
/// - parameter x: X座標
/// - parameter y: Y座標
/// - parameter width: 幅
/// - parameter height: 高さ
public init<T>(_ x: T, _ y: T, _ width: T, _ height: T) {
self.origin = CGPoint(x: CGFloat.cast(x), y: CGFloat.cast(y))
self.size = CGSize(width: CGFloat.cast(width), height: CGFloat.cast(height))
}
/// イニシャライザ
/// - parameter x: X座標
/// - parameter y: Y座標
/// - parameter size: サイズ
public init<T>(x: T, y: T, size: CGSize = CGSize.zero) {
self.origin = CGPoint(x: CGFloat.cast(x), y: CGFloat.cast(y))
self.size = size
}
/// イニシャライザ
/// - parameter width: 幅
/// - parameter height: 高さ
/// - parameter origin: 位置
public init<T>(width: T, height: T, origin: CGPoint = CGPoint.zero) {
self.origin = origin
self.size = CGSize(width: CGFloat.cast(width), height: CGFloat.cast(height))
}
/// イニシャライザ
/// - parameter w: 幅
/// - parameter h: 高さ
public init<T>(_ w: T, _ h: T) {
self.init(width: w, height: h)
}
/// イニシャライザ
/// - parameter size: サイズ
public init(size: CGSize) {
self.origin = CGPoint.zero
self.size = size
}
/// イニシャライザ
/// - parameter orgin: 位置
public init(origin: CGPoint) {
self.origin = origin
self.size = CGSize.zero
}
/// イニシャライザ
/// - parameter center: 中央位置
/// - parameter size: サイズ
public init(center: CGPoint, size: CGSize) {
self.size = size
self.origin = CGPoint.zero
self.centerX = center.x
self.centerY = center.y
}
}
// MARK: - CGSize拡張 -
public extension CGSize {
// MARK: 値の設定/取得
/// 幅 (widthのエイリアス)
public var w: CGFloat {
get { return self.width }
set(v) { self.width = v }
}
/// 高さ (heightのエイリアス)
public var h: CGFloat {
get { return self.height }
set(v) { self.height = v }
}
// MARK: 値の反転
/// 幅と高さを入れ替える
/// - returns: 自身
public mutating func reverse() -> CGSize {
let w = self.width, h = self.height
self.width = h; self.height = w
return self
}
// MARK: イニシャライザ
/// イニシャライザ
/// - parameter width: 幅
/// - parameter height: 高さ
public init<T>(_ w: T, _ h: T) {
self.init(width: CGFloat.cast(w), height: CGFloat.cast(h))
}
/// イニシャライザ(正方形)
/// - parameter width: 正方形一辺の幅
public init<T>(_ width: T) {
let widthOfSide = CGFloat.cast(width)
self.init(width: widthOfSide, height: widthOfSide)
}
}
// MARK: - CGPoint拡張 -
public extension CGPoint {
// MARK: 値の反転
/// X座標とY座標を入れ替える
/// - returns: 自身
public mutating func reverse() -> CGPoint {
let x = self.x, y = self.y
self.x = y; self.y = x
return self
}
// MARK: イニシャライザ
/// イニシャライザ
/// - parameter x: X座標
/// - parameter y: Y座標
public init<T>(_ x: T, _ y: T) {
self.init(x: CGFloat.cast(x), y: CGFloat.cast(y))
}
}
// MARK: - CGRect作成関数 -
/// CGRectを作成する
/// - parameter x: X座標
/// - parameter y: Y座標
/// - parameter width: 幅
/// - parameter height: 高さ
/// - returns: CGRect
public func cr<T>(_ x: T, _ y: T, _ width: T, _ height: T) -> CGRect {
return CGRect(x, y, width, height)
}
/// CGRectを作成する
/// - parameter x: X座標
/// - parameter y: Y座標
/// - parameter size: サイズ
/// - returns: CGRect
public func cr<T>(x: T, y: T, size: CGSize = CGSize.zero) -> CGRect {
return CGRect(x: x, y: y, size: size)
}
/// CGRectを作成する
/// - parameter width: 幅
/// - parameter height: 高さ
/// - parameter origin: 位置
/// - returns: CGRect
public func cr<T>(width: T, height: T, origin: CGPoint = CGPoint.zero) -> CGRect {
return CGRect(width: width, height: height, origin: origin)
}
/// CGRectを作成する
/// - parameter w: 幅
/// - parameter h: 高さ
/// - returns: CGRect
public func cr<T>(_ w: T, _ h: T) -> CGRect {
return CGRect(w, h)
}
/// CGRectを作成する
/// - parameter size: サイズ
/// - returns: CGRect
public func cr(_ size: CGSize) -> CGRect {
return CGRect(size: size)
}
/// CGRectを作成する
/// - parameter orgin: 位置
/// - returns: CGRect
public func cr(_ origin: CGPoint) -> CGRect {
return CGRect(origin: origin)
}
/// CGRectを作成する
/// - parameter origin: 位置
/// - parameter size: サイズ
/// - returns: CGRect
public func cr(origin: CGPoint, size: CGSize) -> CGRect {
return CGRect(origin: origin, size: size)
}
/// CGRectを作成する
/// - parameter center: 中央位置
/// - parameter size: サイズ
/// - returns: CGRect
public func cr(center: CGPoint, size: CGSize) -> CGRect {
return CGRect(center: center, size: size)
}
// MARK: - CGPoint作成関数 -
/// CGPointを作成する
/// - parameter x: X座標
/// - parameter y: Y座標
/// - returns: CGPoint
public func cp<T>(_ x: T, _ y: T) -> CGPoint {
return CGPoint(x, y)
}
// MARK: - CGSize作成関数 -
/// CGSizeを作成する
/// - parameter width: 幅
/// - parameter height: 高さ
/// - returns: CGSize
public func cs<T>(_ width: T, _ height: T) -> CGSize {
return CGSize(width, height)
}
| mit | 9f3b1e9b9d199daf27471917d64b1430 | 23.874286 | 88 | 0.527223 | 3.182018 | false | false | false | false |
twtstudio/WePeiYang-iOS | WePeiYang/YellowPage/CommonView.swift | 1 | 1734 | //
// CommonView.swift
// YellowPage
//
// Created by Halcao on 2017/2/22.
// Copyright © 2017年 Halcao. All rights reserved.
//
import UIKit
class CommonView: UIView {
var collectionView: UICollectionView! = nil
var models: [ClientItem] = []
// FIXME: fix init
convenience init(with models: [ClientItem]) {
self.init()
self.models = models
self.backgroundColor = UIColor.white
let layout = UICollectionViewFlowLayout()
let width = UIScreen.main.bounds.size.width
let headerLabel = UILabel(frame: CGRect(x: 15, y: 20, width: 0, height: 0))
headerLabel.text = "常用部门"
headerLabel.font = UIFont.systemFont(ofSize: 15)
headerLabel.sizeToFit()
collectionView = UICollectionView(frame: CGRect(x: 0, y: headerLabel.frame.size.height+30, width: width, height: 150), collectionViewLayout: layout)
// initial fix
//collectionView.contentInset = UIEdgeInsetsMake(-20, 0, 0, 0)
//collectionView.contentSize = CGSize(width: width, height: 150)
collectionView.backgroundColor = UIColor.white
collectionView.register(CommonClientCell.self, forCellWithReuseIdentifier: "CommonClientCell")
// collectionView.delegate = self
// collectionView.dataSource = self
layout.itemSize = CGSize(width: (width-50)/2, height: 40)
self.addSubview(headerLabel)
self.addSubview(collectionView)
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
| mit | 7de3d9f13b8626c202fd529c8aac4a95 | 31.509434 | 156 | 0.645386 | 4.558201 | false | false | false | false |
niunaruto/DeDaoAppSwift | testSwift/Pods/Kingfisher/Sources/Networking/SessionDelegate.swift | 3 | 9083 | //
// SessionDelegate.swift
// Kingfisher
//
// Created by Wei Wang on 2018/11/1.
//
// Copyright (c) 2019 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// Represents the delegate object of downloader session. It also behave like a task manager for downloading.
class SessionDelegate: NSObject {
typealias SessionChallengeFunc = (
URLSession,
URLAuthenticationChallenge,
(URLSession.AuthChallengeDisposition, URLCredential?) -> Void
)
typealias SessionTaskChallengeFunc = (
URLSession,
URLSessionTask,
URLAuthenticationChallenge,
(URLSession.AuthChallengeDisposition, URLCredential?) -> Void
)
private var tasks: [URL: SessionDataTask] = [:]
private let lock = NSLock()
let onValidStatusCode = Delegate<Int, Bool>()
let onDownloadingFinished = Delegate<(URL, Result<URLResponse, KingfisherError>), Void>()
let onDidDownloadData = Delegate<SessionDataTask, Data?>()
let onReceiveSessionChallenge = Delegate<SessionChallengeFunc, Void>()
let onReceiveSessionTaskChallenge = Delegate<SessionTaskChallengeFunc, Void>()
func add(
_ dataTask: URLSessionDataTask,
url: URL,
callback: SessionDataTask.TaskCallback) -> DownloadTask
{
lock.lock()
defer { lock.unlock() }
// Create a new task if necessary.
let task = SessionDataTask(task: dataTask)
task.onCallbackCancelled.delegate(on: self) { [unowned task] (self, value) in
let (token, callback) = value
let error = KingfisherError.requestError(reason: .taskCancelled(task: task, token: token))
task.onTaskDone.call((.failure(error), [callback]))
// No other callbacks waiting, we can clear the task now.
if !task.containsCallbacks {
let dataTask = task.task
self.remove(dataTask)
}
}
let token = task.addCallback(callback)
tasks[url] = task
return DownloadTask(sessionTask: task, cancelToken: token)
}
func append(
_ task: SessionDataTask,
url: URL,
callback: SessionDataTask.TaskCallback) -> DownloadTask
{
let token = task.addCallback(callback)
return DownloadTask(sessionTask: task, cancelToken: token)
}
private func remove(_ task: URLSessionTask) {
guard let url = task.originalRequest?.url else {
return
}
lock.lock()
defer {lock.unlock()}
tasks[url] = nil
}
private func task(for task: URLSessionTask) -> SessionDataTask? {
guard let url = task.originalRequest?.url else {
return nil
}
lock.lock()
defer { lock.unlock() }
guard let sessionTask = tasks[url] else {
return nil
}
guard sessionTask.task.taskIdentifier == task.taskIdentifier else {
return nil
}
return sessionTask
}
func task(for url: URL) -> SessionDataTask? {
lock.lock()
defer { lock.unlock() }
return tasks[url]
}
func cancelAll() {
lock.lock()
let taskValues = tasks.values
lock.unlock()
for task in taskValues {
task.forceCancel()
}
}
func cancel(url: URL) {
lock.lock()
let task = tasks[url]
lock.unlock()
task?.forceCancel()
}
}
extension SessionDelegate: URLSessionDataDelegate {
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)
{
guard let httpResponse = response as? HTTPURLResponse else {
let error = KingfisherError.responseError(reason: .invalidURLResponse(response: response))
onCompleted(task: dataTask, result: .failure(error))
completionHandler(.cancel)
return
}
let httpStatusCode = httpResponse.statusCode
guard onValidStatusCode.call(httpStatusCode) == true else {
let error = KingfisherError.responseError(reason: .invalidHTTPStatusCode(response: httpResponse))
onCompleted(task: dataTask, result: .failure(error))
completionHandler(.cancel)
return
}
completionHandler(.allow)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
guard let task = self.task(for: dataTask) else {
return
}
task.didReceiveData(data)
if let expectedContentLength = dataTask.response?.expectedContentLength, expectedContentLength != -1 {
let dataLength = Int64(task.mutableData.count)
DispatchQueue.main.async {
task.callbacks.forEach { callback in
callback.onProgress?.call((dataLength, expectedContentLength))
}
}
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
guard let sessionTask = self.task(for: task) else { return }
if let url = task.originalRequest?.url {
let result: Result<URLResponse, KingfisherError>
if let error = error {
result = .failure(KingfisherError.responseError(reason: .URLSessionError(error: error)))
} else if let response = task.response {
result = .success(response)
} else {
result = .failure(KingfisherError.responseError(reason: .noURLResponse(task: sessionTask)))
}
onDownloadingFinished.call((url, result))
}
let result: Result<(Data, URLResponse?), KingfisherError>
if let error = error {
result = .failure(KingfisherError.responseError(reason: .URLSessionError(error: error)))
} else {
if let data = onDidDownloadData.call(sessionTask), let finalData = data {
result = .success((finalData, task.response))
} else {
result = .failure(KingfisherError.responseError(reason: .dataModifyingFailed(task: sessionTask)))
}
}
onCompleted(task: task, result: result)
}
func urlSession(
_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
onReceiveSessionChallenge.call((session, challenge, completionHandler))
}
func urlSession(
_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
onReceiveSessionTaskChallenge.call((session, task, challenge, completionHandler))
}
func urlSession(
_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void)
{
guard let sessionDataTask = self.task(for: task),
let redirectHandler = Array(sessionDataTask.callbacks).last?.options.redirectHandler else
{
completionHandler(request)
return
}
redirectHandler.handleHTTPRedirection(
for: sessionDataTask,
response: response,
newRequest: request,
completionHandler: completionHandler)
}
private func onCompleted(task: URLSessionTask, result: Result<(Data, URLResponse?), KingfisherError>) {
guard let sessionTask = self.task(for: task) else {
return
}
remove(task)
sessionTask.onTaskDone.call((result, sessionTask.callbacks))
}
}
| mit | f8e7720650be79d7fd4a222e80f10205 | 34.901186 | 113 | 0.638005 | 5.120068 | false | false | false | false |
mikina/Simple-custom-tab-bar | TabBarExample/SimpleCustomTabBar/SimpleCustomTabBar/CustomNavigationController.swift | 1 | 3109 | //
// CustomNavigationController.swift
// SimpleCustomTabBar
//
// Created by Mike Mikina on 3/28/16.
// Copyright © 2016 FDT. All rights reserved.
//
import UIKit
class CustomNavigationController: UINavigationController, UINavigationControllerDelegate, UIGestureRecognizerDelegate, SwipeBackPositionProtocol {
var positionClosure: ((position: Int)->())?
var duringPushAnimation = false
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
self.interactivePopGestureRecognizer?.delegate = self
self.interactivePopGestureRecognizer?.addTarget(self, action: #selector(CustomNavigationController.backAction(_:)))
}
func backAction(gesture: UIPanGestureRecognizer) {
if let position = self.positionClosure, let gestureView = gesture.view {
let translation = gesture.translationInView(gestureView)
position(position: Int(translation.x))
}
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
// When interactivePopGestureRecognizer delegate is set, we need to check if
// navigation controller has more than one vc. If not don't perform edge pan back gesture.
func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer.isKindOfClass(UIScreenEdgePanGestureRecognizer.self)
&& self.viewControllers.count == 1 {
return false
}
if self.duringPushAnimation {
return false
}
return true
}
func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
// We send notification when transition is started, it's possible to cancel transition when
// user just start swipe back and cancel it. In this case tab bar will be shown when it's not suppose to.
// It's possible to check in transition coordinator if swipe back is not canceled.
if let coordinator = navigationController.topViewController?.transitionCoordinator() {
coordinator.notifyWhenInteractionEndsUsingBlock({ (context) in
if context.isCancelled() {
if let position = self.positionClosure {
position(position: 0)
}
}
})
}
NSNotificationCenter.defaultCenter().postNotificationName(kPageHasStartedTransition, object: viewController, userInfo: nil)
}
func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) {
NSNotificationCenter.defaultCenter().postNotificationName(kPageHasStartedTransition, object: viewController, userInfo: nil)
self.duringPushAnimation = false
}
override func pushViewController(viewController: UIViewController, animated: Bool) {
super.pushViewController(viewController, animated: animated)
self.duringPushAnimation = true
}
deinit {
self.delegate = nil
self.interactivePopGestureRecognizer?.delegate = nil
}
}
| mit | c97db9a97a4ab61a16d25296c8edec29 | 38.846154 | 170 | 0.755148 | 5.610108 | false | false | false | false |
JuanjoArreola/Logg | Sources/Logg/LogLevel.swift | 1 | 516 | import Foundation
public struct LogLevel: OptionSet {
public let rawValue: Int
public static let debug = LogLevel(rawValue: 1 << 0)
public static let info = LogLevel(rawValue: 1 << 1)
public static let error = LogLevel(rawValue: 1 << 2)
public static let fault = LogLevel(rawValue: 1 << 3)
public static let all: LogLevel = [.debug, .info, .error, .fault]
public static let none: LogLevel = []
public init(rawValue: Int) {
self.rawValue = rawValue
}
}
| mit | e5e36e7bb3b72a3742bf38e90259fba7 | 29.352941 | 69 | 0.637597 | 4.128 | false | false | false | false |
kobe41999/transea-mumble | Source/Classes/NCCU/CallHistory/NCallHistory.swift | 1 | 3966 | //
// CallHistory.swift
// Mumble
//
// Created by William on 2017/4/27.
//
//
import UIKit
import Parse
class CallHistory: UITableViewController {
var hist = [Any]()
override func viewDidLoad() {
super.viewDidLoad()
hist = [Any]()
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
override func viewWillAppear(_ animated: Bool) {
load()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return hist.count
}
func load() {
let query = PFQuery(className: "CallHistory")
//[query addAscendingOrder:@"createdAt"];
query.addDescendingOrder("createdAt")
query.findObjectsInBackground(block: {(_ objects: [PFObject], _ error: Error?) -> Void in
if error == nil {
for object: PFObject in objects{
let expert: String = object["expert"] as! String
let caller:String=object["caller"] as! String
let score = object["score"]
let duration = object["duration"]
print("\(expert)")
print("(CDouble(duration))")
let callHist = CallHistoryObj()
callHist.expert = expert
callHist.rating = score as? NSNumber
callHist.duration = duration as? NSNumber
callHist.date = object.updatedAt
self.hist.append(callHist)
}
self.tableView.reloadData()
}
else {
print("error..")
}
} as! ([PFObject]?, Error?) -> Void)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: HistoryCellTableViewCell? = tableView.dequeueReusableCell(withIdentifier: "histCell", for: indexPath) as? HistoryCellTableViewCell
if cell == nil {
cell = HistoryCellTableViewCell(style: .default, reuseIdentifier: "histCell")
}
let callObj: CallHistoryObj? = (hist[indexPath.row] as? CallHistoryObj)
cell?.labelExpert?.text = callObj?.expert
cell?.rating?.value = CGFloat(CDouble((callObj?.rating)!))
print("duration=\(Int((callObj?.duration)!))")
cell?.labelDuration?.text = timeFormatted(Int(CDouble((callObj?.duration)!)))
var dateFormatter = DateFormatter()
// here we create NSDateFormatter object for change the Format of date..
dateFormatter.dateFormat = "yyyy-MM-dd"
//// here set format of date which is in your output date (means above str with format)
dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
// here set format which you want...
let convertedString: String? = dateFormatter.string(from: (callObj?.date)!)
//here convert date in NSString
print("Converted String : \(String(describing: convertedString))")
cell?.labelDate?.text = convertedString
return cell!
}
func timeFormatted(_ totalSeconds: Int) -> String {
let seconds: Int = totalSeconds % 60
let minutes: Int = (totalSeconds / 60) % 60
let hours: Int = totalSeconds / 3600
return String(format: "%02d:%02d", minutes, seconds)
}
}
| bsd-3-clause | 23e8c00263b79f8e6a43de9ab119a05b | 38.267327 | 148 | 0.599849 | 5.078105 | false | false | false | false |
garricn/secret | FLYR/FeedVM.swift | 1 | 4145 | //
// FeedVM.swift
// FLYR
//
// Created by Garric Nahapetian on 8/1/16.
// Copyright © 2016 Garric Nahapetian. All rights reserved.
//
import UIKit
import Bond
import CloudKit
struct FeedVM: FlyrViewModeling {
let alertOutput = EventProducer<UIAlertController>()
let output = ObservableArray<Flyr>()
let flyrFetcher: FlyrFetchable
let doneLoadingOutput = EventProducer<Void>()
let locationManager: LocationManageable
init(flyrFetcher: FlyrFetchable, locationManager: LocationManageable) {
self.flyrFetcher = flyrFetcher
self.locationManager = locationManager
self.flyrFetcher
.output
.observe {
self.output.removeAll()
self.output.extend($0)
self.doneLoadingOutput.next()
}
self.flyrFetcher.errorOutput.observe { error in
let alert: UIAlertController
if let error = error {
alert = makeAlert(
title: "Error Fetching Flyrs",
message: "Error: \(error)"
)
} else {
alert = makeAlert(
title: "Error Fetching Flyrs",
message: "Unknown Error"
)
}
self.alertOutput.next(alert)
}
}
func refresh() {
self.locationManager.requestLocation { response in
if case .DidUpdateLocations(let locations) = response {
let query = self.makeQuery(from: locations)
self.flyrFetcher.fetch(with: query)
} else {
let alert: UIAlertController
switch response {
case .ServicesNotEnabled:
alert = makeAlert(
title: "Location Services Disabled",
message: "You can enable location services in Settings > Privacy."
)
case .AuthorizationDenied:
alert = makePreferredLocationAlert()
case .AuthorizationRestricted:
alert = makeAlert(
title: "Authorization Restricted",
message: "Location services are restricted on this device."
)
case .DidFail(let error):
alert = makeAlert(
title: "Location Services Error",
message: "Error: \(error)."
)
default:
alert = makeAlert(
title: "Location Services Error",
message: "There was an error."
)
}
self.alertOutput.next(alert)
}
}
}
private func makeQuery(from locations: [CLLocation]) -> CKQuery {
let location = locations.last!
let radius: CGFloat = 100000000.0
let format = "(distanceToLocation:fromLocation:(location, %@) < %f)"
let predicate = NSPredicate(
format: format,
location,
radius
)
return CKQuery(recordType: "Flyr", predicate: predicate)
}
}
func makePreferredLocationAlert() -> UIAlertController {
let alert = makeAlert(title: "Authorization Denied", message: "You denied location services authorization.")
let setPreferredLocationAction = UIAlertAction(
title: "Set Preferred Location",
style: .Default,
handler: { _ in AppCoordinator.sharedInstance.locationButtonTapped() })
alert.addAction(setPreferredLocationAction)
return alert
}
func makeAlert(from error: ErrorType?) -> UIAlertController {
return makeAlert(title: "Error", message: "\(error)")
}
func makeAlert(title title: String?, message: String?) -> UIAlertController {
let okAction = UIAlertAction(
title: "OK",
style: .Default,
handler: nil
)
let alert = UIAlertController(
title: title,
message: message,
preferredStyle: .Alert
)
alert.addAction(okAction)
return alert
}
| mit | 72822fd3668a56961e9bfc5e8d09ed67 | 31.124031 | 112 | 0.549469 | 5.238938 | false | false | false | false |
MrPudin/Skeem | IOS/Prevoir/SKMDatabase.swift | 1 | 14749 | //
// SKMDatabase.swift
// Skeem
//
// Created by Zhu Zhan Yan on 13/10/16.
// Copyright © 2016 SSTInc. All rights reserved.
//
import UIKit
/*
* public enum SKMDBKey:String
* - Defines key of virtual storage Locations
*/
public enum SKMDBKey:String
{
//Persistent File
case task = "pvrdb_task" //Task Location
case void_duration = "pvrdb_voidduration" //Void Duration Location
//Temp File
case cache = "pvrdb_cache" //Cache Location
//Not Saved
case mcache = "pvrdb_mcache" //Memory Only Cache
}
/*
* public enum SKMDBError:Error
* - Defines errors that may occur when using SKMDatabase
*/
public enum SKMDBError:Error
{
case entry_exist //Entry already exist
case entry_not_exist //Entry does not exist
case entry_modified //An Entry has been modified but not safed
}
/*
* public enum SKMDBFileError:Error
* - Defines errors that may occur when using SKMDBFile
*/
public enum SKMDBFileError:Error
{
case file_not_exist //File does not exist
case file_exist //File Already exists
case file_unreadable //File is not readable. An unkown I/O error occured.
case data_staged //Data has already been staged
}
/*
* public class SKMDBFile:NSObject
* - Defines an object that represents a database file
* - Performs I/O Operations
*/
public class SKMDBFile:NSObject
{
//Properties
//Storage
public private(set) var file_path:String //Path to file of the object
private var data:NSMutableData = NSMutableData() //Data of the archive
private var unach:NSKeyedUnarchiver! //Unarchiver
private var ach:NSKeyedArchiver! //Archiver
//Status
var staged:Bool = false //Whether data has been staged
/*
* init(file_path:String)
* [Argument]
* file_path - Path to file of the object.
*/
init(file_path:String = "")
{
self.file_path = file_path
super.init()
do
{
try self.load()
}
catch SKMDBFileError.file_not_exist
{
print("Info:SKMDBFile: File does not exist, assumming new file")
}
catch SKMDBFileError.file_unreadable
{
print("FATAL:SKMDBFile: File not readable")
abort()
}
catch
{
print("FATAL:SKMDBFile: Unknown Error")
abort()
}
}
/*
* public func stage(key:SKMDBKey,data:Any)
* - Stage data for writing
* [Arguments]
* key - Virtual Storage Location to store data
* data - Data to store for key
*/
public func stage(key:SKMDBKey,data:Any)
{
if self.staged == false
{
//New Stage
self.data = NSMutableData()
self.ach = NSKeyedArchiver(forWritingWith: self.data)
self.staged = true
}
self.ach.encode(data, forKey: key.rawValue)
}
/*
* public func retrieve(key:SKMDBKey) throws -> Any
* - Retrieve data from virtual storage location
* [Argument]
* key - Virtual storage location to retrieve from
* [Return]
* Any - Data retrieved
* [Exception]
* SKMDBFileError.data_staged - Changes have been staged
*/
public func retrieve(key:SKMDBKey) throws -> Any
{
if self.staged == true
{
throw SKMDBFileError.data_staged
}
return self.unach.decodeObject(forKey: key.rawValue)!
}
/*
* public func commit()
* - (Over)Write changes staged to disk
*/
public func commit()
{
if self.staged == true
{
if FileManager.default.fileExists(atPath: self.file_path)
{
try! FileManager.default.removeItem(atPath: self.file_path)
}
//Write Data
self.ach.finishEncoding()
self.data.write(toFile: self.file_path, atomically: true)
self.staged = false
}
}
/*
* public func load() throws
* - Load data from disk
* [Error]
* SKMDBFileError.data_staged - Changes have been staged
* SKMDBFileError.file_unreadable - File is unreadable, an unknown I/O error occured
* SKMDBFileError.file_not_exist - File does not exist
*/
public func load() throws
{
if self.staged == true
{
throw SKMDBFileError.data_staged
}
if FileManager.default.fileExists(atPath: self.file_path) == true
{
if let dat = NSMutableData(contentsOfFile: self.file_path)
{
//Data Read Successful
self.data = dat
self.unach = NSKeyedUnarchiver(forReadingWith: (self.data as Data))
}
else
{
throw SKMDBFileError.file_unreadable
}
}
else
{
throw SKMDBFileError.file_not_exist
}
}
}
public class SKMDatabase:NSObject
{
//Properties
//Data
private var task:[String:SKMTask] //Tasks
private var voidDuration:[String:SKMVoidDuration] //Void Duration
private var mcache:[String:Any] //In-Memory Cache
private var cache:[String:NSCoding] //Cache
//Storage
private var pst_file:SKMDBFile
private var tmp_file:SKMDBFile
//Status
internal var modified:Bool
//Methods
//Init
override init()
{
//Persistent Storage
let doc_path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]
self.pst_file = SKMDBFile(file_path: "\(doc_path)/skm_pst.plist")
//Cache (Tmp Storage)
let tmp_path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]
self.tmp_file = SKMDBFile(file_path: "\(tmp_path)/skm_cache.plist")
self.task = [:]
self.voidDuration = [:]
self.mcache = [:]
self.cache = [:]
self.modified = false
super.init()
}
//I/O
/*
* public func load() throws
* - Loads all data from SKMDBFile, or inits data
* [Exception]
* SKMDBError.entry_modified - An Entry has been modified
*/
public func load() throws
{
if self.modified == false
{
//Persistent Storage
do
{
try self.pst_file.load()
self.task = (try! self.pst_file.retrieve(key: SKMDBKey.task) as! [String : SKMTask])
self.voidDuration = (try! self.pst_file.retrieve(key: SKMDBKey.void_duration) as! [String:SKMDuration] as! [String : SKMVoidDuration])
}
catch SKMDBFileError.file_not_exist
{
self.task = [:]
}
catch
{
abort()
}
//Temporary Storage
do
{
try self.tmp_file.load()
if let cch = (try? self.tmp_file.retrieve(key: SKMDBKey.cache) as! [String:NSCoding])
{
self.cache = cch
}
else
{
self.cache = [:]
}
}
catch SKMDBFileError.file_not_exist
{
self.cache = [:]
}
catch
{
abort()
}
}
else
{
throw SKMDBError.entry_modified
}
}
/*
* public func commit()
* - Commit changes to disk.
*/
public func commit()
{
if self.modified == true
{
//Persistent File
self.pst_file.stage(key: SKMDBKey.task, data: self.task)
self.pst_file.stage(key: SKMDBKey.void_duration, data: self.voidDuration)
self.pst_file.commit()
//Temporary File
self.tmp_file.stage(key: SKMDBKey.cache, data: self.cache)
self.tmp_file.commit()
}
}
/*
* public func createEntry(locKey:SKMDBKey,key:String,val:Any) throws
* - Creates an entry in the virtual storage location specifed by loc key
* [Argument]
* lockey - Virtual storage location to store entry
* key - Unique Identifier for the entry
* val - Value of the entry
* [Exception]
* SKMDBError.entry_exist - An entry already exists under the key
*/
public func createEntry(locKey:SKMDBKey,key:String,val:Any) throws
{
if locKey == SKMDBKey.task
{
if self.task[key] == nil
{
self.task[key] = (val as! SKMTask)
}
else
{
throw SKMDBError.entry_exist
}
}
else if locKey == SKMDBKey.void_duration
{
if self.voidDuration[key] == nil
{
self.voidDuration[key] = (val as! SKMVoidDuration)
}
else
{
throw SKMDBError.entry_exist
}
}
else if locKey == SKMDBKey.cache
{
if self.cache[key] == nil
{
self.cache[key] = (val as! NSCoding)
}
else
{
throw SKMDBError.entry_exist
}
}
else if locKey == SKMDBKey.mcache
{
if self.mcache[key] == nil
{
self.mcache[key] = val
}
else
{
throw SKMDBError.entry_exist
}
}
self.modified = true
}
/*
public func updateEntry(lockey:SKMDBKey,key:String,val:Any) throws
- Update value of entry specified by key in the virtual storage location specifed by lockey
* [Argument]
* locKey - Virtual storage location of the entry
* key - Identifier for the entry
* val - Value to update the entry
* [Exception]
* SKMDBError.entry_not_exist - Entry specifed by key does not exist
*/
public func updateEntry(locKey:SKMDBKey,key:String,val:Any) throws
{
if locKey == SKMDBKey.task
{
if self.task[key] != nil
{
self.task[key] = (val as! SKMTask)
}
else
{
throw SKMDBError.entry_not_exist
}
}
else if locKey == SKMDBKey.void_duration
{
if self.voidDuration[key] != nil
{
self.voidDuration[key] = (val as! SKMVoidDuration)
}
else
{
throw SKMDBError.entry_not_exist
}
}
else if locKey == SKMDBKey.cache
{
if self.cache[key] != nil
{
self.cache[key] = (val as! NSCoding)
}
else
{
throw SKMDBError.entry_not_exist
}
}
else if locKey == SKMDBKey.mcache
{
if self.mcache[key] != nil
{
self.mcache[key] = val
}
else
{
throw SKMDBError.entry_not_exist
}
}
self.modified = true
}
/*
* public func deleteEntry(lockey:SKMDBKey,key:String)
* - Deletes entry specifed by key in the virtual storage location specifed by lockey
* [Argument]
* lockey - Virtual storage location of the entry
* key - Identifier of the entry
*/
public func deleteEntry(lockey:SKMDBKey,key:String)
{
if lockey == SKMDBKey.task
{
self.task[key] = nil
}
else if lockey == SKMDBKey.void_duration
{
self.voidDuration[key] = nil
}
else if lockey == SKMDBKey.cache
{
self.cache[key] = nil
}
else if lockey == SKMDBKey.mcache
{
self.mcache[key] = nil
}
self.modified = true
}
/*
* public func retrieveEntry(lockey:SKMDBKey,key:String) throws -> Any
* - Retrieves the data of the entry specified key located in the virtual storage location specfied by lockey
* NOTE: Might Terminate executable
* [Argument]
* lockey - Virtual storage location of the entry
* key - Identifier of the entry
* [Return]
* Any - Data of the entry
* [Exception]
* SKMDBError.entry_not_exist - Entry does not exist
*/
public func retrieveEntry(lockey:SKMDBKey,key:String) throws -> Any
{
if lockey == SKMDBKey.task
{
if let rst = self.task[key]
{
return rst
}
else
{
throw SKMDBError.entry_not_exist
}
}
else if lockey == SKMDBKey.void_duration
{
if let rst = self.voidDuration[key]
{
return rst
}
else
{
throw SKMDBError.entry_not_exist
}
}
else if lockey == SKMDBKey.cache
{
if let rst = self.cache[key]
{
return rst
}
else
{
throw SKMDBError.entry_not_exist
}
}
else if lockey == SKMDBKey.mcache
{
if let rst = self.mcache[key]
{
return rst
}
else
{
throw SKMDBError.entry_not_exist
}
}
else
{
//Should not happen
abort() //Terminates Executable
}
}
/*
* public func retrieveAllEntry(lockey:SKMDBKey) -> Any
* - Retrieves all entries located in the virtual storage location specified by lockey
* NOTE: Might Terminate Executable
* [Argument]
* lockey - Specfies the Virtual Storage location to retrieve all entrues
* [Return]
* Dictionary[String,Any] - Dictionary of entryies in virtual storage location
*/
public func retrieveAllEntry(lockey:SKMDBKey) -> [String:Any]
{
if lockey == SKMDBKey.task
{
return self.task
}
else if lockey == SKMDBKey.void_duration
{
return self.voidDuration
}
else if lockey == SKMDBKey.cache
{
return self.cache
}
else if lockey == SKMDBKey.mcache
{
return self.mcache
}
else
{
//Should not happen
abort() //Terminates Executable
}
}
}
| mit | 2dece35d8134923bfc75003f139f311a | 25.572973 | 167 | 0.528411 | 4.302217 | false | false | false | false |
TinyCrayon/TinyCrayon-iOS-SDK | TCMask/Utils.swift | 1 | 5973 | //
// Utils.swift
// TinyCrayon
//
// Created by Xin Zeng on 11/1/15.
// Copyright © 2015 Xin Zeng. All rights reserved.
//
import UIKit
let watch = StopWatch()
class StopWatch {
var times = [Date]()
func begin() {
self.times.append(Date())
}
func end(_ msg: String) {
let start = self.times.removeLast()
let end = Date()
let interval = end.timeIntervalSince(start)
print("\(msg) - time:\(interval)s")
}
func abort() {
if !self.times.isEmpty {
self.times.removeLast()
}
}
}
class Util {
static func openAppStoreForReview(_ appleId: Int, completion: ((_ success: Bool) -> ())?) {
let url = URL(string: "itms-apps://itunes.apple.com/app/bars/id\(appleId)")
if #available(iOS 10.0, *), UIApplication.shared.canOpenURL(url!) {
DispatchQueue.main.async(execute: {
UIApplication.shared.open(url!, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil)
completion?(true)
})
}
else {
let errorAlert = UIAlertController(title: "Error Message", message: "An error happened when launching your App Store, please check your settings, or contact us via [email protected]", preferredStyle: UIAlertController.Style.alert)
errorAlert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {
action -> () in
}))
let controller = UIApplication.shared.keyWindow!.rootViewController!
controller.present(errorAlert, animated: true, completion: nil)
completion?(false)
}
}
static func getBufferAddress<T>(_ array: [T]) -> String {
return array.withUnsafeBufferPointer { buffer in
return String(describing: buffer.baseAddress)
}
}
static func runBlockWithIndicatorInView(_ view: UIView, block: @escaping ()->(), completion: (() -> Void)! = nil) {
let activityView = UIView(frame: view.bounds)
let box = UIView(frame: CGRect(x: 0, y: 0, width: 75, height: 75))
let indicator = UIActivityIndicatorView(frame: box.bounds)
activityView.addSubview(box)
view.addSubview(activityView)
activityView.backgroundColor = UIColor(white: 0, alpha: 0)
box.backgroundColor = UIColor(white: 0, alpha: 0.75)
box.layer.cornerRadius = 10
box.center = activityView.center
box.addSubview(indicator)
indicator.center = CGPoint(x: box.width / 2, y: box.height / 2)
indicator.startAnimating()
activityView.alpha = 0
UIView.animate(withDuration: 0.5, animations: {
activityView.alpha = 1
})
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(USEC_PER_SEC)) / Double(NSEC_PER_SEC), execute: {
block()
UIView.animate(withDuration: 0.5, animations:
{
activityView.alpha = 0
}, completion:
{
success in
completion?()
activityView.removeFromSuperview()
}
)
})
}
static func printArray(_ arr: [UInt8]) {
var dict = [UInt8:Int]()
for e in arr {
if let count = dict[e] {
dict[e] = count + 1
}
else {
dict[e] = 1
}
}
let sortedDict = dict.sorted(by: { $0.0 < $1.0 })
for (e, count) in sortedDict {
print("\(e) : \(count)")
}
}
}
func CGContextDrawImageNoFlip(_ ctx: CGContext, _ rect: CGRect, _ image: CGImage?) {
let height = CGFloat(ctx.height)
ctx.draw(image!, in: CGRect(x: rect.origin.x, y: height - rect.origin.y - rect.height, width: rect.width, height: rect.height))
}
func CGContextDrawLine(_ ctx: CGContext, p1: CGPoint, p2: CGPoint, lineWidth: CGFloat, color: CGColor) -> CGRect {
ctx.setStrokeColor(color)
ctx.setBlendMode(CGBlendMode.copy)
ctx.setLineWidth(lineWidth)
ctx.move(to: CGPoint(x: p1.x, y: p1.y))
ctx.addLine(to: CGPoint(x: p2.x, y: p2.y))
ctx.strokePath()
let width = CGFloat(ctx.width)
let height = CGFloat(ctx.height)
let dirtyPoint1 = CGRect(x: p1.x-lineWidth/2, y: p1.y-lineWidth/2, width: lineWidth, height: lineWidth)
let dirtyPoint2 = CGRect(x: p2.x-lineWidth/2, y: p2.y-lineWidth/2, width: lineWidth, height: lineWidth)
var scaledRect = dirtyPoint1.union(dirtyPoint2)
scaledRect.origin.x = min(max(0, floor(scaledRect.origin.x)), width)
scaledRect.origin.y = min(max(0, floor(scaledRect.origin.y)), height)
scaledRect.size.width = min(width - scaledRect.origin.x, ceil(scaledRect.size.width))
scaledRect.size.height = min(height - scaledRect.origin.y, ceil(scaledRect.size.height))
return scaledRect
}
func CGContextFillRect(_ ctx: CGContext, rect: CGRect, color: CGColor) {
ctx.setFillColor(color)
ctx.setBlendMode(CGBlendMode.copy)
ctx.fill(rect)
}
func CGContextDrawImage(_ ctx: CGContext, image: UIImage, rect: CGRect, blendMode: CGBlendMode) {
UIGraphicsPushContext(ctx)
image.draw(in: rect, blendMode: blendMode, alpha: 1)
UIGraphicsPopContext()
}
func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {
#if DEBUG
Swift.print(items[0], separator:separator, terminator: terminator)
#endif
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] {
return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value)})
}
| mit | ba8f52912bda6a91d498d32538bdca98 | 35.414634 | 245 | 0.610348 | 4.112948 | false | false | false | false |
remobjects/Marzipan | CodeGen4/CGSkeletonCodeGenerator.swift | 1 | 10021 | //
// An Empty Code Generator with stubs for all methids that usually need implementing
// Useful as a starting oint for creating a new codegen, or check for missing implementations via diff
//
// All concrete implementations should use the same sort order for methods as this class.
//
// All methods named "generate*" should be overrides. For language-specific generators, add a prefix
// to the method name to indicate the language — see Swift of Pascal codegen implementations for reference.
//
public class CGSkeletonCodeGenerator : CGCodeGenerator {
public override var defaultFileExtension: String { return "" }
override func escapeIdentifier(_ name: String) -> String {
return name
}
override func generateHeader() {
}
override func generateFooter() {
}
/*override func generateImports() {
}*/
override func generateImport(_ imp: CGImport) {
}
override func generateInlineComment(_ comment: String) {
}
//
// Statements
//
override func generateConditionStart(_ condition: CGConditionalDefine) {
}
override func generateConditionElse() {
}
override func generateConditionEnd(_ condition: CGConditionalDefine) {
}
override func generateBeginEndStatement(_ statement: CGBeginEndBlockStatement) {
}
override func generateIfElseStatement(_ statement: CGIfThenElseStatement) {
}
override func generateForToLoopStatement(_ statement: CGForToLoopStatement) {
}
override func generateForEachLoopStatement(_ statement: CGForEachLoopStatement) {
}
override func generateWhileDoLoopStatement(_ statement: CGWhileDoLoopStatement) {
}
override func generateDoWhileLoopStatement(_ statement: CGDoWhileLoopStatement) {
}
/*
override func generateInfiniteLoopStatement(_ statement: CGInfiniteLoopStatement) {
}
*/
override func generateSwitchStatement(_ statement: CGSwitchStatement) {
}
override func generateLockingStatement(_ statement: CGLockingStatement) {
}
override func generateUsingStatement(_ statement: CGUsingStatement) {
}
override func generateAutoReleasePoolStatement(_ statement: CGAutoReleasePoolStatement) {
}
override func generateTryFinallyCatchStatement(_ statement: CGTryFinallyCatchStatement) {
}
override func generateReturnStatement(_ statement: CGReturnStatement) {
}
override func generateYieldStatement(_ statement: CGYieldStatement) {
}
override func generateThrowStatement(_ statement: CGThrowStatement) {
}
override func generateBreakStatement(_ statement: CGBreakStatement) {
}
override func generateContinueStatement(_ statement: CGContinueStatement) {
}
override func generateVariableDeclarationStatement(_ statement: CGVariableDeclarationStatement) {
}
override func generateAssignmentStatement(_ statement: CGAssignmentStatement) {
}
override func generateConstructorCallStatement(_ statement: CGConstructorCallStatement) {
}
//
// Expressions
//
override func generateNamedIdentifierExpression(_ expression: CGNamedIdentifierExpression) {
}
override func generateAssignedExpression(_ expression: CGAssignedExpression) {
}
override func generateSizeOfExpression(_ expression: CGSizeOfExpression) {
}
override func generateTypeOfExpression(_ expression: CGTypeOfExpression) {
}
override func generateDefaultExpression(_ expression: CGDefaultExpression) {
}
override func generateSelectorExpression(_ expression: CGSelectorExpression) {
}
override func generateTypeCastExpression(_ expression: CGTypeCastExpression) {
}
override func generateInheritedExpression(_ expression: CGInheritedExpression) {
}
override func generateSelfExpression(_ expression: CGSelfExpression) {
}
override func generateNilExpression(_ expression: CGNilExpression) {
}
override func generatePropertyValueExpression(_ expression: CGPropertyValueExpression) {
}
override func generateAwaitExpression(_ expression: CGAwaitExpression) {
}
override func generateAnonymousMethodExpression(_ expression: CGAnonymousMethodExpression) {
}
override func generateAnonymousTypeExpression(_ expression: CGAnonymousTypeExpression) {
}
override func generatePointerDereferenceExpression(_ expression: CGPointerDereferenceExpression) {
}
override func generateUnaryOperatorExpression(_ expression: CGUnaryOperatorExpression) {
}
override func generateBinaryOperatorExpression(_ expression: CGBinaryOperatorExpression) {
}
override func generateUnaryOperator(_ `operator`: CGUnaryOperatorKind) {
}
override func generateBinaryOperator(_ `operator`: CGBinaryOperatorKind) {
}
override func generateIfThenElseExpression(_ expression: CGIfThenElseExpression) {
}
override func generateFieldAccessExpression(_ expression: CGFieldAccessExpression) {
}
override func generateArrayElementAccessExpression(_ expression: CGArrayElementAccessExpression) {
}
override func generateMethodCallExpression(_ expression: CGMethodCallExpression) {
}
override func generateNewInstanceExpression(_ expression: CGNewInstanceExpression) {
}
override func generatePropertyAccessExpression(_ expression: CGPropertyAccessExpression) {
}
override func generateEnumValueAccessExpression(_ expression: CGEnumValueAccessExpression) {
}
override func generateStringLiteralExpression(_ expression: CGStringLiteralExpression) {
}
override func generateCharacterLiteralExpression(_ expression: CGCharacterLiteralExpression) {
}
override func generateIntegerLiteralExpression(_ expression: CGIntegerLiteralExpression) {
}
override func generateFloatLiteralExpression(_ expression: CGFloatLiteralExpression) {
}
override func generateArrayLiteralExpression(_ expression: CGArrayLiteralExpression) {
}
override func generateSetLiteralExpression(_ expression: CGSetLiteralExpression) {
}
override func generateDictionaryExpression(_ expression: CGDictionaryLiteralExpression) {
}
/*
override func generateTupleExpression(_ expression: CGTupleLiteralExpression) {
// default handled in base
}
*/
override func generateSetTypeReference(_ type: CGSetTypeReference, ignoreNullability: Boolean = false) {
}
override func generateSequenceTypeReference(_ type: CGSequenceTypeReference, ignoreNullability: Boolean = false) {
}
//
// Type Definitions
//
override func generateAttribute(_ attribute: CGAttribute, inline: Boolean) {
}
override func generateAliasType(_ type: CGTypeAliasDefinition) {
}
override func generateBlockType(_ type: CGBlockTypeDefinition) {
}
override func generateEnumType(_ type: CGEnumTypeDefinition) {
}
override func generateClassTypeStart(_ type: CGClassTypeDefinition) {
}
override func generateClassTypeEnd(_ type: CGClassTypeDefinition) {
}
override func generateStructTypeStart(_ type: CGStructTypeDefinition) {
}
override func generateStructTypeEnd(_ type: CGStructTypeDefinition) {
}
override func generateInterfaceTypeStart(_ type: CGInterfaceTypeDefinition) {
}
override func generateInterfaceTypeEnd(_ type: CGInterfaceTypeDefinition) {
}
override func generateExtensionTypeStart(_ type: CGExtensionTypeDefinition) {
}
override func generateExtensionTypeEnd(_ type: CGExtensionTypeDefinition) {
}
//
// Type Members
//
override func generateMethodDefinition(_ method: CGMethodDefinition, type: CGTypeDefinition) {
}
override func generateConstructorDefinition(_ ctor: CGConstructorDefinition, type: CGTypeDefinition) {
}
override func generateDestructorDefinition(_ dtor: CGDestructorDefinition, type: CGTypeDefinition) {
}
override func generateFinalizerDefinition(_ finalizer: CGFinalizerDefinition, type: CGTypeDefinition) {
}
override func generateFieldDefinition(_ field: CGFieldDefinition, type: CGTypeDefinition) {
}
override func generatePropertyDefinition(_ property: CGPropertyDefinition, type: CGTypeDefinition) {
}
override func generateEventDefinition(_ event: CGEventDefinition, type: CGTypeDefinition) {
}
override func generateCustomOperatorDefinition(_ customOperator: CGCustomOperatorDefinition, type: CGTypeDefinition) {
}
override func generateNestedTypeDefinition(_ member: CGNestedTypeDefinition, type: CGTypeDefinition) {
}
//
// Type References
//
override func generateNamedTypeReference(_ type: CGNamedTypeReference) {
}
override func generatePredefinedTypeReference(_ type: CGPredefinedTypeReference, ignoreNullability: Boolean = false) {
switch (type.Kind) {
case .Int: Append("")
case .UInt: Append("")
case .Int8: Append("")
case .UInt8: Append("")
case .Int16: Append("")
case .UInt16: Append("")
case .Int32: Append("")
case .UInt32: Append("")
case .Int64: Append("")
case .UInt64: Append("")
case .IntPtr: Append("")
case .UIntPtr: Append("")
case .Single: Append("")
case .Double: Append("")
case .Boolean: Append("")
case .String: Append("")
case .AnsiChar: Append("")
case .UTF16Char: Append("")
case .UTF32Char: Append("")
case .Dynamic: Append("")
case .InstanceType: Append("")
case .Void: Append("")
case .Object: Append("")
case .Class: Append("")
}
}
override func generateIntegerRangeTypeReference(_ type: CGIntegerRangeTypeReference, ignoreNullability: Boolean = false) {
Append(type.Start.ToString())
Append("..")
Append(type.End.ToString())
}
override func generateInlineBlockTypeReference(_ type: CGInlineBlockTypeReference, ignoreNullability: Boolean = false) {
}
override func generatePointerTypeReference(_ type: CGPointerTypeReference) {
}
override func generateKindOfTypeReference(_ type: CGKindOfTypeReference, ignoreNullability: Boolean = false) {
}
override func generateTupleTypeReference(_ type: CGTupleTypeReference, ignoreNullability: Boolean = false) {
}
override func generateArrayTypeReference(_ type: CGArrayTypeReference, ignoreNullability: Boolean = false) {
}
override func generateDictionaryTypeReference(_ type: CGDictionaryTypeReference, ignoreNullability: Boolean = false) {
}
} | bsd-3-clause | 81830757586b8d9aca7fdc6c26e828c3 | 21.665158 | 123 | 0.772886 | 4.299142 | false | false | false | false |
nohana/NohanaImagePicker | NohanaImagePicker/MomentViewController.swift | 1 | 11113 | /*
* Copyright (C) 2016 nohana, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
import Photos
final class MomentViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, ActivityIndicatable {
private let nohanaImagePickerController: NohanaImagePickerController
var momentInfoSectionList: [MomentInfoSection] = []
var isFirstAppearance = true
var cellSize: CGSize {
var numberOfColumns = nohanaImagePickerController.numberOfColumnsInLandscape
if UIApplication.shared.currentStatusBarOrientation.isPortrait {
numberOfColumns = nohanaImagePickerController.numberOfColumnsInPortrait
}
let cellMargin: CGFloat = 2
let cellWidth = (view.frame.width - cellMargin * (CGFloat(numberOfColumns) - 1)) / CGFloat(numberOfColumns)
return CGSize(width: cellWidth, height: cellWidth)
}
init?(coder: NSCoder, nohanaImagePickerController: NohanaImagePickerController) {
self.nohanaImagePickerController = nohanaImagePickerController
super.init(coder: coder)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = nohanaImagePickerController.config.color.background ?? .white
setUpToolbarItems()
addPickPhotoKitAssetNotificationObservers()
setUpActivityIndicator()
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
let mediaType = self.nohanaImagePickerController.mediaType
self.momentInfoSectionList = MomentInfoSectionCreater().createSections(mediaType: mediaType)
self.isLoading = false
self.collectionView?.reloadData()
self.isFirstAppearance = true
self.scrollCollectionViewToInitialPosition()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setToolbarTitle(nohanaImagePickerController)
collectionView?.reloadData()
scrollCollectionViewToInitialPosition()
}
func scrollCollectionView(to indexPath: IndexPath) {
let count: Int? = momentInfoSectionList.count
guard count != nil && count! > 0 else {
return
}
DispatchQueue.main.async {
self.collectionView?.scrollToItem(at: indexPath, at: .bottom, animated: false)
}
}
func scrollCollectionViewToInitialPosition() {
guard isFirstAppearance else {
return
}
let lastSection = momentInfoSectionList.count - 1
guard lastSection >= 0 else {
return
}
let indexPath = IndexPath(item: momentInfoSectionList[lastSection].assetResult.count - 1, section: lastSection)
scrollCollectionView(to: indexPath)
isFirstAppearance = false
}
// MARK: - UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
if let activityIndicator = activityIndicator {
updateVisibilityOfActivityIndicator(activityIndicator)
}
return momentInfoSectionList.count
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return momentInfoSectionList[section].assetResult.count
}
// MARK: - UICollectionViewDelegate
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AssetCell", for: indexPath) as? AssetCell else {
fatalError("failed to dequeueReusableCellWithIdentifier(\"AssetCell\")")
}
let asset = PhotoKitAsset(asset: momentInfoSectionList[indexPath.section].assetResult[indexPath.row])
cell.tag = indexPath.item
cell.update(asset: asset, nohanaImagePickerController: nohanaImagePickerController)
let imageSize = CGSize(
width: cellSize.width * UIScreen.main.scale,
height: cellSize.height * UIScreen.main.scale
)
asset.image(targetSize: imageSize) { (imageData) -> Void in
DispatchQueue.main.async(execute: { () -> Void in
if let imageData = imageData {
if cell.tag == indexPath.item {
cell.imageView.image = imageData.image
}
}
})
}
return (nohanaImagePickerController.delegate?.nohanaImagePicker?(nohanaImagePickerController, assetListViewController: self, cell: cell, indexPath: indexPath, photoKitAsset: asset.originalAsset)) ?? cell
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionView.elementKindSectionHeader:
let album = momentInfoSectionList[indexPath.section]
guard let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "MomentHeader", for: indexPath) as? MomentSectionHeaderView else {
fatalError("failed to create MomentHeader")
}
let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeStyle = DateFormatter.Style.none
header.dateLabel.text = formatter.string(from: album.creationDate)
return header
default:
fatalError("failed to create MomentHeader")
}
}
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return cellSize
}
// MARK: - ActivityIndicatable
var activityIndicator: UIActivityIndicatorView?
var isLoading = true
func setUpActivityIndicator() {
activityIndicator = UIActivityIndicatorView(style: .medium)
activityIndicator?.color = .gray
let screenRect = Size.screenRectWithoutAppBar(self)
activityIndicator?.center = CGPoint(x: screenRect.size.width / 2, y: screenRect.size.height / 2)
activityIndicator?.startAnimating()
}
func isProgressing() -> Bool {
return isLoading
}
// MARK: - UICollectionViewDelegate
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
nohanaImagePickerController.delegate?.nohanaImagePicker?(nohanaImagePickerController, didSelectPhotoKitAsset: momentInfoSectionList[indexPath.section].assetResult[indexPath.row])
}
@available(iOS 13.0, *)
override func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
let asset = PhotoKitAsset(asset: momentInfoSectionList[indexPath.section].assetResult[indexPath.row])
if let cell = collectionView.cellForItem(at: indexPath) as? AssetCell {
return UIContextMenuConfiguration(identifier: indexPath as NSCopying, previewProvider: { [weak self] in
// Create a preview view controller and return it
guard let self = self else { return nil }
let previewViewController = ImagePreviewViewController(asset: asset)
let imageSize = cell.imageView.image?.size ?? .zero
let width = self.view.bounds.width
let height = imageSize.height * (width / imageSize.width)
let contentSize = CGSize(width: width, height: height)
previewViewController.preferredContentSize = contentSize
return previewViewController
}, actionProvider: { [weak self] _ in
guard let self = self else { return nil }
if self.nohanaImagePickerController.pickedAssetList.isPicked(asset) {
let title = self.nohanaImagePickerController.config.strings.albumListTitle ?? NSLocalizedString("action.title.deselect", tableName: "NohanaImagePicker", bundle: self.nohanaImagePickerController.assetBundle, comment: "")
let deselect = UIAction(title: title, image: UIImage(systemName: "minus.circle"), attributes: [.destructive]) { _ in
self.nohanaImagePickerController.dropAsset(asset)
collectionView.reloadItems(at: [indexPath])
}
return UIMenu(title: "", children: [deselect])
} else {
let title = self.nohanaImagePickerController.config.strings.albumListTitle ?? NSLocalizedString("action.title.select", tableName: "NohanaImagePicker", bundle: self.nohanaImagePickerController.assetBundle, comment: "")
let select = UIAction(title: title, image: UIImage(systemName: "checkmark.circle")) { _ in
self.nohanaImagePickerController.pickAsset(asset)
collectionView.reloadItems(at: [indexPath])
}
return UIMenu(title: "", children: [select])
}
})
} else {
return nil
}
}
@available(iOS 13.0, *)
override func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
animator.addCompletion { [weak self] in
guard let self = self else { return }
if let indexPath = configuration.identifier as? IndexPath {
collectionView.selectItem(at: indexPath, animated: false, scrollPosition: [])
self.performSegue(withIdentifier: "toMomentDetailListViewController", sender: nil)
}
}
}
// MARK: - IBSegueAction
@IBSegueAction func makeMomentDetail(_ coder: NSCoder) -> MomentDetailListViewController? {
guard let selectedIndexPath = collectionView?.indexPathsForSelectedItems?.first else {
return nil
}
return MomentDetailListViewController(coder: coder, nohanaImagePickerController: nohanaImagePickerController, momentInfoSection: momentInfoSectionList[selectedIndexPath.section], currentIndexPath: selectedIndexPath)
}
}
| apache-2.0 | 9ddd42669c02953b086f1e536391aecc | 46.491453 | 239 | 0.678035 | 5.509668 | false | false | false | false |
onmyway133/Github.swift | Sources/Classes/Search/Client+Search.swift | 1 | 1253 | //
// Client+Search.swift
// GithubSwift
//
// Created by Khoa Pham on 20/04/16.
// Copyright © 2016 Fantageek. All rights reserved.
//
import Foundation
import RxSwift
import Construction
public extension Client {
/// Search repositories.
///
/// query - The search keywords, as well as any qualifiers. This must not be nil.
/// orderBy - The sort field. One of stars, forks, or updated. Default: results
/// are sorted by best match. This can be nil.
/// ascending - The sort order, ascending or not.
///
/// Returns a signal which will send the search result `OCTRepositoriesSearchResult`.
public func searchRepositories(query: String, orderBy: String? = nil,
ascending: Bool = true) -> Observable<RepositorySearchResult> {
let requestDescriptor: RequestDescriptor = construct {
$0.path = "/search/repositories"
$0.parameters = [
"q": query,
"order": ascending ? "asc" : "desc"
]
if let orderBy = orderBy {
$0.parameters["sort"] = orderBy
}
$0.headers["Accept"] = "application/vnd.github.v3.text-match+json"
}
return enqueue(requestDescriptor).map {
return Parser.one($0)
}
}
}
| mit | 45bc2cb0abc916e01538444eb8170d3b | 26.822222 | 96 | 0.623003 | 4.064935 | false | false | false | false |
DeliciousRaspberryPi/MockFive | MockFive/MockFiveInternal.swift | 1 | 6259 | import Foundation
extension Mock {
private(set) public var invocations: [String] { get { return mockRecords[mockFiveLock] ?? [] } set(new) { mockRecords[mockFiveLock] = new } }
public func resetMock() {
mockRecords[mockFiveLock] = []
mockBlocks[mockFiveLock] = [:]
}
public func unregisterStub(identifier: String) {
var blocks = mockBlocks[mockFiveLock] ?? [:] as [String:Any]
blocks.removeValueForKey(identifier)
mockBlocks[mockFiveLock] = blocks
}
public func registerStub<T>(identifier: String, returns: ([Any?]) -> T) {
var blocks = mockBlocks[mockFiveLock] ?? [:] as [String:Any]
blocks[identifier] = returns
mockBlocks[mockFiveLock] = blocks
}
public func stub<T: NilLiteralConvertible>(identifier identifier: String, arguments: Any?..., function: String = __FUNCTION__, returns: ([Any?]) -> T = { _ in nil }) -> T {
logInvocation(stringify(function, arguments: arguments, returnType: "\(T.self)"))
if let registeredStub = mockBlocks[mockFiveLock]?[identifier] {
guard let typecastStub = registeredStub as? ([Any?]) -> T else { fatalError("MockFive: Incompatible block of type '\(registeredStub.dynamicType)' registered for function '\(identifier)' requiring block type '([Any?]) -> \(T.self)'") }
return typecastStub(arguments)
}
else { return returns(arguments) }
}
public func stub<T>(identifier identifier: String, arguments: Any?..., function: String = __FUNCTION__, returns: ([Any?]) -> T) -> T {
logInvocation(stringify(function, arguments: arguments, returnType: "\(T.self)"))
if let registeredStub = mockBlocks[mockFiveLock]?[identifier] {
guard let typecastStub = registeredStub as? ([Any?]) -> T else { fatalError("MockFive: Incompatible block of type '\(registeredStub.dynamicType)' registered for function '\(identifier)' requiring block type '([Any?]) -> \(T.self)'") }
return typecastStub(arguments)
}
else { return returns(arguments) }
}
public func stub(identifier identifier: String, arguments: Any?..., function: String = __FUNCTION__, returns: ([Any?]) -> () = { _ in }) {
logInvocation(stringify(function, arguments: arguments, returnType: .None))
if let registeredStub = mockBlocks[mockFiveLock]?[identifier] {
guard let typecastStub = registeredStub as? ([Any?]) -> () else { fatalError("MockFive: Incompatible block of type '\(registeredStub.dynamicType)' registered for function '\(identifier)' requiring block type '([Any?]) -> ()'") }
typecastStub(arguments)
}
else { returns(arguments) }
}
// Utility stuff
private func logInvocation(invocation: String) {
var invocations = [String]()
invocations.append(invocation)
if let existingInvocations = mockRecords[mockFiveLock] { invocations = existingInvocations + invocations }
mockRecords[mockFiveLock] = invocations
}
}
public func resetMockFive() { globalObjectIDIndex = 0; mockRecords = [:]; mockBlocks = [:] }
public func lock(signature: String = __FILE__ + ":\(__LINE__):\(OSAtomicIncrement32(&globalObjectIDIndex))") -> String { return signature }
func + <T, U> (left: [T:U], right: [T:U]) -> [T:U] {
var result: [T:U] = [:]
for (k, v) in left { result.updateValue(v, forKey: k) }
for (k, v) in right { result.updateValue(v, forKey: k) }
return result
}
// Private
private var globalObjectIDIndex: Int32 = 0
private var mockRecords: [String:[String]] = [:]
private var mockBlocks: [String:[String:Any]] = [:]
private func stringify(function: String, arguments: [Any?], returnType: String?) -> String {
var invocation = ""
let arguments = arguments.map { $0 ?? "nil" } as [Any]
if .None == function.rangeOfCharacterFromSet(NSCharacterSet(charactersInString: "()")) {
invocation = function + "(\(arguments.first ?? "nil"))"
if let returnType = returnType { invocation += " -> \(returnType)" }
} else if let _ = function.rangeOfString("()") {
invocation = function
if let returnType = returnType { invocation += " -> \(returnType)" }
} else {
let startIndex = function.rangeOfString("(")!.endIndex
let endIndex = function.rangeOfString(")")!.startIndex
invocation += function.substringToIndex(startIndex)
let argumentLabels = function.substringWithRange(Range(start: startIndex, end: endIndex)).componentsSeparatedByString(":")
for i in 0..<argumentLabels.count - 1 {
invocation += argumentLabels[i] + ": "
if (i < arguments.count) { invocation += "\(arguments[i])" }
invocation += ", "
}
invocation = invocation.substringToIndex(invocation.endIndex.advancedBy(-2)) + ")"
if let returnType = returnType { invocation += " -> \(returnType)" }
if argumentLabels.count - 1 != arguments.count {
invocation += " [Expected \(argumentLabels.count - 1), got \(arguments.count)"
if argumentLabels.count < arguments.count {
let remainder = arguments[argumentLabels.count - 1..<arguments.count]
let roughArguments = remainder.reduce(": ", combine: { $0 + "\($1), " })
invocation += roughArguments.substringToIndex(roughArguments.endIndex.advancedBy(-2))
}
invocation += "]"
}
}
return invocation
}
// Testing
@noreturn func fatalError(@autoclosure message: () -> String = "", file: StaticString = __FILE__, line: UInt = __LINE__) {
FatalErrorUtil.fatalErrorClosure(message(), file, line)
unreachable()
}
@noreturn func unreachable() {
repeat { NSRunLoop.currentRunLoop().run() } while (true)
}
struct FatalErrorUtil {
static var fatalErrorClosure: (String, StaticString, UInt) -> () = defaultFatalErrorClosure
private static let defaultFatalErrorClosure = { Swift.fatalError($0, file: $1, line: $2) }
static func replaceFatalError(closure: (String, StaticString, UInt) -> ()) { fatalErrorClosure = closure }
static func restoreFatalError() { fatalErrorClosure = defaultFatalErrorClosure }
}
| apache-2.0 | 510422a703107283aae31fd881ecfa93 | 49.475806 | 246 | 0.637003 | 4.457977 | false | false | false | false |
ThePacielloGroup/CCA-OSX | Colour Contrast Analyser/CCAColourBrightnessDifferenceField.swift | 1 | 1071 | //
// NSColourBrightnessDifferenceField.swift
// Colour Contrast Analyser
//
// Created by Cédric Trévisan on 03/02/2015.
// Copyright (c) 2015 Cédric Trévisan. All rights reserved.
//
import Cocoa
class CCAColourBrightnessDifferenceField: NSTextField {
@IBOutlet weak var statusImage:NSImageView!
var currentStatus:Bool = false
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
}
func setFail() {
if (currentStatus == true) {
self.statusImage.image = NSImage(named: NSImage.Name(rawValue: "No"))
currentStatus = false;
}
}
func setPass() {
if (currentStatus == false) {
self.statusImage.image = NSImage(named: NSImage.Name(rawValue: "Yes"))
currentStatus = true;
}
}
func validateColourBrightnessDifference(_ brightness:Int, colour:Int) {
if brightness > 125 && colour > 500 {
self.setPass();
} else {
self.setFail();
}
}
}
| gpl-3.0 | 24b20bf61fb67ed604b7f7cccf4874c9 | 25.02439 | 82 | 0.597938 | 4.250996 | false | false | false | false |
Beaver/BeaverCodeGen | Sources/BeaverCodeGen/SwiftModel/SwiftKind.swift | 1 | 2897 | public enum SwiftKind {
case `enum`
case enumcase
case enumelement
case typeref
case `protocol`
case `struct`
case `var`
case method
case `extension`
case staticMethod
case `switch`
case call
case `class`
case argument
case `if`
case unknown(value: String)
}
extension SwiftKind: Decodable {
public init(from decoder: Decoder) throws {
let value = try decoder.singleValueContainer().decode(String.self)
switch value {
case "source.lang.swift.decl.enum":
self = .`enum`
case "source.lang.swift.decl.enumcase", "source.lang.swift.stmt.case":
self = .enumcase
case "source.lang.swift.decl.enumelement":
self = .enumelement
case "source.lang.swift.decl.typeref", "source.lang.swift.structure.elem.typeref":
self = .typeref
case "source.lang.swift.decl.protocol":
self = .`protocol`
case "source.lang.swift.decl.struct":
self = .`struct`
case "source.lang.swift.decl.var.instance":
self = .`var`
case "source.lang.swift.decl.function.method.instance":
self = .method
case "source.lang.swift.decl.function.method.static":
self = .staticMethod
case "source.lang.swift.decl.extension":
self = .`extension`
case "source.lang.swift.stmt.switch":
self = .`switch`
case "source.lang.swift.expr.call":
self = .call
case "source.lang.swift.decl.class":
self = .`class`
case "source.lang.swift.expr.argument":
self = .argument
case "source.lang.swift.stmt.if":
self = .`if`
default:
self = .unknown(value: value)
}
}
}
extension SwiftKind {
var name: String {
switch self {
case .`enum`:
return "enum"
case .enumcase:
return "enumcase"
case .enumelement:
return "enumelement"
case .typeref:
return "typeref"
case .`protocol`:
return "protocol"
case .`struct`:
return "struct"
case .`var`:
return "var"
case .method:
return "method"
case .staticMethod:
return "method.static"
case .`extension`:
return "extension"
case .`switch`:
return "switch"
case .call:
return "call"
case .`class`:
return "class"
case .argument:
return "argument"
case .`if`:
return "if"
case .unknown(let value):
return value
}
}
}
extension SwiftKind: Equatable {
public static func ==(lhs: SwiftKind, rhs: SwiftKind) -> Bool {
return lhs.name == rhs.name
}
}
| mit | c57202878639defdfa1a18aa67b25440 | 27.126214 | 90 | 0.537453 | 4.279173 | false | false | false | false |
DannyvanSwieten/SwiftSignals | SwiftAudio/Midi.swift | 1 | 6156 | //
// MidiClient.swift
// SwiftAudio
//
// Created by Danny van Swieten on 1/9/16.
// Copyright © 2016 Danny van Swieten. All rights reserved.
//
import CoreMIDI
class MidiDevice
{
var device = MIDIDeviceRef()
var entity: MIDIEndpointRef?
var source: MIDIEndpointRef?
init(name: CFString)
{
let numDevices = MIDIGetNumberOfDevices()
for deviceIndex in 0..<numDevices
{
let midiEndPoint = MIDIGetDevice(deviceIndex)
if midiEndPoint > 0
{
var property : Unmanaged<CFString>?
let err = MIDIObjectGetStringProperty(midiEndPoint, kMIDIPropertyName, &property)
if err == noErr
{
let displayName = property!.takeRetainedValue()
if displayName == name
{
device = midiEndPoint
entity = MIDIDeviceGetEntity(device, 0)
return
}
}
}
}
}
func connectToInput(input: MidiInput)
{
source = MIDIEntityGetSource(entity!, 0)
if(MIDIPortConnectSource(input.inputPtr.memory, source!, nil) == noErr)
{
print("Device succesfully connected to Input")
}
}
}
class MidiInput
{
var inputPtr = UnsafeMutablePointer<MIDIPortRef>.alloc(1)
var input = MIDIPortRef()
var listeners = [MidiProcessor]()
init(client: MidiClient, name: CFString)
{
inputPtr.initialize(input)
if (MIDIInputPortCreateWithBlock(client.midiClient, name, inputPtr, messageReceived) == noErr)
{
print("Midi input created succesfully")
}
}
func messageReceived(packetList: UnsafePointer<MIDIPacketList>, source: UnsafeMutablePointer<Void>) -> Void
{
let packets = packetList.memory
let packet = packets.packet
let status = packet.data.0
let channel = packet.data.0 & 0x0f
var type = MidiMessageType.UNKNOWN
var message = MidiMessage(aType: type, aPitch: 0, aVelocity: 0, aChannel: 0)
switch(status >> 4)
{
case 0b1000:
type = MidiMessageType.NOTEOFF
message = MidiMessage(aType: type, aPitch: packet.data.1, aVelocity: packet.data.2, aChannel: channel)
case 0b1001:
type = MidiMessageType.NOTEON
message = MidiMessage(aType: type, aPitch: packet.data.1, aVelocity: packet.data.2, aChannel: channel)
case 0b1110:
type = MidiMessageType.PITCHBEND
message = MidiMessage(aType: type, aPitch: packet.data.1, aVelocity: packet.data.2, aChannel: channel)
default:
type = MidiMessageType.UNKNOWN
message = MidiMessage(aType: type, aPitch: 0, aVelocity: 0, aChannel: 0)
}
for listener in listeners
{
listener.onMidiEvent(message)
}
}
class func listDevices() -> [String]
{
var devices = [String]()
let numSrcs = MIDIGetNumberOfSources()
print("number of MIDI sources: \(numSrcs)")
for srcIndex in 0 ..< numSrcs {
#if arch(arm64) || arch(x86_64)
let midiEndPoint = MIDIGetSource(srcIndex)
#else
let midiEndPoint = unsafeBitCast(MIDIGetSource(srcIndex), MIDIObjectRef.self)
#endif
var property : Unmanaged<CFString>?
let err = MIDIObjectGetStringProperty(midiEndPoint, kMIDIPropertyDisplayName, &property)
if err == noErr {
let displayName = property!.takeRetainedValue() as String
devices.append(displayName)
print("\(srcIndex): \(displayName)")
} else {
print("\(srcIndex): error \(err)")
}
}
let numdest = MIDIGetNumberOfDestinations()
print("number of MIDI Destinations: \(numSrcs)")
for destIndex in 0 ..< numdest {
#if arch(arm64) || arch(x86_64)
let midiEndPoint = MIDIGetDestination(destIndex)
#else
let midiEndPoint = unsafeBitCast(MIDIGetDestination(destIndex), MIDIObjectRef.self)
#endif
var property : Unmanaged<CFString>?
let err = MIDIObjectGetStringProperty(midiEndPoint, kMIDIPropertyDisplayName, &property)
if err == noErr {
let displayName = property!.takeRetainedValue() as String
devices.append(displayName)
print("\(destIndex): \(displayName)")
} else {
print("\(destIndex): error \(err)")
}
}
return devices
}
}
class MidiClient
{
var midiClient = MIDIClientRef()
init()
{
if(MIDIClientCreateWithBlock("MyMIDIClient", &midiClient, MyMIDINotifyBlock) == noErr)
{
print("Midi client created succesfully")
}
}
func MyMIDINotifyBlock(midiNotification: UnsafePointer<MIDINotification>) {
print("State of the midi system changed")
}
}
enum MidiMessageType
{
case NOTEON
case NOTEOFF
case PITCHBEND
case UNKNOWN
}
class MidiMessage
{
var type: MidiMessageType
var pitch: UInt8
var velocity: UInt8
var channel: UInt8
init(aType: MidiMessageType, aPitch: UInt8, aVelocity: UInt8, aChannel: UInt8)
{
type = aType
pitch = aPitch
velocity = aVelocity
channel = aChannel
}
func isNoteOn() -> Bool{
return type == .NOTEON
}
func isNoteOff() -> Bool{
return type == .NOTEOFF
}
func isPitchBend() -> Bool{
return type == .PITCHBEND
}
func midiToFrequency() -> Float32{
return powf(2.0, (Float(pitch) - 69.0)/12.0) * 440.0
}
}
protocol MidiProcessor
{
func onMidiEvent(event: MidiMessage)
} | gpl-3.0 | 7c0516c42741463fdce7c411b23aee0c | 28.454545 | 114 | 0.55922 | 4.437635 | false | false | false | false |
KatagiriSo/CoreDataUtil | CoreDataUtil/CoreDataUtil.swift | 1 | 3207 | //
// CoreDataUtil.swift
// CoreDataUtil
//
// Created by 片桐奏羽 on 2015/10/02.
// Copyright (c) 2015年 SoKatagiri. All rights reserved.
//
import UIKit
import CoreData
class CoreDataUtil: NSObject {
var managerContext : NSManagedObjectContext?
var entityDescription : NSEntityDescription?
var DBName = "data.sqlite"
static internal var shareInstance : CoreDataUtil? = nil
static func share()->CoreDataUtil
{
if (shareInstance == nil) {
shareInstance = CoreDataUtil()
}
return shareInstance!
}
override init() {
super.init()
setUp()
}
func setUp()
{
// バンドルからモデルファイルを読み込む
let m = NSManagedObjectModel.mergedModelFromBundles(nil)
let psc = NSPersistentStoreCoordinator(managedObjectModel:m!)
var error:NSError?
// 永続ストアとしてSQLite使用
psc.addPersistentStoreWithType(
NSSQLiteStoreType,
configuration: nil,
URL: sqliteURL(),
options: persistentOptions(),
error: &error)
self.managerContext = NSManagedObjectContext()
self.managerContext!.persistentStoreCoordinator = psc
self.entityDescription = NSEntityDescription.entityForName(Record.entityName, inManagedObjectContext: self.managerContext!)
}
func sqliteURL()->(NSURL?)
{
// 永続storeとしてsqliteのセット
var documentPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]as! String
println("path=\(documentPath)")
let url = NSURL(fileURLWithPath:documentPath.stringByAppendingPathComponent(DBName))
return url
}
// 永続ストアのオプション
func persistentOptions()->[String:Bool]
{
// マイグレーションは自動的に
var options = [NSMigratePersistentStoresAutomaticallyOption:true, NSInferMappingModelAutomaticallyOption:true]
return options
}
func GET()->[Record]
{
let fetchReq = NSFetchRequest(entityName: self.entityDescription!.name!)
fetchReq.returnsObjectsAsFaults = false
// ソートしたいとき
// let sortDescriptor = NSSortDescriptor(key: Record.keyTimeStamp, ascending: true)
// fetchRequest.sortDescriptors = [sortDescriptor]
// フェッチ要求実行
var error : NSError? = nil
var results : Array! = self.managerContext!.executeFetchRequest(fetchReq, error: &error)
if (error != nil) {
println("[error]\(error?.description)")
}
return results as! [Record]
}
func save(errorp:NSErrorPointer)->Bool
{
if ((self.managerContext?.save(errorp)) != nil) {
return true
}
return false
}
func CREATE()->Record
{
var record = Record(entity:self.entityDescription!, insertIntoManagedObjectContext: self.managerContext)
return record
}
}
| mit | 924c905a08e312d22ce185a65e3e8a09 | 26.917431 | 161 | 0.623398 | 4.98036 | false | false | false | false |
Gray-Wind/WWCalendarTimeSelector | Sources/NSDate+Timepiece.swift | 1 | 5887 | //
// NSDate+Timepiece.swift
// Timepiece
//
// Created by Naoto Kaneko on 2014/08/16.
// Copyright (c) 2014年 Naoto Kaneko. All rights reserved.
//
import Foundation
import ObjectiveC
// MARK: - Calculation
func + (lhs: Date, rhs: Duration) -> Date {
return (NSCalendar.current as NSCalendar).dateByAddingDuration(rhs, toDate: lhs, options: .searchBackwards)!
}
func - (lhs: Date, rhs: Duration) -> Date {
return (NSCalendar.current as NSCalendar).dateByAddingDuration(-rhs, toDate: lhs, options: .searchBackwards)!
}
func - (lhs: Date, rhs: Date) -> TimeInterval {
return lhs.timeIntervalSince(rhs)
}
// MARK: - Equatable
//extension NSDate: Equatable {}
//func == (lhs: Date, rhs: Date) -> Bool {
// return (lhs == rhs)
//}
// MARK: - Comparable
//internal extension NSDate: Comparable {}
//
//func < (lhs: NSDate, rhs: NSDate) -> Bool {
// return lhs.compare(rhs) == .OrderedAscending
//}
// MARK: -
extension Date {
fileprivate struct AssociatedKeys {
static var TimeZone = "timepiece_TimeZone"
}
// MARK: - Get components
var year: Int {
return components.year!
}
var month: Int {
return components.month!
}
var weekday: Int {
return (components.weekday! + 7 - Calendar.current.firstWeekday) % 7 + 1
}
var day: Int {
return components.day!
}
var hour: Int {
return components.hour!
}
var minute: Int {
return components.minute!
}
var second: Int {
return components.second!
}
var timeZone: NSTimeZone {
return objc_getAssociatedObject(self, &AssociatedKeys.TimeZone) as? NSTimeZone ?? calendar.timeZone as NSTimeZone
}
fileprivate var components: DateComponents {
return (calendar as NSCalendar).components([.year, .month, .weekday, .day, .hour, .minute, .second], from: self)
}
fileprivate var calendar: NSCalendar {
return (NSCalendar.current as NSCalendar)
}
// MARK: - Initialize
static func date(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int) -> Date {
let now = Date()
return now.change(year: year, month: month, day: day, hour: hour, minute: minute, second: second)
}
static func date(year: Int, month: Int, day: Int) -> Date {
return Date.date(year: year, month: month, day: day, hour: 0, minute: 0, second: 0)
}
static func today() -> Date {
let now = Date()
return Date.date(year: now.year, month: now.month, day: now.day)
}
static func yesterday() -> Date {
return today() - 1.day
}
static func tomorrow() -> Date {
return today() + 1.day
}
// MARK: - Initialize by setting components
/**
Initialize a date by changing date components of the receiver.
*/
func change(year: Int? = nil, month: Int? = nil, day: Int? = nil, hour: Int? = nil, minute: Int? = nil, second: Int? = nil) -> Date! {
var components = self.components
components.year = year ?? self.year
components.month = month ?? self.month
components.day = day ?? self.day
components.hour = hour ?? self.hour
components.minute = minute ?? self.minute
components.second = second ?? self.second
return calendar.date(from: components)
}
/**
Initialize a date by changing the weekday of the receiver.
*/
func change(weekday: Int) -> Date! {
return self - (self.weekday - weekday).days
}
/**
Initialize a date by changing the time zone of receiver.
*/
func change(timeZone: NSTimeZone) -> Date! {
let originalTimeZone = calendar.timeZone
calendar.timeZone = timeZone as TimeZone
let newDate = calendar.date(from: components)!
newDate.calendar.timeZone = timeZone as TimeZone
objc_setAssociatedObject(newDate, &AssociatedKeys.TimeZone, timeZone, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
calendar.timeZone = originalTimeZone
return newDate
}
// MARK: - Initialize a date at beginning/end of each units
var beginningOfYear: Date {
return change(month: 1, day: 1, hour: 0, minute: 0, second: 0)
}
var endOfYear: Date {
return (beginningOfYear + 1.year).addingTimeInterval(-1)
}
var beginningOfMonth: Date {
return change(day: 1, hour: 0, minute: 0, second: 0)
}
var endOfMonth: Date {
return (beginningOfMonth + 1.month).addingTimeInterval(-1)
}
var beginningOfWeek: Date {
return change(weekday: 1).beginningOfDay
}
var endOfWeek: Date {
return (beginningOfWeek + 1.week).addingTimeInterval(-1)
}
var beginningOfDay: Date {
return change(hour: 0, minute: 0, second: 0)
}
var endOfDay: Date {
return (beginningOfDay + 1.day).addingTimeInterval(-1)
}
var beginningOfHour: Date {
return change(minute: 0, second: 0)
}
var endOfHour: Date {
return (beginningOfHour + 1.hour).addingTimeInterval(-1)
}
var beginningOfMinute: Date {
return change(second: 0)
}
var endOfMinute: Date {
return (beginningOfMinute + 1.minute).addingTimeInterval(-1)
}
// MARK: - Format dates
func stringFromFormat(_ format: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = format
return formatter.string(from: self)
}
// MARK: - Differences
func differenceWith(_ date: Date, inUnit unit: NSCalendar.Unit) -> Int {
return (calendar.components(unit, from: self, to: date, options: []) as NSDateComponents).value(forComponent: unit)
}
}
| mit | 9c2fad1049743c4564c3b176dc56ca21 | 26.890995 | 138 | 0.607307 | 4.188612 | false | false | false | false |
ipraba/Bean | Pod/Classes/Cache.swift | 1 | 1628 | //
// BeanBag.swift
// Pods
//
// Created by Prabaharan Elangovan on 17/12/15.
//
//
import Foundation
/**
Cache is a lightweight wrapper around NSCache
*/
public class Cache {
static public let sharedCache = Cache() //Singleton
let cache = NSCache()
//MARK: Initializers
init(cacheCountLimit: Int, cacheSizeLimit: Int) {
cache.countLimit = cacheCountLimit
cache.totalCostLimit = cacheSizeLimit
}
convenience init(){
self.init(cacheCountLimit: 0,cacheSizeLimit: 0)
}
//MARK: Public Methods
public func storeImage(image: UIImage, url: String) {
cache.setObject(image, forKey: url)
}
public func storeAnyObject(any: AnyObject, url: String) {
cache.setObject(any, forKey: url)
}
public func getJson(url: String) -> [String: AnyObject]? {
if let obj = cache.objectForKey(url) {
return obj as? [String: AnyObject]
}
return nil
}
public func getData(url: String) -> NSData? {
if let obj = cache.objectForKey(url) {
return obj as? NSData
}
return nil
}
public func clearCache() {
cache.removeAllObjects()
}
public func getImage(url: String) -> UIImage? {
if let obj = cache.objectForKey(url) {
switch (obj.self) {
case is UIImage:
return obj as? UIImage
case is NSData:
return UIImage(data: obj as! NSData)
default :
return nil
}
}
return nil
}
}
| mit | 0f8b809274fc85574c7510d9334cf864 | 21.30137 | 62 | 0.558354 | 4.38814 | false | false | false | false |
kstaring/swift | test/attr/attr_noreturn.swift | 4 | 2776 | // RUN: %target-parse-verify-swift
@noreturn func noReturn1(_: Int) {}
// expected-error@-1 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{1-11=}}{{33-33= -> Never }}
@noreturn func noReturn2(_: Int)
{}
// expected-error@-2 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{1-11=}}{{33-33= -> Never}}
@noreturn
func noReturn3(_: Int)
{}
// expected-error@-3 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{1-10=}}{{23-23= -> Never}}
@noreturn func noReturnInt1(_: Int) -> Int {}
// expected-error@-1 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{1-11=}}{{40-43=Never}}
@noreturn func noReturnInt2(_: Int) -> Int
{}
// expected-error@-2 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{1-11=}}{{40-43=Never}}
@noreturn func noReturnThrows1(_: Int) throws {}
// expected-error@-1 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{1-11=}}{{46-46= -> Never }}
@noreturn func noReturnThrows2(_: Int) throws
{}
// expected-error@-2 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{1-11=}}{{46-46= -> Never}}
@noreturn func noReturnThrowsInt1(_: Int) throws -> Int {}
// expected-error@-1 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{1-11=}}{{53-56=Never}}
@noreturn func noReturnThrowsInt2(_: Int) throws -> Int
{}
// expected-error@-2 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{1-11=}}{{53-56=Never}}
// Test that error recovery gives us the 'Never' return type
let x: Never = noReturn1(0) // No error
// @noreturn in function type declarations
let valueNoReturn: @noreturn () -> ()
// expected-error@-1 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{20-30=}}{{36-38=Never}}
let valueNoReturnInt: @noreturn () -> Int
// expected-error@-1 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{23-33=}}{{39-42=Never}}
let valueNoReturnInt2: @noreturn
() -> Int
// expected-error@-2 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{24-1=}}{{7-10=Never}}
let valueNoReturn2: @noreturn () -> () = {}
// expected-error@-1 {{'@noreturn' has been removed; functions that never return should have a return type of 'Never' instead}}{{21-31=}}{{37-39=Never}}
| apache-2.0 | ec729d089955b2e74bdac7269ea868c9 | 53.431373 | 156 | 0.692363 | 3.716198 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.