repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
audiokit/AudioKit | Tests/AudioKitTests/Node Tests/Effects Tests/Filter Tests/HighShelfFilterTests.swift | 2 | 1117 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AudioKit
import XCTest
class HighShelfFilterTests: XCTestCase {
func testDefault() {
let engine = AudioEngine()
let input = Oscillator()
engine.output = HighShelfFilter(input)
input.start()
let audio = engine.startTest(totalDuration: 1.0)
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}
func testGain() {
let engine = AudioEngine()
let input = Oscillator()
engine.output = HighShelfFilter(input, gain: 1)
input.start()
let audio = engine.startTest(totalDuration: 1.0)
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}
func testParameters() {
let engine = AudioEngine()
let input = Oscillator()
engine.output = HighShelfFilter(input, cutOffFrequency: 400, gain: 1)
input.start()
let audio = engine.startTest(totalDuration: 1.0)
audio.append(engine.render(duration: 1.0))
testMD5(audio)
}
}
| mit |
maxim-pervushin/Overlap | Overlap/App/View Controllers/TimezonePicker/TimezonePickerViewController.swift | 1 | 3679 | //
// TimeZonePickerViewController.swift
// Overlap
//
// Created by Maxim Pervushin on 01/05/16.
// Copyright © 2016 Maxim Pervushin. All rights reserved.
//
import UIKit
class TimeZonePickerViewController: UIViewController {
// MARK: @IB
@IBOutlet weak var tableView: UITableView?
@IBOutlet weak var searchBar: UISearchBar?
@IBAction func cancelButtonAction(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func pickButtonAction(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
finished?()
}
// MARK: public
var timeZone: NSTimeZone {
set {
_timeZoneSet = newValue
reloadData()
}
get {
return _timeZoneSet
}
}
var finished: (Void -> Void)?
// MARK: override
override func viewDidLoad() {
super.viewDidLoad()
for name in NSTimeZone.knownTimeZoneNames() {
if let timeZone = NSTimeZone(name: name) {
_timeZoneList.append(timeZone)
}
}
updateFilter()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
reloadData()
}
// MARK: private
private var _timeZoneSet = NSTimeZone.localTimeZone()
private var _timeZoneList = [NSTimeZone]()
private var _timeZoneListFiltered = [NSTimeZone]() {
didSet {
reloadData()
}
}
private func updateFilter() {
if let searchBar = searchBar, text = searchBar.text where text.characters.count > 0 {
_timeZoneListFiltered = _timeZoneList.filter({
timezone -> Bool in
let name = timezone.name
if name.rangeOfString(text) != nil {
return true
}
if let localizedName = timezone.localizedName(.Standard, locale: NSLocale.currentLocale()) where localizedName.rangeOfString(text) != nil {
return true
}
return false
})
} else {
_timeZoneListFiltered = _timeZoneList
}
}
private func reloadData() {
tableView?.reloadData()
}
}
extension TimeZonePickerViewController: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return _timeZoneListFiltered.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(TimeZoneCell.identifier, forIndexPath: indexPath) as! TimeZoneCell
let timezone = _timeZoneListFiltered[indexPath.row]
if timezone == self._timeZoneSet {
cell.accessoryType = .Checkmark
} else {
cell.accessoryType = .None
}
cell.timezone = timezone
return cell
}
}
extension TimeZonePickerViewController: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let
cell = tableView.cellForRowAtIndexPath(indexPath) as? TimeZoneCell,
timezone = cell.timezone {
self.timeZone = timezone
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
extension TimeZonePickerViewController: UISearchBarDelegate {
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
updateFilter()
}
} | mit |
ainopara/Stage1st-Reader | Stage1st/Manager/Navigation/S1Animator.swift | 1 | 6384 | //
// S1Animator.swift
// Stage1st
//
// Created by Zheng Li on 5/14/16.
// Copyright © 2016 Renaissance. All rights reserved.
//
import UIKit
import CocoaLumberjack
class S1Animator: NSObject, UIViewControllerAnimatedTransitioning {
enum Direction: Int {
case push
case pop
}
let direction: Direction
init(direction: Direction) {
self.direction = direction
super.init()
}
func transitionDuration(using _: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard
let toViewController = transitionContext.viewController(forKey: .to),
let fromViewController = transitionContext.viewController(forKey: .from)
else {
assert(false)
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
return
}
let containerView = transitionContext.containerView
// TODO: remove this workaround once it is no more necessary
toViewController.view.frame = containerView.bounds
// FIXME: will take no effect if toViewController clipsToBounds == true, maybe add the effect to a temp view
toViewController.view.layer.shadowOpacity = 0.5
toViewController.view.layer.shadowRadius = 5.0
toViewController.view.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
toViewController.view.layer.shadowPath = UIBezierPath(rect: toViewController.view.bounds).cgPath
let containerViewWidth = containerView.frame.width
switch direction {
case .push:
containerView.insertSubview(toViewController.view, aboveSubview: fromViewController.view)
fromViewController.view.transform = .identity
toViewController.view.transform = CGAffineTransform(translationX: containerViewWidth, y: 0.0)
case .pop:
containerView.insertSubview(toViewController.view, belowSubview: fromViewController.view)
fromViewController.view.transform = .identity
toViewController.view.transform = CGAffineTransform(translationX: -containerViewWidth / 2.0, y: 0.0)
}
let options: UIView.AnimationOptions = direction == .pop ? .curveLinear : .curveEaseInOut
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0.0, options: options, animations: { [weak self] in
guard let strongSelf = self else { return }
switch strongSelf.direction {
case .push:
fromViewController.view.transform = CGAffineTransform(translationX: -containerViewWidth / 2.0, y: 0.0)
toViewController.view.transform = .identity
case .pop:
fromViewController.view.transform = CGAffineTransform(translationX: containerViewWidth, y: 0.0)
toViewController.view.transform = .identity
}
}) { finished in
fromViewController.view.transform = .identity
toViewController.view.transform = .identity
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
// MARK: -
protocol CardWithBlurredBackground {
var backgroundBlurView: UIVisualEffectView { get }
var containerView: UIView { get }
}
class S1ModalAnimator: NSObject, UIViewControllerAnimatedTransitioning {
let presentType: PresentType
enum PresentType {
case present
case dismissal
}
init(presentType: PresentType) {
self.presentType = presentType
}
func transitionDuration(using _: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
switch presentType {
case .present:
guard let toViewController = transitionContext.viewController(forKey: .to) else {
assert(false)
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
return
}
let containerView = transitionContext.containerView
guard let targetViewController = toViewController as? CardWithBlurredBackground else {
assert(false)
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
return
}
let blurredBackgroundView = targetViewController.backgroundBlurView
let contentView = targetViewController.containerView
contentView.alpha = 0.0
contentView.transform = CGAffineTransform.init(scaleX: 0.9, y: 0.9)
containerView.addSubview(toViewController.view)
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
blurredBackgroundView.effect = UIBlurEffect(style: .dark)
contentView.alpha = 1.0
contentView.transform = CGAffineTransform.identity
}) { _ in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
case .dismissal:
guard let fromViewController = transitionContext.viewController(forKey: .from) else {
assert(false)
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
return
}
guard let targetViewController = fromViewController as? CardWithBlurredBackground else {
assert(false)
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
return
}
let blurredBackgroundView = targetViewController.backgroundBlurView
let contentView = targetViewController.containerView
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
contentView.alpha = 0.0
contentView.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
blurredBackgroundView.effect = nil
}) { _ in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
}
| bsd-3-clause |
mbigatti/ImagesGenerator | ImagesGenerator/AppDelegate.swift | 1 | 529 | //
// AppDelegate.swift
// ImagesGenerator
//
// Created by Massimiliano Bigatti on 19/06/15.
// Copyright © 2015 Massimiliano Bigatti. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
/*
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
*/
}
| mit |
ainopara/Stage1st-Reader | Stage1st/Manager/Parser.swift | 1 | 3641 | //
// Parser.swift
// Stage1st
//
// Created by Zheng Li on 2019/3/9.
// Copyright © 2019 Renaissance. All rights reserved.
//
import Foundation
enum Parser {
static func extractTopic(from urlString: String) -> S1Topic? {
// Current Html Scheme
let result1 = S1Global.regexExtract(from: urlString, withPattern: #"thread-([0-9]+)-([0-9]+)-[0-9]+\.html"#, andColums: [1, 2]) ?? []
if result1.count == 2 {
let topicIDString = result1[0]
let topicPageString = result1[1]
if let topicID = Int(topicIDString), let topicPage = Int(topicPageString) {
let topic = S1Topic(topicID: NSNumber(value: topicID))
topic.lastViewedPage = NSNumber(value: topicPage)
S1LogDebug("Extract Topic \(topic)")
return topic
}
}
// Old Html Scheme
let result2 = S1Global.regexExtract(from: urlString, withPattern: #""read-htm-tid-([0-9]+)\.html""#, andColums: [1]) ?? []
if result2.count == 1 {
let topicIDString = result2[0]
if let topicID = Int(topicIDString) {
let topic = S1Topic(topicID: NSNumber(value: topicID))
topic.lastViewedPage = 1
S1LogDebug("Extract Topic \(topic)")
return topic
}
}
// PHP Scheme
let queryDict = self.extractQuerys(from: urlString)
if
let topicIDString = queryDict["tid"],
let topicPageString = queryDict["page"],
let topicID = Int(topicIDString),
let topicPage = Int(topicPageString)
{
let topic = S1Topic(topicID: NSNumber(value: topicID))
topic.lastViewedPage = NSNumber(value: topicPage)
topic.locateFloorIDTag = URLComponents(string: urlString)?.fragment
S1LogDebug("Extract Topic \(topic)")
return topic
}
S1LogError("Failed to Extract topic from \(urlString)")
return nil
}
static func extractQuerys(from urlString: String) -> [String: String] {
var result = [String: String]()
guard let components = URLComponents(string: urlString) else {
return result
}
for item in components.queryItems ?? [] {
result[item.name] = item.value
}
return result
}
static func replyFloorInfo(from responseString: String?) -> [String: String]? {
guard let responseString = responseString else { return nil }
let pattern = "<input[^>]*name=\"([^>\"]*)\"[^>]*value=\"([^>\"]*)\""
let re = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines])
let results = re.matches(in: responseString, options: [], range: NSRange(responseString.startIndex..., in: responseString))
guard results.count > 0 else {
return nil
}
var info = [String: String]()
for result in results {
if
let keyRange = Range(result.range(at: 1), in: responseString),
let valueRange = Range(result.range(at: 2), in: responseString)
{
let key = responseString[keyRange]
let value = responseString[valueRange]
if key == "noticetrimstr" {
info[String(key)] = String(value).aibo_stringByUnescapingFromHTML()
} else {
info[String(key)] = String(value)
}
} else {
assertionFailure()
}
}
return info
}
}
| bsd-3-clause |
tensorflow/swift-models | Gym/PPO/Categorical.swift | 1 | 4105 | // Copyright 2020 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import TensorFlow
// Below code comes from eaplatanios/swift-rl:
// https://github.com/eaplatanios/swift-rl/blob/master/Sources/ReinforcementLearning/Utilities/Protocols.swift
public protocol Batchable {
func flattenedBatch(outerDimCount: Int) -> Self
func unflattenedBatch(outerDims: [Int]) -> Self
}
public protocol DifferentiableBatchable: Batchable, Differentiable {
@differentiable(wrt: self)
func flattenedBatch(outerDimCount: Int) -> Self
@differentiable(wrt: self)
func unflattenedBatch(outerDims: [Int]) -> Self
}
extension Tensor: Batchable {
public func flattenedBatch(outerDimCount: Int) -> Tensor {
if outerDimCount == 1 {
return self
}
var newShape = [-1]
for i in outerDimCount..<rank {
newShape.append(shape[i])
}
return reshaped(to: TensorShape(newShape))
}
public func unflattenedBatch(outerDims: [Int]) -> Tensor {
if rank > 1 {
return reshaped(to: TensorShape(outerDims + shape.dimensions[1...]))
}
return reshaped(to: TensorShape(outerDims))
}
}
extension Tensor: DifferentiableBatchable where Scalar: TensorFlowFloatingPoint {
@differentiable(wrt: self)
public func flattenedBatch(outerDimCount: Int) -> Tensor {
if outerDimCount == 1 {
return self
}
var newShape = [-1]
for i in outerDimCount..<rank {
newShape.append(shape[i])
}
return reshaped(to: TensorShape(newShape))
}
@differentiable(wrt: self)
public func unflattenedBatch(outerDims: [Int]) -> Tensor {
if rank > 1 {
return reshaped(to: TensorShape(outerDims + shape.dimensions[1...]))
}
return reshaped(to: TensorShape(outerDims))
}
}
// Below code comes from eaplatanios/swift-rl:
// https://github.com/eaplatanios/swift-rl/blob/master/Sources/ReinforcementLearning/Distributions/Distribution.swift
public protocol Distribution {
associatedtype Value
func entropy() -> Tensor<Float>
/// Returns a random sample drawn from this distribution.
func sample() -> Value
}
public protocol DifferentiableDistribution: Distribution, Differentiable {
@differentiable(wrt: self)
func entropy() -> Tensor<Float>
}
// Below code comes from eaplatanios/swift-rl:
// https://github.com/eaplatanios/swift-rl/blob/master/Sources/ReinforcementLearning/Distributions/Categorical.swift
public struct Categorical<Scalar: TensorFlowIndex>: DifferentiableDistribution, KeyPathIterable {
/// Log-probabilities of this categorical distribution.
public var logProbabilities: Tensor<Float>
@inlinable
@differentiable(wrt: probabilities)
public init(probabilities: Tensor<Float>) {
self.logProbabilities = log(probabilities)
}
@inlinable
@differentiable(wrt: self)
public func entropy() -> Tensor<Float> {
-(logProbabilities * exp(logProbabilities)).sum(squeezingAxes: -1)
}
@inlinable
public func sample() -> Tensor<Scalar> {
let seed = Context.local.randomSeed
let outerDimCount = self.logProbabilities.rank - 1
let logProbabilities = self.logProbabilities.flattenedBatch(outerDimCount: outerDimCount)
let multinomial: Tensor<Scalar> = _Raw.multinomial(
logits: logProbabilities,
numSamples: Tensor<Int32>(1),
seed: Int64(seed.graph),
seed2: Int64(seed.op))
let flattenedSamples = multinomial.gathering(atIndices: Tensor<Int32>(0), alongAxis: 1)
return flattenedSamples.unflattenedBatch(
outerDims: [Int](self.logProbabilities.shape.dimensions[0..<outerDimCount]))
}
}
| apache-2.0 |
CodePath2017Group4/travel-app | RoadTripPlanner/TripReviewViewController.swift | 1 | 785 | //
// TripReviewViewController.swift
// RoadTripPlanner
//
// Created by Diana Fisher on 10/30/17.
// Copyright © 2017 RoadTripPlanner. All rights reserved.
//
import UIKit
class TripReviewViewController: UIViewController {
static func storyboardInstance() -> TripReviewViewController? {
let storyboard = UIStoryboard(name: String(describing: self), bundle: nil)
return storyboard.instantiateInitialViewController() as? TripReviewViewController
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
pyconjp/pyconjp-ios | PyConJP/View/UITableViewCell/StaffTableViewCell.swift | 1 | 1844 | //
// StaffTableViewCell.swift
// PyConJP
//
// Created by Yutaro Muta on 9/10/16.
// Copyright © 2016 PyCon JP. All rights reserved.
//
import UIKit
class StaffTableViewCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var roleLabel: UILabel!
@IBOutlet weak var facebookButton: UIButton!
@IBOutlet weak var twitterButton: UIButton!
static let estimatedRowHeight: CGFloat = 100
private var facebookAction: (() -> Void)?
private var twitterAction: (() -> Void)?
override func prepareForReuse() {
nameLabel.text = nil
roleLabel.text = nil
toggleFacebookButton(enabled: false)
toggleTwitterButton(enabled: false)
}
func fill(staff: Staff, onFacebookButton: @escaping (() -> Void), onTwitterButton: @escaping (() -> Void)) {
nameLabel.text = staff.name
roleLabel.text = staff.role
toggleFacebookButton(enabled: !staff.facebook.isEmpty)
toggleTwitterButton(enabled: !staff.twitter.isEmpty)
facebookAction = onFacebookButton
twitterAction = onTwitterButton
}
private func toggleFacebookButton(enabled: Bool) {
facebookButton.isEnabled = enabled
facebookButton.backgroundColor = enabled ? UIColor.facebook : UIColor.silver
}
private func toggleTwitterButton(enabled: Bool) {
twitterButton.isEnabled = enabled
twitterButton.backgroundColor = enabled ? UIColor.twitter : UIColor.silver
}
@IBAction func onFacebookButton(_ sender: UIButton) {
guard let facebookAction = facebookAction else { return }
facebookAction()
}
@IBAction func onTwitterButton(_ sender: UIButton) {
guard let twitterAction = twitterAction else { return }
twitterAction()
}
}
| mit |
apple/swift | test/ModuleInterface/concurrency.swift | 7 | 1434 | // RUN: %empty-directory(%t)
// RUN: %target-swift-emit-module-interface(%t/Library.swiftinterface) %s -enable-experimental-concurrency -DLIBRARY -module-name Library
// RUN: %target-swift-typecheck-module-from-interface(%t/Library.swiftinterface) -enable-experimental-concurrency
// REQUIRES: concurrency
#if LIBRARY
@available(SwiftStdlib 5.5, *)
public func fn() async {
fatalError()
}
@available(SwiftStdlib 5.5, *)
public func reasyncFn(_: () async -> ()) reasync {
fatalError()
}
@available(SwiftStdlib 5.5, *)
public func takesSendable(
_ block: @Sendable @escaping () async throws -> Void
) { }
// RUN: %target-typecheck-verify-swift -enable-experimental-concurrency -I %t
#else
import Library
@available(SwiftStdlib 5.5, *)
func callFn() async {
await fn()
}
#endif
// RUN: %FileCheck %s <%t/Library.swiftinterface
// CHECK: // swift-module-flags:{{.*}} -enable-experimental-concurrency
// CHECK: public func fn() async
// CHECK: public func reasyncFn(_: () async -> ()) reasync
// CHECK: public func takesSendable(_ block: @escaping @Sendable () async throws ->
// RUN: %target-swift-emit-module-interface(%t/Library.swiftinterface) %s -enable-experimental-concurrency -DLIBRARY -module-name Library -module-interface-preserve-types-as-written
// RUN: %target-swift-typecheck-module-from-interface(%t/Library.swiftinterface) -enable-experimental-concurrency
// RUN: %FileCheck %s <%t/Library.swiftinterface
| apache-2.0 |
kaojohnny/CoreStore | Sources/Observing/SectionBy.swift | 1 | 3001 | //
// SectionBy.swift
// CoreStore
//
// Copyright © 2015 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
#if os(iOS) || os(watchOS) || os(tvOS)
// MARK: - SectionBy
/**
The `SectionBy` clause indicates the key path to use to group the `ListMonitor` objects into sections. An optional closure can also be provided to transform the value into an appropriate section name:
```
let monitor = CoreStore.monitorSectionedList(
From(MyPersonEntity),
SectionBy("age") { "Age \($0)" },
OrderBy(.Ascending("lastName"))
)
```
*/
public struct SectionBy {
/**
Initializes a `SectionBy` clause with the key path to use to group `ListMonitor` objects into sections
- parameter sectionKeyPath: the key path to use to group the objects into sections
*/
public init(_ sectionKeyPath: KeyPath) {
self.init(sectionKeyPath, { $0 })
}
/**
Initializes a `SectionBy` clause with the key path to use to group `ListMonitor` objects into sections, and a closure to transform the value for the key path to an appropriate section name
- Important: Some utilities (such as `ListMonitor`s) may keep `SectionBy`s in memory and may thus introduce retain cycles if reference captures are not handled properly.
- parameter sectionKeyPath: the key path to use to group the objects into sections
- parameter sectionIndexTransformer: a closure to transform the value for the key path to an appropriate section name
*/
public init(_ sectionKeyPath: KeyPath, _ sectionIndexTransformer: (sectionName: String?) -> String?) {
self.sectionKeyPath = sectionKeyPath
self.sectionIndexTransformer = sectionIndexTransformer
}
// MARK: Internal
internal let sectionKeyPath: KeyPath
internal let sectionIndexTransformer: (sectionName: KeyPath?) -> String?
}
#endif
| mit |
cnoon/swift-compiler-crashes | fixed/01605-swift-protocoltype-canonicalizeprotocols.swift | 11 | 216 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol B:b{func^(a!func
protocol b{protocol a | mit |
VirrageS/TDL | TDL/DetailTagViewController.swift | 1 | 4121 | import UIKit
class DetailTagViewController: UITableViewController, SlideNavigationControllerDelegate {
var detailTagTasks = [Task]()
var tag: Tag?
func shouldDisplayMenu() -> Bool {
return false
}
init(tag: Tag) {
super.init(nibName: nil, bundle: nil)
title = tag.name
self.tag = tag
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
detailTagTasks.removeAll(keepCapacity: false)
if allTasks.count > 0 {
for i in 0...allTasks.count-1 {
if allTasks[i].tag == nil {
if self.tag!.name.lowercaseString == "none" {
detailTagTasks.append(allTasks[i])
}
} else {
if allTasks[i].tag!.name.lowercaseString == self.tag!.name.lowercaseString {
detailTagTasks.append(allTasks[i])
}
}
}
}
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
if tag?.enabled != false {
let addButtonItem = UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: "openEditTagViewController:")
navigationItem.rightBarButtonItem = addButtonItem
}
tableView.backgroundColor = UIColor.whiteColor()
tableView.separatorColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0)
tableView.registerClass(TaskCell.self, forCellReuseIdentifier: NSStringFromClass(TaskCell))
tableView.registerClass(NoTaskCell.self, forCellReuseIdentifier: NSStringFromClass(NoTaskCell))
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (detailTagTasks.count > 0 ? detailTagTasks.count : 1)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (detailTagTasks.count > 0) {
let cell = tableView.dequeueReusableCellWithIdentifier(NSStringFromClass(TaskCell), forIndexPath: indexPath) as! TaskCell
cell.configureCell(detailTagTasks[indexPath.row])
return cell as TaskCell
}
let cell = tableView.dequeueReusableCellWithIdentifier(NSStringFromClass(NoTaskCell), forIndexPath: indexPath) as! NoTaskCell
tableView.scrollEnabled = false
return cell as NoTaskCell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
// Row height for closed cell
if (detailTagTasks.count > 0) {
return taskCellHeight
}
return noTaskCellHeight
}
override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
let cell: AnyObject? = tableView.cellForRowAtIndexPath(indexPath)
if cell is NoTaskCell {
return false
}
return true
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func openEditTagViewController(sender: AnyObject) {
let editTagViewController = EditTagViewController(tag: tag!)
let slideNavigation = SlideNavigationController().sharedInstance()
slideNavigation._delegate = editTagViewController
// Check if navigationController is nil
if navigationController == nil {
println("openAddTaskController - navigationController is nil")
return
}
navigationController!.pushViewController(editTagViewController, animated: true)
}
} | mit |
cloudinary/cloudinary_ios | Cloudinary/Classes/Core/Features/CacheSystem/StorehouseLibrary/Core/Warehouse.swift | 1 | 5628 | //
// Warehouse.swift
//
// Copyright (c) 2020 Cloudinary (http://cloudinary.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
import Dispatch
///
/// Manage a storehouse with wares, generic over SoredType.
///
internal final class Warehouse<SoredType>
{
/// MARK: - Typealias
internal typealias Item = SoredType
/// MARK: - Private Properties
private let accessor : StorehouseAccessor<Item>
private let storehouse : StorehouseHybrid <Item>
/// MARK: - Public Computed Properties
internal var memoryCapacity : Int {
return accessor.memoryCapacity
}
internal var diskCapacity : Int {
return accessor.diskCapacity
}
internal var currentMemoryUsage : Int {
return accessor.currentMemoryUsage
}
internal var currentDiskUsage: Int {
return accessor.currentDiskUsage
}
/// MARK: - Initializers
///
/// Initialize a warehouse with configuration options.
///
/// - Parameters:
/// - memoryConfig: In memory storehouse configuration
/// - diskConfig : Disk storehouse configuration
/// - transformer : A transformer to use for conversion of the stored data into the file system
///
/// - Throws: Throw StorehouseError if any.
///
internal convenience init(memoryConfig: StorehouseConfigurationInMemory, diskConfig: StorehouseConfigurationDisk, transformer: StorehouseTransformer<Item>) throws
{
let disk = try StorehouseOnDisk<Item>(configuration: diskConfig, transformer: transformer)
let memory = StorehouseInMemory<Item>(configuration: memoryConfig)
let storage = StorehouseHybrid<Item>(inMemory: memory, onDisk: disk)
self.init(hybrid: storage)
}
///
/// Initialize a warehouse with configuration options.
///
/// - Parameters:
/// - memoryConfig: In memory storehouse configuration
/// - diskConfig : Disk storehouse configuration
/// - transformer : A transformer to use for conversion of the stored data into the file system
///
/// - Throws: Throw StorehouseError if any.
///
internal convenience init(purgingConfig: StorehouseConfigurationAutoPurging, diskConfig: StorehouseConfigurationDisk, transformer: StorehouseTransformer<Item>) throws
{
let disk = try StorehouseOnDisk (configuration: diskConfig, transformer: transformer)
let memory = StorehouseAutoPurging(configuration: purgingConfig, transformer: transformer)
let storage = StorehouseHybrid(inMemory: memory, onDisk: disk)
self.init(hybrid: storage)
}
///
/// Initialise a warehouse with a prepared storehouse.
///
/// - Parameter storage: The storehouse to use
internal init(hybrid storage: StorehouseHybrid<Item>)
{
let queue = DispatchQueue(label: "com.cloudinary.accessQueue", attributes: [.concurrent])
self.storehouse = storage
self.accessor = StorehouseAccessor(storage: storage, queue: queue)
}
internal func updateCacheCapacity(purgingConfig: StorehouseConfigurationAutoPurging, diskConfig: StorehouseConfigurationDisk, transformer: StorehouseTransformer<Item>) throws {
let disk = try StorehouseOnDisk (configuration: diskConfig, transformer: transformer)
let memory = StorehouseAutoPurging(configuration: purgingConfig, transformer: transformer)
let storage = StorehouseHybrid(inMemory: memory, onDisk: disk)
accessor.replaceStorage(storage)
}
}
extension Warehouse : StorehouseProtocol
{
@discardableResult
internal func entry(forKey key: String) throws -> StorehouseEntry<Item>
{
return try accessor.entry(forKey: key)
}
internal func removeObject(forKey key: String) throws
{
try accessor.removeObject(forKey: key)
}
internal func setObject(_ object: Item, forKey key: String, expiry: StorehouseExpiry? = nil) throws
{
try accessor.setObject(object, forKey: key, expiry: expiry)
}
internal func removeAll() throws
{
try accessor.removeAll()
}
internal func removeExpiredObjects() throws
{
try accessor.removeExpiredObjects()
}
internal func removeStoredObjects(since date: Date) throws
{
try accessor.removeStoredObjects(since: date)
}
internal func removeObjectIfExpired(forKey key: String) throws
{
try accessor.removeObjectIfExpired(forKey: key)
}
}
| mit |
n-miyo/ViewSizeChecker | ViewSizeChecker/ViewController.swift | 1 | 4407 | // -*- mode:swift -*-
import UIKit
class ViewController: UITableViewController {
@IBOutlet weak var displayScaleLabel: UILabel!
@IBOutlet weak var horizontalSizeLabel: UILabel!
@IBOutlet weak var verticalSizeLabel: UILabel!
@IBOutlet weak var screenScaleLabel: UILabel!
@IBOutlet weak var screenNativeScaleLabel: UILabel!
@IBOutlet weak var screenBoundsLabel: UILabel!
@IBOutlet weak var screenNativeBoundsLabel: UILabel!
@IBOutlet weak var navigationBarSizeLabel: UILabel!
@IBOutlet weak var tabBarSizeLabel: UILabel!
var hwMachine: String!
var displayScale: String!
var horizontalSize: String!
var verticalSize: String!
var screenScale: String!
var screenNativeScale: String!
var screenBounds: String!
var screenNativeBounds: String!
var navigationBarSize: String!
var tabBarSize: String!
override func viewDidLoad() {
super.viewDidLoad()
hwMachine = sysctlByName("hw.machine")
updateViews()
}
override func viewWillTransitionToSize(
size: CGSize,
withTransitionCoordinator coordinator:
UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(
size, withTransitionCoordinator:coordinator)
coordinator.animateAlongsideTransition(
nil,
completion: {
context in
self.updateViews()
})
}
@IBAction func pressedActionButton(sender: UIBarButtonItem) {
updateValues()
let a: [String] = [
"[\(hwMachine)]",
"",
"UITraitCollection:",
" displayScale: \(displayScale)",
" horizontalSize: \(horizontalSize)",
" verticalSize: \(verticalSize)",
"",
"UIScreen:",
" scale: \(screenScale)",
" nativeScale: \(screenNativeScale)",
" screenBounds: \(screenBounds)",
" nativeBounds: \(screenNativeBounds)",
"",
"MISC:",
" NavigationBar size: \(navigationBarSize)",
" TabBar size: \(tabBarSize)"
]
var s = ""
for x in a {
s += "\(x)\n"
}
let avc =
UIActivityViewController(activityItems:[s], applicationActivities:nil)
avc.popoverPresentationController?.barButtonItem = sender
navigationController!.presentViewController(
avc, animated:true, completion:nil)
}
// MARK: Private
private func updateViews() {
updateValues()
navigationItem.title = hwMachine
displayScaleLabel.text = displayScale
horizontalSizeLabel.text = horizontalSize
verticalSizeLabel.text = verticalSize
screenScaleLabel.text = screenScale
screenNativeScaleLabel.text = screenNativeScale
screenBoundsLabel.text = screenBounds
screenNativeBoundsLabel.text = screenNativeBounds
navigationBarSizeLabel.text = navigationBarSize
tabBarSizeLabel.text = tabBarSize
}
private func updateValues() {
let tc = self.view.traitCollection
displayScale = "\(tc.displayScale)"
horizontalSize = "\(tc.horizontalSizeClass)"
verticalSize = "\(tc.verticalSizeClass)"
let ms = UIScreen.mainScreen()
screenScale = "\(ms.scale)"
screenNativeScale = "\(ms.nativeScale)"
screenBounds = NSStringFromCGSize(ms.bounds.size)
screenNativeBounds = NSStringFromCGSize(ms.nativeBounds.size)
let n = navigationController!.navigationBar
navigationBarSize = NSStringFromCGSize(n.frame.size)
let t = tabBarController!.tabBar
tabBarSize = NSStringFromCGSize(t.frame.size)
}
private func sysctlByName(name: String) -> String {
return name.withCString {
cs in
var s: UInt = 0
sysctlbyname(cs, nil, &s, nil, 0)
var v = [CChar](count: Int(s)/sizeof(CChar), repeatedValue: 0)
sysctlbyname(cs, &v, &s, nil, 0)
return String.fromCString(v)!
}
}
}
extension UIUserInterfaceSizeClass: Printable {
public var description: String {
switch self {
case .Compact:
return "Compact"
case .Regular:
return "Regular"
default:
return "Unspecified"
}
}
}
// EOF
| mit |
Akagi201/learning-ios | swift/ios/Helloworld/Helloworld/AppDelegate.swift | 1 | 2411 | //
// AppDelegate.swift
// Helloworld
//
// Created by Bob Liu on 6/18/15.
// Copyright © 2015 Akagi201. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
NSLog("didFinishLaunchingWithOptions")
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
NSLog("applicationWillResignActive")
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
NSLog("applicationDidEnterBackground")
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
NSLog("applicationWillEnterForeground")
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
NSLog("applicationDidBecomeActive")
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
NSLog("applicationWillTerminate")
}
}
| mit |
antonio081014/LeetCode-CodeBase | Swift/expression-add-operators.swift | 1 | 1185 | class Solution {
func addOperators(_ num: String, _ target: Int) -> [String] {
var result = [String]()
let num = Array(num)
func dfs(_ path: String, _ currentIndex: Int, _ value: Int, _ lastValue: Int) {
if currentIndex == num.count {
if value == target {
result.append(path)
}
return
}
var sum = 0
for index in currentIndex ..< num.count {
if num[currentIndex] == Character("0"), index != currentIndex {
return
}
sum = sum * 10 + Int(String(num[index]))!
if currentIndex == 0 {
dfs(path + "\(sum)", index + 1, sum, sum)
} else {
dfs(path + "+\(sum)", index + 1, value + sum, sum)
dfs(path + "-\(sum)", index + 1, value - sum, -sum)
dfs(path + "*\(sum)", index + 1, value - lastValue + lastValue * sum, lastValue * sum)
}
}
}
dfs("", 0, 0, 0)
return result
}
}
| mit |
ProfileCreator/ProfileCreator | ProfileCreator/ProfileCreator/Profile Editor TableView CellView Items/PayloadCellViewItemComboBox.swift | 1 | 773 | //
// PayloadCellViewItemPopUpButton.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Cocoa
class EditorComboBox {
class func withTitles(titles: [String],
cellView: NSComboBoxDelegate) -> NSComboBox {
// ---------------------------------------------------------------------
// Create and setup ComboBox
// ---------------------------------------------------------------------
let comboBox = NSComboBox()
comboBox.translatesAutoresizingMaskIntoConstraints = false
comboBox.target = cellView
comboBox.delegate = cellView
comboBox.addItems(withObjectValues: titles)
return comboBox
}
}
| mit |
mcgraw/dojo-testing | dojo-testingTests/dojo_testingTests.swift | 1 | 739 | //
// dojo_testingTests.swift
// dojo-testingTests
//
// Created by David McGraw on 1/19/15.
// Copyright (c) 2015 David McGraw. All rights reserved.
//
import UIKit
import XCTest
class dojo_testingTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testViewControllerLoad() {
let vc = ViewController()
XCTAssertNotNil(vc.view, "View did not load for ViewController")
}
}
| mit |
away4m/Vendors | Vendors/Extensions/Optional.swift | 1 | 3911 | //
// Optional.swift
// Pods
//
// Created by ALI KIRAN on 3/26/17.
//
//
import Foundation
// https://github.com/RuiAAPeres/OptionalExtensions
public extension Optional {
/// SwifterSwift: Get self of default value (if self is nil).
///
/// let foo: String? = nil
/// print(foo.unwrapped(or: "bar")) -> "bar"
///
/// let bar: String? = "bar"
/// print(bar.unwrapped(or: "foo")) -> "bar"
///
/// - Parameter defaultValue: default value to return if self is nil.
/// - Returns: self if not nil or default value if nil.
public func unwrapped(or defaultValue: Wrapped) -> Wrapped {
// http://www.russbishop.net/improving-optionals
return self ?? defaultValue
}
/// SwifterSwift: Gets the wrapped value of an optional. If the optional is `nil`, throw a custom error.
///
/// let foo: String? = nil
/// try print(foo.unwrapped(or: MyError.notFound)) -> error: MyError.notFound
///
/// let bar: String? = "bar"
/// try print(bar.unwrapped(or: MyError.notFound)) -> "bar"
///
/// - Parameter error: The error to throw if the optional is `nil`.
/// - Returns: The value wrapped by the optional.
/// - Throws: The error passed in.
public func unwrapped(or error: Error) throws -> Wrapped {
guard let wrapped = self else { throw error }
return wrapped
}
/// SwifterSwift: Runs a block to Wrapped if not nil
///
/// let foo: String? = nil
/// foo.run { unwrappedFoo in
/// // block will never run sice foo is nill
/// print(unwrappedFoo)
/// }
///
/// let bar: String? = "bar"
/// bar.run { unwrappedBar in
/// // block will run sice bar is not nill
/// print(unwrappedBar) -> "bar"
/// }
///
/// - Parameter block: a block to run if self is not nil.
public func run(_ block: (Wrapped) -> Void) {
// http://www.russbishop.net/improving-optionals
_ = map(block)
}
/// SwifterSwift: Assign an optional value to a variable only if the value is not nil.
///
/// let someParameter: String? = nil
/// let parameters = [String:Any]() //Some parameters to be attached to a GET request
/// parameters[someKey] ??= someParameter //It won't be added to the parameters dict
///
/// - Parameters:
/// - lhs: Any?
/// - rhs: Any?
public static func ??= (lhs: inout Optional, rhs: Optional) {
guard let rhs = rhs else { return }
lhs = rhs
}
// func filter(_ predicate: (Wrapped) -> Bool) -> Optional {
// return map(predicate) == .some(true) ? self : .none
// }
// func mapNil(_ predicate: () -> Wrapped) -> Optional {
// return self ?? .some(predicate())
// }
//
// func flatMapNil(_ predicate: () -> Optional) -> Optional {
// return self ?? predicate()
// }
// func then(_ f: (Wrapped) -> Void) {
// if let wrapped = self { f(wrapped) }
// }
// func maybe<U>(_ defaultValue: U, f: (Wrapped) -> U) -> U {
// return map(f) ?? defaultValue
// }
// func onSome(_ f: (Wrapped) -> Void) -> Optional {
// then(f)
// return self
// }
// func onNone(_ f: () -> Void) -> Optional {
// if isNone { f() }
// return self
// }
//
// var isSome: Bool {
// return self != nil
// }
//
// var isNone: Bool {
// return !isSome
// }
}
// MARK: - Methods (Collection)
public extension Optional where Wrapped: Collection {
/// Check if optional is nil or empty collection.
public var isNilOrEmpty: Bool {
guard let collection = self else { return true }
return collection.isEmpty
}
}
// MARK: - Operators
infix operator ??=: AssignmentPrecedence
| mit |
zisko/swift | test/ClangImporter/static_inline.swift | 1 | 754 | // RUN: %empty-directory(%t)
// Check if SIL printing+parsing of a clang imported function works.
// RUN: %target-swift-frontend -parse-as-library -module-name=test -emit-sil %s -import-objc-header %S/Inputs/static_inline.h -o %t/test.sil
// RUN: %FileCheck < %t/test.sil %s
// RUN: %target-swift-frontend -parse-as-library -module-name=test -O -emit-ir %t/test.sil -import-objc-header %S/Inputs/static_inline.h | %FileCheck --check-prefix=CHECK-IR %s
// CHECK: sil shared [serializable] [clang c_inline_func] @c_inline_func : $@convention(c) (Int32) -> Int32
// CHECK-IR-LABEL: define{{.*}} i32 @"$S4test6testit1xs5Int32VAE_tF"(i32)
// CHECK-IR: = add {{.*}}, 27
// CHECK-IR: ret
public func testit(x: Int32) -> Int32 {
return c_inline_func(x)
}
| apache-2.0 |
JC-Hu/ColorExpert | Pods/FirebaseCoreInternal/FirebaseCore/Internal/Sources/HeartbeatLogging/RingBuffer.swift | 1 | 2808 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
/// A generic circular queue structure.
struct RingBuffer<Element>: Sequence {
/// An array of heartbeats treated as a circular queue and intialized with a fixed capacity.
private var circularQueue: [Element?]
/// The current "tail" and insert point for the `circularQueue`.
private var tailIndex: Int = 0
/// Designated initializer.
/// - Parameter capacity: An `Int` representing the capacity.
init(capacity: Int) {
circularQueue = Array(repeating: nil, count: capacity)
}
/// Pushes an element to the back of the buffer, returning the element (`Element?`) that was overwritten.
/// - Parameter element: The element to push to the back of the buffer.
/// - Returns: The element that was overwritten or `nil` if nothing was overwritten.
/// - Complexity: O(1)
@discardableResult
mutating func push(_ element: Element) -> Element? {
guard circularQueue.count > 0 else {
// Do not push if `circularQueue` is a fixed empty array.
return nil
}
defer {
// Increment index, wrapping around to the start if needed.
tailIndex += 1
tailIndex %= circularQueue.count
}
let replaced = circularQueue[tailIndex]
circularQueue[tailIndex] = element
return replaced
}
/// Pops an element from the back of the buffer, returning the element (`Element?`) that was popped.
/// - Returns: The element that was popped or `nil` if there was no element to pop.
/// - Complexity: O(1)
@discardableResult
mutating func pop() -> Element? {
guard circularQueue.count > 0 else {
// Do not pop if `circularQueue` is a fixed empty array.
return nil
}
// Decrement index, wrapping around to the back if needed.
tailIndex -= 1
if tailIndex < 0 {
tailIndex = circularQueue.count - 1
}
guard let popped = circularQueue[tailIndex] else {
return nil // There is no element to pop.
}
circularQueue[tailIndex] = nil
return popped
}
func makeIterator() -> IndexingIterator<[Element]> {
circularQueue
.compactMap { $0 } // Remove `nil` elements.
.makeIterator()
}
}
// MARK: - Codable
extension RingBuffer: Codable where Element: Codable {}
| mit |
hooman/swift | stdlib/public/core/ArrayShared.swift | 5 | 13295 | //===--- ArrayShared.swift ------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
/// This type is used as a result of the `_checkSubscript` call to associate the
/// call with the array access call it guards.
///
/// In order for the optimizer see that a call to `_checkSubscript` is semantically
/// associated with an array access, a value of this type is returned and later passed
/// to the accessing function. For example, a typical call to `_getElement` looks like
/// let token = _checkSubscript(index, ...)
/// return _getElement(index, ... , matchingSubscriptCheck: token)
@frozen
public struct _DependenceToken {
@inlinable
public init() {
}
}
/// Returns an Array of `_count` uninitialized elements using the
/// given `storage`, and a pointer to uninitialized memory for the
/// first element.
///
/// This function is referenced by the compiler to allocate array literals.
///
/// - Precondition: `storage` is `_ContiguousArrayStorage`.
@inlinable // FIXME(inline-always)
@inline(__always)
@_semantics("array.uninitialized_intrinsic")
public // COMPILER_INTRINSIC
func _allocateUninitializedArray<Element>(_ builtinCount: Builtin.Word)
-> (Array<Element>, Builtin.RawPointer) {
let count = Int(builtinCount)
if count > 0 {
// Doing the actual buffer allocation outside of the array.uninitialized
// semantics function enables stack propagation of the buffer.
let bufferObject = Builtin.allocWithTailElems_1(
_ContiguousArrayStorage<Element>.self, builtinCount, Element.self)
let (array, ptr) = Array<Element>._adoptStorage(bufferObject, count: count)
return (array, ptr._rawValue)
}
// For an empty array no buffer allocation is needed.
let (array, ptr) = Array<Element>._allocateUninitialized(count)
return (array, ptr._rawValue)
}
// Referenced by the compiler to deallocate array literals on the
// error path.
@inlinable
@_semantics("array.dealloc_uninitialized")
public // COMPILER_INTRINSIC
func _deallocateUninitializedArray<Element>(
_ array: __owned Array<Element>
) {
var array = array
array._deallocateUninitialized()
}
#if !INTERNAL_CHECKS_ENABLED
@_alwaysEmitIntoClient
@_semantics("array.finalize_intrinsic")
@_effects(readnone)
public // COMPILER_INTRINSIC
func _finalizeUninitializedArray<Element>(
_ array: __owned Array<Element>
) -> Array<Element> {
var mutableArray = array
mutableArray._endMutation()
return mutableArray
}
#else
// When asserts are enabled, _endCOWMutation writes to _native.isImmutable
// So we cannot have @_effects(readnone)
@_alwaysEmitIntoClient
@_semantics("array.finalize_intrinsic")
public // COMPILER_INTRINSIC
func _finalizeUninitializedArray<Element>(
_ array: __owned Array<Element>
) -> Array<Element> {
var mutableArray = array
mutableArray._endMutation()
return mutableArray
}
#endif
extension Collection {
// Utility method for collections that wish to implement
// CustomStringConvertible and CustomDebugStringConvertible using a bracketed
// list of elements, like an array.
internal func _makeCollectionDescription(
withTypeName type: String? = nil
) -> String {
var result = ""
if let type = type {
result += "\(type)(["
} else {
result += "["
}
var first = true
for item in self {
if first {
first = false
} else {
result += ", "
}
debugPrint(item, terminator: "", to: &result)
}
result += type != nil ? "])" : "]"
return result
}
}
extension _ArrayBufferProtocol {
@inlinable // FIXME @useableFromInline https://bugs.swift.org/browse/SR-7588
@inline(never)
internal mutating func _arrayOutOfPlaceReplace<C: Collection>(
_ bounds: Range<Int>,
with newValues: __owned C,
count insertCount: Int
) where C.Element == Element {
let growth = insertCount - bounds.count
let newCount = self.count + growth
var newBuffer = _forceCreateUniqueMutableBuffer(
newCount: newCount, requiredCapacity: newCount)
_arrayOutOfPlaceUpdate(
&newBuffer, bounds.lowerBound - startIndex, insertCount,
{ rawMemory, count in
var p = rawMemory
var q = newValues.startIndex
for _ in 0..<count {
p.initialize(to: newValues[q])
newValues.formIndex(after: &q)
p += 1
}
_expectEnd(of: newValues, is: q)
}
)
}
}
/// A _debugPrecondition check that `i` has exactly reached the end of
/// `s`. This test is never used to ensure memory safety; that is
/// always guaranteed by measuring `s` once and re-using that value.
@inlinable
internal func _expectEnd<C: Collection>(of s: C, is i: C.Index) {
_debugPrecondition(
i == s.endIndex,
"invalid Collection: count differed in successive traversals")
}
@inlinable
internal func _growArrayCapacity(_ capacity: Int) -> Int {
return capacity * 2
}
@_alwaysEmitIntoClient
internal func _growArrayCapacity(
oldCapacity: Int, minimumCapacity: Int, growForAppend: Bool
) -> Int {
if growForAppend {
if oldCapacity < minimumCapacity {
// When appending to an array, grow exponentially.
return Swift.max(minimumCapacity, _growArrayCapacity(oldCapacity))
}
return oldCapacity
}
// If not for append, just use the specified capacity, ignoring oldCapacity.
// This means that we "shrink" the buffer in case minimumCapacity is less
// than oldCapacity.
return minimumCapacity
}
//===--- generic helpers --------------------------------------------------===//
extension _ArrayBufferProtocol {
/// Create a unique mutable buffer that has enough capacity to hold 'newCount'
/// elements and at least 'requiredCapacity' elements. Set the count of the new
/// buffer to 'newCount'. The content of the buffer is uninitialized.
/// The formula used to compute the new buffers capacity is:
/// max(requiredCapacity, source.capacity) if newCount <= source.capacity
/// max(requiredCapacity, _growArrayCapacity(source.capacity)) otherwise
@inline(never)
@inlinable // @specializable
internal func _forceCreateUniqueMutableBuffer(
newCount: Int, requiredCapacity: Int
) -> _ContiguousArrayBuffer<Element> {
return _forceCreateUniqueMutableBufferImpl(
countForBuffer: newCount, minNewCapacity: newCount,
requiredCapacity: requiredCapacity)
}
/// Create a unique mutable buffer that has enough capacity to hold
/// 'minNewCapacity' elements and set the count of the new buffer to
/// 'countForNewBuffer'. The content of the buffer uninitialized.
/// The formula used to compute the new buffers capacity is:
/// max(minNewCapacity, source.capacity) if minNewCapacity <= source.capacity
/// max(minNewCapacity, _growArrayCapacity(source.capacity)) otherwise
@inline(never)
@inlinable // @specializable
internal func _forceCreateUniqueMutableBuffer(
countForNewBuffer: Int, minNewCapacity: Int
) -> _ContiguousArrayBuffer<Element> {
return _forceCreateUniqueMutableBufferImpl(
countForBuffer: countForNewBuffer, minNewCapacity: minNewCapacity,
requiredCapacity: minNewCapacity)
}
/// Create a unique mutable buffer that has enough capacity to hold
/// 'minNewCapacity' elements and at least 'requiredCapacity' elements and set
/// the count of the new buffer to 'countForBuffer'. The content of the buffer
/// uninitialized.
/// The formula used to compute the new capacity is:
/// max(requiredCapacity, source.capacity) if minNewCapacity <= source.capacity
/// max(requiredCapacity, _growArrayCapacity(source.capacity)) otherwise
@inlinable
internal func _forceCreateUniqueMutableBufferImpl(
countForBuffer: Int, minNewCapacity: Int,
requiredCapacity: Int
) -> _ContiguousArrayBuffer<Element> {
_internalInvariant(countForBuffer >= 0)
_internalInvariant(requiredCapacity >= countForBuffer)
_internalInvariant(minNewCapacity >= countForBuffer)
let minimumCapacity = Swift.max(requiredCapacity,
minNewCapacity > capacity
? _growArrayCapacity(capacity) : capacity)
return _ContiguousArrayBuffer(
_uninitializedCount: countForBuffer, minimumCapacity: minimumCapacity)
}
}
extension _ArrayBufferProtocol {
/// Initialize the elements of dest by copying the first headCount
/// items from source, calling initializeNewElements on the next
/// uninitialized element, and finally by copying the last N items
/// from source into the N remaining uninitialized elements of dest.
///
/// As an optimization, may move elements out of source rather than
/// copying when it isUniquelyReferenced.
@inline(never)
@inlinable // @specializable
internal mutating func _arrayOutOfPlaceUpdate(
_ dest: inout _ContiguousArrayBuffer<Element>,
_ headCount: Int, // Count of initial source elements to copy/move
_ newCount: Int, // Number of new elements to insert
_ initializeNewElements:
((UnsafeMutablePointer<Element>, _ count: Int) -> ()) = { ptr, count in
_internalInvariant(count == 0)
}
) {
_internalInvariant(headCount >= 0)
_internalInvariant(newCount >= 0)
// Count of trailing source elements to copy/move
let sourceCount = self.count
let tailCount = dest.count - headCount - newCount
_internalInvariant(headCount + tailCount <= sourceCount)
let oldCount = sourceCount - headCount - tailCount
let destStart = dest.firstElementAddress
let newStart = destStart + headCount
let newEnd = newStart + newCount
// Check to see if we have storage we can move from
if let backing = requestUniqueMutableBackingBuffer(
minimumCapacity: sourceCount) {
let sourceStart = firstElementAddress
let oldStart = sourceStart + headCount
// Destroy any items that may be lurking in a _SliceBuffer before
// its real first element
let backingStart = backing.firstElementAddress
let sourceOffset = sourceStart - backingStart
backingStart.deinitialize(count: sourceOffset)
// Move the head items
destStart.moveInitialize(from: sourceStart, count: headCount)
// Destroy unused source items
oldStart.deinitialize(count: oldCount)
initializeNewElements(newStart, newCount)
// Move the tail items
newEnd.moveInitialize(from: oldStart + oldCount, count: tailCount)
// Destroy any items that may be lurking in a _SliceBuffer after
// its real last element
let backingEnd = backingStart + backing.count
let sourceEnd = sourceStart + sourceCount
sourceEnd.deinitialize(count: backingEnd - sourceEnd)
backing.count = 0
}
else {
let headStart = startIndex
let headEnd = headStart + headCount
let newStart = _copyContents(
subRange: headStart..<headEnd,
initializing: destStart)
initializeNewElements(newStart, newCount)
let tailStart = headEnd + oldCount
let tailEnd = endIndex
_copyContents(subRange: tailStart..<tailEnd, initializing: newEnd)
}
self = Self(_buffer: dest, shiftedToStartIndex: startIndex)
}
}
extension _ArrayBufferProtocol {
@inline(never)
@usableFromInline
internal mutating func _outlinedMakeUniqueBuffer(bufferCount: Int) {
if _fastPath(
requestUniqueMutableBackingBuffer(minimumCapacity: bufferCount) != nil) {
return
}
var newBuffer = _forceCreateUniqueMutableBuffer(
newCount: bufferCount, requiredCapacity: bufferCount)
_arrayOutOfPlaceUpdate(&newBuffer, bufferCount, 0)
}
/// Append items from `newItems` to a buffer.
@inlinable
internal mutating func _arrayAppendSequence<S: Sequence>(
_ newItems: __owned S
) where S.Element == Element {
// this function is only ever called from append(contentsOf:)
// which should always have exhausted its capacity before calling
_internalInvariant(count == capacity)
var newCount = self.count
// there might not be any elements to append remaining,
// so check for nil element first, then increase capacity,
// then inner-loop to fill that capacity with elements
var stream = newItems.makeIterator()
var nextItem = stream.next()
while nextItem != nil {
// grow capacity, first time around and when filled
var newBuffer = _forceCreateUniqueMutableBuffer(
countForNewBuffer: newCount,
// minNewCapacity handles the exponential growth, just
// need to request 1 more than current count/capacity
minNewCapacity: newCount + 1)
_arrayOutOfPlaceUpdate(&newBuffer, newCount, 0)
let currentCapacity = self.capacity
let base = self.firstElementAddress
// fill while there is another item and spare capacity
while let next = nextItem, newCount < currentCapacity {
(base + newCount).initialize(to: next)
newCount += 1
nextItem = stream.next()
}
self.count = newCount
}
}
}
| apache-2.0 |
tmd2013/iOSDesignPatternSwift | observer-swift/observer-swiftTests/observer_swiftTests.swift | 1 | 995 | //
// observer_swiftTests.swift
// observer-swiftTests
//
// Created by nonoking on 2017/6/5.
// Copyright © 2017年 nonoking. All rights reserved.
//
import XCTest
@testable import observer_swift
class observer_swiftTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| apache-2.0 |
pkl728/ZombieInjection | ZombieInjectionTests/ZombieServiceTests.swift | 1 | 2388 | //
// ZombieServiceTests.swift
// ZombieInjection
//
// Created by Patrick Lind on 7/27/16.
// Copyright © 2016 Patrick Lind. All rights reserved.
//
import XCTest
import Bond
@testable import ZombieInjection
class ZombieServiceTests: XCTestCase {
private var zombieRepository: ZombieRepositoryProtocol!
private var zombieService: ZombieServiceProtocol!
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
self.zombieRepository = ZombieRepositoryMock()
self.zombieService = ZombieService(zombieRepository: self.zombieRepository)
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
self.zombieRepository.deleteAll()
}
func testFetchZombies() {
// Arrange
// Act
self.zombieService.fetchZombies()
// Assert
XCTAssert(self.zombieRepository.count() > 0)
}
func testGetZombies() {
// Arrange
// Act
let zombies = self.zombieService.getAllZombies()
// Assert
XCTAssert(zombies?.count == 3)
}
func testGetZombiesIfNoZombies() {
// Arrange
self.zombieRepository.deleteAll()
// Act
let zombies = self.zombieService.getAllZombies()
// Assert
XCTAssert(zombies?.count == 0)
}
func testUpdateZombie() {
// Arrange
let zombie = self.zombieRepository.get(0)
zombie?.name.value = "Test"
// Act
self.zombieService.update(zombie!)
// Assert
XCTAssert(self.zombieRepository.get(0)?.name.value == "Test")
}
func testUpdateWithNonExistentZombieDoesNothing() {
// Arrange
let badZombie = Zombie(id: -1, name: "Bad", imageUrlAddress: nil)
// Act
self.zombieService.update(badZombie)
// Assert
XCTAssert(self.zombieRepository.count() == 3)
XCTAssert(self.zombieRepository.get(0)?.name.value == "First")
XCTAssert(self.zombieRepository.get(1)?.name.value == "Second")
XCTAssert(self.zombieRepository.get(2)?.name.value == "Third")
}
}
| mit |
kaishin/ImageScout | Sources/ImageScout/SessionDelegate.swift | 1 | 539 | import Foundation
class SessionDelegate: NSObject, URLSessionDataDelegate {
weak var scout: ImageScout?
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
guard let scout = scout else { return }
scout.didReceive(data: data, task: dataTask)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
guard let scout = scout else { return }
scout.didComplete(with: error as NSError?, task: task as! URLSessionDataTask)
}
}
| mit |
moltin/ios-sdk | Sources/SDK/Requests/MoltinRequest.swift | 1 | 11760 | //
// MoltinRequest.swift
// moltin
//
// Created by Craig Tweedy on 21/02/2018.
//
import Foundation
enum HTTPMethod: String, CustomStringConvertible {
var description: String {
return self.rawValue
}
case GET
case POST
case PUT
case DELETE
}
/// Boxes up results into success or failure cases
/// This enum will either return success, with the corresponding value with the correct type, or return failure, with the corresponding error
public enum Result<T> {
/// Holds the success result
case success(result: T)
/// Holds the failure error
case failure(error: Error)
}
/// Base class which various endpoints extend from.
/// This class is responsible for orchestrating a request, by constructing queries, authenticating calls, and parsing data.
public class MoltinRequest {
internal var config: MoltinConfig
internal var http: MoltinHTTP
internal var parser: MoltinParser
internal var query: MoltinQuery
internal var auth: MoltinAuth
internal var headers: [String: String] = [:]
// MARK: - Init
/**
Initialise a new `MoltinRequest` with some standard configuration
- Author:
Craig Tweedy
- parameters:
- withConfiguration: A `MoltinConfig` object
*/
public init(withConfiguration configuration: MoltinConfig) {
self.config = configuration
self.http = MoltinHTTP(withSession: URLSession.shared)
self.parser = MoltinParser(withDecoder: JSONDecoder.dateFormattingDecoder())
self.query = MoltinQuery()
self.auth = MoltinAuth(withConfiguration: self.config)
}
// MARK: - Default Calls
/**
Return all instances of type `T`, which must be `Codable`.
- Author:
Craig Tweedy
- parameters:
- withPath: The resource path to call
- completionHandler: The handler to be called on success or failure
- returns:
A instance of `MoltinRequest` which encapsulates the request.
*/
@discardableResult func list<T>(withPath path: String, completionHandler: @escaping CollectionRequestHandler<T>) -> Self {
let urlRequest: URLRequest
do {
urlRequest = try self.http.buildURLRequest(
withConfiguration: self.config,
withPath: path,
withQueryParameters: self.query.toURLQueryItems()
)
} catch {
completionHandler(.failure(error: error))
return self
}
self.send(withURLRequest: urlRequest) { (data, response, error) in
if error != nil {
completionHandler(.failure(error: MoltinError.responseError(underlyingError: error)))
return
}
self.parser.collectionHandler(withData: data, withResponse: response, completionHandler: completionHandler)
}
return self
}
/**
Return a single instance of type `T`, which must be `Codable`.
- Author:
Craig Tweedy
- parameters:
- withPath: The resource path to call
- completionHandler: The handler to be called on success or failure
- returns:
A instance of `MoltinRequest` which encapsulates the request.
*/
@discardableResult func get<T: Codable>(withPath path: String, completionHandler: @escaping ObjectRequestHandler<T>) -> Self {
let urlRequest: URLRequest
do {
urlRequest = try self.http.buildURLRequest(
withConfiguration: self.config,
withPath: path,
withQueryParameters: self.query.toURLQueryItems()
)
} catch {
completionHandler(.failure(error: error))
return self
}
self.send(withURLRequest: urlRequest) { (data, response, error) in
if error != nil {
completionHandler(.failure(error: MoltinError.responseError(underlyingError: error)))
return
}
self.parser.singleObjectHandler(withData: data, withResponse: response, completionHandler: completionHandler)
}
return self
}
/**
Construct a creation request, and return an instance of type `T`, which must be `Codable`
- Author:
Craig Tweedy
- parameters:
- withPath: The resource path to call
- withData: The data with which to create the resource
- completionHandler: The handler to be called on success or failure
- returns:
A instance of `MoltinRequest` which encapsulates the request.
*/
@discardableResult func post<T: Codable>(withPath path: String, withData data: [String: Any], completionHandler: @escaping ObjectRequestHandler<T>) -> Self {
let urlRequest: URLRequest
do {
urlRequest = try self.http.buildURLRequest(
withConfiguration: self.config,
withPath: path,
withQueryParameters: self.query.toURLQueryItems(),
withMethod: HTTPMethod.POST,
withData: data
)
} catch {
completionHandler(.failure(error: error))
return self
}
self.send(withURLRequest: urlRequest) { (data, response, error) in
if error != nil {
completionHandler(.failure(error: MoltinError.responseError(underlyingError: error)))
return
}
self.parser.singleObjectHandler(withData: data, withResponse: response, completionHandler: completionHandler)
}
return self
}
/**
Construct an update request, and return an instance of type `T`, which must be `Codable`
- Author:
Craig Tweedy
- parameters:
- withPath: The resource path to call
- withData: The data with which to update the resource
- completionHandler: The handler to be called on success or failure
- returns:
A instance of `MoltinRequest` which encapsulates the request.
*/
@discardableResult func put<T: Codable>(withPath path: String, withData data: [String: Any], completionHandler: @escaping ObjectRequestHandler<T>) -> Self {
let urlRequest: URLRequest
do {
urlRequest = try self.http.buildURLRequest(
withConfiguration: self.config,
withPath: path,
withQueryParameters: self.query.toURLQueryItems(),
withMethod: HTTPMethod.PUT,
withData: data
)
} catch {
completionHandler(.failure(error: error))
return self
}
self.send(withURLRequest: urlRequest) { (data, response, error) in
if error != nil {
completionHandler(.failure(error: MoltinError.responseError(underlyingError: error)))
return
}
self.parser.singleObjectHandler(withData: data, withResponse: response, completionHandler: completionHandler)
}
return self
}
/**
Construct a deletion request, and return an instance of type `T`, which must be `Codable`
- Author:
Craig Tweedy
- parameters:
- withPath: The resource path to call
- completionHandler: The handler to be called on success or failure
- returns:
A instance of `MoltinRequest` which encapsulates the request.
*/
@discardableResult func delete<T: Codable>(withPath path: String, completionHandler: @escaping ObjectRequestHandler<T>) -> Self {
let urlRequest: URLRequest
do {
urlRequest = try self.http.buildURLRequest(
withConfiguration: self.config,
withPath: path,
withQueryParameters: self.query.toURLQueryItems(),
withMethod: HTTPMethod.DELETE
)
} catch {
completionHandler(.failure(error: error))
return self
}
self.send(withURLRequest: urlRequest) { (data, response, error) in
if error != nil {
completionHandler(.failure(error: MoltinError.responseError(underlyingError: error)))
return
}
self.parser.singleObjectHandler(withData: data, withResponse: response, completionHandler: completionHandler)
}
return self
}
private func send(withURLRequest urlRequest: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) {
self.auth.authenticate { [weak self] (result) in
switch result {
case .success(let result):
let request = self?.http.configureRequest(urlRequest,
withToken: result.token,
withConfig: self?.config,
withAdditionalHeaders: self?.headers)
self?.http.executeRequest(request) { (data, response, error) in
completionHandler(data, response, error)
}
case .failure(let error):
completionHandler(nil, nil, error)
}
}
}
// MARK: - Modifiers
/**
Add some includes to the query
- Author:
Craig Tweedy
- parameters:
- includes: An array of `MoltinInclude` to append to the request
- returns:
A instance of `MoltinRequest` which encapsulates the request.
*/
public func include(_ includes: [MoltinInclude]) -> Self {
self.query.withIncludes = includes
return self
}
/**
Add a limit parameter to the query
- Author:
Craig Tweedy
- parameters:
- limit: The amount of items to return
- returns:
A instance of `MoltinRequest` which encapsulates the request.
*/
public func limit(_ limit: Int) -> Self {
self.query.withLimit = "\(limit)"
return self
}
/**
Add a sort parameter to the query
- Author:
Craig Tweedy
- parameters:
- sort: The sort order to use
- returns:
A instance of `MoltinRequest` which encapsulates the request.
*/
public func sort(_ sort: String) -> Self {
self.query.withSorting = sort
return self
}
/**
Add an offset parameter to the query
- Author:
Craig Tweedy
- parameters:
- offset: The amount of items to offset by
- returns:
A instance of `MoltinRequest` which encapsulates the request.
*/
public func offset(_ offset: Int) -> Self {
self.query.withOffset = "\(offset)"
return self
}
/**
Add an filter parameter to the query
- Author:
Craig Tweedy
- parameters:
- operator: The `MoltinFilterOperator` to use
- key: The key for the filter
- value: The value for the filter
- returns:
A instance of `MoltinRequest` which encapsulates the request.
*/
public func filter(operator op: MoltinFilterOperator, key: String, value: String) -> Self {
self.query.withFilter.append((op, key, value))
return self
}
/**
Add a header to the request
- Author:
Craig Tweedy
- parameters:
- key: The header key
- withValue: The header value
- returns:
An instance of `MoltinRequest` which encapsulates the request.
*/
public func addHeader(_ key: String, withValue value: String) -> Self {
self.headers[key] = value
return self
}
}
| mit |
bugfender/BugfenderSDK-iOS-swift-sample | BugfenderSDK-iOS-swift-sample/AppDelegate.swift | 1 | 2896 | //
// AppDelegate.swift
// Bugfender sample
//
// Created by gimix on 07/05/15.
// Copyright (c) 2015 Bugfender. All rights reserved.
//
import UIKit
import BugfenderSDK
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
// Override point for customization after application launch.
let yourBugFenderAppKey = "4k4QFtHpvkQGDdCfF4fT6BAfv4PQpgGs" //TODO: insert your key here!
Bugfender.activateLogger(yourBugFenderAppKey)
Bugfender.enableUIEventLogging()
let string = Bugfender.deviceIdentifier();
UserDefaults.standard.set(string, forKey: "device_id")
BFLog("#######################################")
BFLog("### BugfenderSDK TEST APP ###")
BFLog("### by Bugfender ###")
BFLog("#######################################")
BFLog("")
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
BFLog("App is going to background!")
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
BFLog("App is coming from background to active!")
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| apache-2.0 |
SwiftMN/SwiftMN | Sources/App/Controllers/TalkController.swift | 1 | 3575 | //
// TalkController.swift
// App
//
// Created by Steven Vlaminck on 10/24/17.
//
import Vapor
import HTTP
/// Here we have a controller that helps facilitate
/// RESTful interactions with our Talks table
final class TalkController: ResourceRepresentable {
/// When users call 'GET' on '/talks'
/// it should return an index of all available talks
func index(_ req: Request) throws -> ResponseRepresentable {
return try Talk.all().makeJSON()
}
/// When consumers call 'POST' on '/talks' with valid JSON
/// construct and save the talk
func store(_ req: Request) throws -> ResponseRepresentable {
let talk = try req.talk()
try talk.save()
return talk
}
/// When the consumer calls 'GET' on a specific resource, ie:
/// '/talks/13rd88' we should show that specific talk
func show(_ req: Request, talk: Talk) throws -> ResponseRepresentable {
return talk
}
/// When the consumer calls 'DELETE' on a specific resource, ie:
/// 'talks/l2jd9' we should remove that resource from the database
func delete(_ req: Request, talk: Talk) throws -> ResponseRepresentable {
try talk.delete()
return Response(status: .ok)
}
/// When the consumer calls 'DELETE' on the entire table, ie:
/// '/talks' we should remove the entire table
func clear(_ req: Request) throws -> ResponseRepresentable {
try Talk.makeQuery().delete()
return Response(status: .ok)
}
/// When the user calls 'PATCH' on a specific resource, we should
/// update that resource to the new values.
func update(_ req: Request, talk: Talk) throws -> ResponseRepresentable {
// See `extension Talk: Updateable`
try talk.update(for: req)
// Save an return the updated talk.
try talk.save()
return talk
}
/// When a user calls 'PUT' on a specific resource, we should replace any
/// values that do not exist in the request with null.
/// This is equivalent to creating a new Talk with the same ID.
func replace(_ req: Request, talk: Talk) throws -> ResponseRepresentable {
// First attempt to create a new Talk from the supplied JSON.
// If any required fields are missing, this request will be denied.
let new = try req.talk()
// Update the talk with all of the properties from
// the new talk
talk.content = new.content
try talk.save()
// Return the updated talk
return talk
}
/// When making a controller, it is pretty flexible in that it
/// only expects closures, this is useful for advanced scenarios, but
/// most of the time, it should look almost identical to this
/// implementation
func makeResource() -> Resource<Talk> {
return Resource(
index: index,
store: store,
show: show,
update: update,
replace: replace,
destroy: delete,
clear: clear
)
}
}
extension Request {
/// Create a talk from the JSON body
/// return BadRequest error if invalid
/// or no JSON
func talk() throws -> Talk {
guard let json = json else { throw Abort.badRequest }
return try Talk(json: json)
}
}
/// Since TalkController doesn't require anything to
/// be initialized we can conform it to EmptyInitializable.
///
/// This will allow it to be passed by type.
extension TalkController: EmptyInitializable { }
| mit |
jngd/advanced-ios10-training | T2E02/T2E02/AppDelegate.swift | 1 | 2065 | //
// AppDelegate.swift
// T2E02
//
// Created by jngd on 23/01/2017.
// Copyright © 2017 jngd. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| apache-2.0 |
crepashok/The-Complete-Watch-OS2-Developer-Course | Section-13/Producitivity Timer/Producitivity TimerUITests/Producitivity_TimerUITests.swift | 1 | 1282 | //
// Producitivity_TimerUITests.swift
// Producitivity TimerUITests
//
// Created by Pavlo Cretsu on 4/20/16.
// Copyright © 2016 Pasha Cretsu. All rights reserved.
//
import XCTest
class Producitivity_TimerUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| gpl-3.0 |
crashoverride777/Swift2-iAds-AdMob-CustomAds-Helper | SwiftyAd/SwiftyAdConsentManager.swift | 2 | 10561 | // The MIT License (MIT)
//
// Copyright (c) 2015-2018 Dominik Ringler
//
// 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 PersonalizedAdConsent
/// LocalizedString
/// TODO
private extension String {
static let consentTitle = "Permission to use data"
static let consentMessage = "We care about your privacy and data security. We keep this app free by showing ads. You can change your choice anytime in the app settings. Our partners will collect data and use a unique identifier on your device to show you ads."
static let ok = "OK"
static let weShowAdsFrom = "We show ads from: "
static let weUseAdProviders = "We use the following ad technology providers: "
static let adFree = "Buy ad free app"
static let allowPersonalized = "Allow personalized ads"
static let allowNonPersonalized = "Allow non-personalized ads"
}
/**
SwiftyAdConsentManager
A class to manage consent request for Google AdMob (e.g GDPR).
*/
final class SwiftyAdConsentManager {
// MARK: - Types
struct Configuration: Codable {
let privacyPolicyURL: String
let shouldOfferAdFree: Bool
let mediationNetworks: [String]
let isTaggedForUnderAgeOfConsent: Bool
let isCustomForm: Bool
var mediationNetworksString: String {
return mediationNetworks.map({ $0 }).joined(separator: ", ")
}
}
enum ConsentStatus {
case personalized
case nonPersonalized
case adFree
case unknown
}
// MARK: - Properties
/// The current status
var status: ConsentStatus {
switch consentInformation.consentStatus {
case .personalized:
return .personalized
case .nonPersonalized:
return .nonPersonalized
case .unknown:
return .unknown
@unknown default:
return .unknown
}
}
/// Check if user is in EEA (EU economic area)
var isInEEA: Bool {
return consentInformation.isRequestLocationInEEAOrUnknown
}
var isRequiredToAskForConsent: Bool {
guard isInEEA else { return false }
guard !isTaggedForUnderAgeOfConsent else { return false } // must be non personalized only, cannot legally consent
return true
}
/// Check if we can show ads
var hasConsent: Bool {
guard isInEEA, !isTaggedForUnderAgeOfConsent else { return true }
return status != .unknown
}
/// Check if under age is turned on
var isTaggedForUnderAgeOfConsent: Bool {
return configuration.isTaggedForUnderAgeOfConsent
}
/// Private
private let ids: [String]
private let configuration: Configuration
private let consentInformation: PACConsentInformation = .sharedInstance
// MARK: - Init
init(ids: [String], configuration: Configuration) {
self.ids = ids
self.configuration = configuration
consentInformation.isTaggedForUnderAgeOfConsent = configuration.isTaggedForUnderAgeOfConsent
}
// MARK: - Ask For Consent
func ask(from viewController: UIViewController, skipIfAlreadyAuthorized: Bool = false, handler: @escaping (ConsentStatus) -> Void) {
consentInformation.requestConsentInfoUpdate(forPublisherIdentifiers: ids) { (_ error) in
if let error = error {
print("SwiftyAdConsentManager error requesting consent info update: \(error)")
handler(self.status)
return
}
// If we already have permission dont ask again
if skipIfAlreadyAuthorized {
switch self.consentInformation.consentStatus {
case .personalized:
print("SwiftyAdConsentManager already has consent permission, no need to ask again")
handler(self.status)
return
case .nonPersonalized:
print("SwiftyAdConsentManager already has consent permission, no need to ask again")
handler(self.status)
return
case .unknown:
break
@unknown default:
break
}
}
// We only need to ask for consent if we are in the EEA
guard self.consentInformation.isRequestLocationInEEAOrUnknown else {
print("SwiftyAdConsentManager not in EU, no need to handle consent logic")
self.consentInformation.consentStatus = .personalized
handler(.personalized)
return
}
// We also do not need to ask for consent if under age is turned on because than all add requests have to be non-personalized
guard !self.isTaggedForUnderAgeOfConsent else {
self.consentInformation.consentStatus = .nonPersonalized
print("SwiftyAdConsentManager under age, no need to handle consent logic as it must be non-personalized")
handler(.nonPersonalized)
return
}
// Show consent form
if self.configuration.isCustomForm {
self.showCustomConsentForm(from: viewController, handler: handler)
} else {
self.showDefaultConsentForm(from: viewController, handler: handler)
}
}
}
}
// MARK: - Default Consent Form
private extension SwiftyAdConsentManager {
func showDefaultConsentForm(from viewController: UIViewController, handler: @escaping (ConsentStatus) -> Void) {
// Make sure we have a valid privacy policy url
guard let url = URL(string: configuration.privacyPolicyURL) else {
print("SwiftyAdConsentManager invalid privacy policy URL")
handler(status)
return
}
// Make sure we have a valid consent form
guard let form = PACConsentForm(applicationPrivacyPolicyURL: url) else {
print("SwiftyAdConsentManager PACConsentForm nil")
handler(status)
return
}
// Set form properties
form.shouldOfferPersonalizedAds = true
form.shouldOfferNonPersonalizedAds = true
form.shouldOfferAdFree = configuration.shouldOfferAdFree
// Load form
form.load { (_ error) in
if let error = error {
print("SwiftyAdConsentManager error loading consent form: \(error)")
handler(self.status)
return
}
// Loaded successfully, present it
form.present(from: viewController) { (error, prefersAdFree) in
if let error = error {
print("SwiftyAdConsentManager error presenting consent form: \(error)")
handler(self.status)
return
}
// Check if user prefers to use a paid version of the app (shouldOfferAdFree button)
guard !prefersAdFree else {
self.consentInformation.consentStatus = .unknown
handler(.adFree)
return
}
// Consent info update succeeded. The shared PACConsentInformation instance has been updated
handler(self.status)
}
}
}
}
// MARK: - Custom Consent Form
private extension SwiftyAdConsentManager {
func showCustomConsentForm(from viewController: UIViewController, handler: @escaping (ConsentStatus) -> Void) {
// Create alert message with all ad providers
var message = .consentMessage + "\n\n" + .weShowAdsFrom + "Google AdMob, " + configuration.mediationNetworksString
if let adProviders = consentInformation.adProviders, !adProviders.isEmpty {
message += "\n\n" + .weUseAdProviders + "\((adProviders.map({ $0.name })).joined(separator: ", "))"
}
message += "\n\n\(configuration.privacyPolicyURL)"
// Create alert controller
let alertController = UIAlertController(title: .consentTitle, message: message, preferredStyle: .alert)
// Personalized action
let personalizedAction = UIAlertAction(title: .allowPersonalized, style: .default) { action in
self.consentInformation.consentStatus = .personalized
handler(.personalized)
}
alertController.addAction(personalizedAction)
// Non-Personalized action
let nonPersonalizedAction = UIAlertAction(title: .allowNonPersonalized, style: .default) { action in
self.consentInformation.consentStatus = .nonPersonalized
handler(.nonPersonalized)
}
alertController.addAction(nonPersonalizedAction)
// Ad free action
if configuration.shouldOfferAdFree {
let adFreeAction = UIAlertAction(title: .adFree, style: .default) { action in
self.consentInformation.consentStatus = .unknown
handler(.adFree)
}
alertController.addAction(adFreeAction)
}
// Present alert
DispatchQueue.main.async {
viewController.present(alertController, animated: true)
}
}
}
| mit |
coolshubh4/iOS-Demos | TextFieldChallenge/TextFieldChallenge/ZipCodeDelegate.swift | 1 | 726 | //
// ZipCodeDelegate.swift
// TextFieldChallenge
//
// Created by Shubham Tripathi on 13/07/15.
// Copyright (c) 2015 Shubham Tripathi. All rights reserved.
//
import Foundation
import UIKit
class ZipCodeDelegate: NSObject, UITextFieldDelegate {
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
var newText = textField.text as NSString
newText = newText.stringByReplacingCharactersInRange(range, withString: string)
return newText.length <= 5
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true;
}
} | mit |
Mindera/Alicerce | Tests/AlicerceTests/Extensions/UIKit/NSDirectionalEdgeInsetsTestCase.swift | 1 | 411 | import XCTest
import UIKit
@testable import Alicerce
@available(iOS 11.0, *)
final class NSDirectionalEdgeInsetsTestCase: XCTestCase {
func test_nonDirectional_ShouldReturnInstanceWithCorrectValues() {
XCTAssertEqual(
NSDirectionalEdgeInsets(top: 1, leading: 2, bottom: 3, trailing: 4).nonDirectional,
UIEdgeInsets(top: 1, left: 2, bottom: 3, right: 4)
)
}
}
| mit |
waterskier2007/NVActivityIndicatorView | NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallScaleRipple.swift | 1 | 3210 | //
// NVActivityIndicatorAnimationBallScaleRipple.swift
// NVActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// 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 NVActivityIndicatorAnimationBallScaleRipple: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let duration: CFTimeInterval = 1
let timingFunction = CAMediaTimingFunction(controlPoints: 0.21, 0.53, 0.56, 0.8)
// Scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.7]
scaleAnimation.timingFunction = timingFunction
scaleAnimation.values = [0.1, 1]
scaleAnimation.duration = duration
// Opacity animation
let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
opacityAnimation.keyTimes = [0, 0.7, 1]
opacityAnimation.timingFunctions = [timingFunction, timingFunction]
opacityAnimation.values = [1, 0.7, 0]
opacityAnimation.duration = duration
// Animation
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, opacityAnimation]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw circle
<<<<<<< HEAD
let circle = NVActivityIndicatorShape.Ring.createLayerWith(size: size, color: color)
let frame = CGRect(x: (layer.bounds.width - size.width) / 2,
y: (layer.bounds.height - size.height) / 2,
width: size.width,
height: size.height)
=======
let circle = NVActivityIndicatorShape.ring.layerWith(size: size, color: color)
let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2,
y: (layer.bounds.size.height - size.height) / 2,
width: size.width,
height: size.height)
>>>>>>> ninjaprox/master
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
| mit |
goRestart/restart-backend-app | Sources/API/Application/Error/Generic/MissingParameters.swift | 1 | 155 | final class MissingParameters: ResponseError {
static let error = make(with: .badRequest, code: 5, message: "Invalid request, missing parameter(s)")
}
| gpl-3.0 |
carabina/AmazonS3RequestManager | AmazonS3RequestManager/AmazonS3RequestManager.swift | 1 | 15851 | //
// AmazonS3RequestManager.swift
// AmazonS3RequestManager
//
// Based on `AFAmazonS3Manager` by `Matt Thompson`
//
// Created by Anthony Miller. 2015.
//
// 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 MobileCoreServices
import Alamofire
/**
* MARK: Information
*/
/**
MARK: Error Domain
The Error Domain for `ZRAPI`
*/
private let AmazonS3RequestManagerErrorDomain = "com.alamofire.AmazonS3RequestManager"
/**
MARK: Error Codes
The error codes for the `AmazonS3RequestManagerErrorDomain`
- AccessKeyMissing: The `accessKey` for the request manager is `nil`. The `accessKey` must be set in order to make requests with `AmazonS3RequestManager`.
- SecretMissing: The secret for the request manager is `nil`. The secret must be set in order to make requests with `AmazonS3RequestManager`.
*/
public enum AmazonS3RequestManagerErrorCodes: Int {
case AccessKeyMissing = 1,
SecretMissing
}
/**
MARK: Amazon S3 Regions
The possible Amazon Web Service regions for the client.
- USStandard: N. Virginia or Pacific Northwest
- USWest1: Oregon
- USWest2: N. California
- EUWest1: Ireland
- EUCentral1: Frankfurt
- APSoutheast1: Singapore
- APSoutheast2: Sydney
- APNortheast1: Toyko
- SAEast1: Sao Paulo
*/
public enum AmazonS3Region: String {
case USStandard = "s3.amazonaws.com",
USWest1 = "s3-us-west-1.amazonaws.com",
USWest2 = "s3-us-west-2.amazonaws.com",
EUWest1 = "s3-eu-west-1.amazonaws.com",
EUCentral1 = "s3-eu-central-1.amazonaws.com",
APSoutheast1 = "s3-ap-southeast-1.amazonaws.com",
APSoutheast2 = "s3-ap-southeast-2.amazonaws.com",
APNortheast1 = "s3-ap-northeast-1.amazonaws.com",
SAEast1 = "s3-sa-east-1.amazonaws.com"
}
/**
MARK: AmazonS3RequestManager
`AmazonS3RequestManager` is a subclass of `Alamofire.Manager` that encodes requests to the Amazon S3 service.
*/
public class AmazonS3RequestManager {
/**
MARK: Instance Properties
*/
/**
The Amazon S3 Bucket for the client
*/
public var bucket: String?
/**
The Amazon S3 region for the client. `AmazonS3Region.USStandard` by default.
:note: Must not be `nil`.
:see: `AmazonS3Region` for defined regions.
*/
public var region: AmazonS3Region = .USStandard
/**
The Amazon S3 Access Key ID used to generate authorization headers and pre-signed queries
:dicussion: This can be found on the AWS control panel: http://aws-portal.amazon.com/gp/aws/developer/account/index.html?action=access-key
*/
public var accessKey: String?
/**
The Amazon S3 Secret used to generate authorization headers and pre-signed queries
:dicussion: This can be found on the AWS control panel: http://aws-portal.amazon.com/gp/aws/developer/account/index.html?action=access-key
*/
public var secret: String?
/**
The AWS STS session token. `nil` by default.
*/
public var sessionToken: String?
/**
Whether to connect over HTTPS. `true` by default.
*/
public var useSSL: Bool = true
/**
The `Alamofire.Manager` instance to use for network requests.
:note: This defaults to the shared instance of `Manager` used by top-level Alamofire requests.
*/
public var requestManager: Alamofire.Manager = Alamofire.Manager.sharedInstance
/**
A readonly endpoint URL created for the specified bucket, region, and SSL use preference. `AmazonS3RequestManager` uses this as the baseURL for all requests.
*/
public var endpointURL: NSURL {
var URLString = ""
let scheme = self.useSSL ? "https" : "http"
if bucket != nil {
URLString = "\(scheme)://\(region.rawValue)/\(bucket!)"
} else {
URLString = "\(scheme)://\(region.rawValue)"
}
return NSURL(string: URLString)!
}
/**
MARK: Initialization
*/
/**
Initalizes an `AmazonS3RequestManager` with the given Amazon S3 credentials.
:param: bucket The Amazon S3 bucket for the client
:param: region The Amazon S3 region for the client
:param: accessKey The Amazon S3 access key ID for the client
:param: secret The Amazon S3 secret for the client
:returns: An `AmazonS3RequestManager` with the given Amazon S3 credentials and a default configuration.
*/
required public init(bucket: String?, region: AmazonS3Region, accessKey: String?, secret: String?) {
self.bucket = bucket
self.region = region
self.accessKey = accessKey
self.secret = secret
}
/**
MARK: - GET Object Requests
*/
/**
Gets and object from the Amazon S3 service and returns it as the response object without saving to file.
:note: This method performs a standard GET request and does not allow use of progress blocks.
:param: path The object path
:returns: A GET request for the object
*/
public func getObject(path: String) -> Request {
return requestManager.request(amazonURLRequest(.GET, path: path))
}
/**
Gets an object from the Amazon S3 service and saves it to file.
:note: The user for the manager's Amazon S3 credentials must have read access to the object
:dicussion: This method performs a download request that allows for a progress block to be implemented. For more information on using progress blocks, see `Alamofire`.
:param: path The object path
:param: destinationURL The `NSURL` to save the object to
:returns: A download request for the object
*/
public func downloadObject(path: String, saveToURL destinationURL: NSURL) -> Request {
return requestManager.download(amazonURLRequest(.GET, path: path), destination: { (_, _) -> (NSURL) in
return destinationURL
})
}
/**
MARK: PUT Object Requests
*/
/**
Uploads an object to the Amazon S3 service with a given local file URL.
:note: The user for the manager's Amazon S3 credentials must have read access to the bucket
:param: fileURL The local `NSURL` of the file to upload
:param: destinationPath The desired destination path, including the file name and extension, in the Amazon S3 bucket
:param: acl The optional access control list to set the acl headers for the request. For more information see `AmazonS3ACL`.
:returns: An upload request for the object
*/
public func putObject(fileURL: NSURL, destinationPath: String, acl: AmazonS3ACL? = nil) -> Request {
let putRequest = amazonURLRequest(.PUT, path: destinationPath, acl: acl)
return requestManager.upload(putRequest, file: fileURL)
}
/**
Uploads an object to the Amazon S3 service with the given data.
:note: The user for the manager's Amazon S3 credentials must have read access to the bucket
:param: data The `NSData` for the object to upload
:param: destinationPath The desired destination path, including the file name and extension, in the Amazon S3 bucket
:param: acl The optional access control list to set the acl headers for the request. For more information see `AmazonS3ACL`.
:returns: An upload request for the object
*/
public func putObject(data: NSData, destinationPath: String, acl: AmazonS3ACL? = nil) -> Request {
let putRequest = amazonURLRequest(.PUT, path: destinationPath, acl: acl)
return requestManager.upload(putRequest, data: data)
}
/**
MARK: DELETE Object Request
*/
/**
Deletes an object from the Amazon S3 service.
:warning: Once an object has been deleted, there is no way to restore or undelete it.
:param: path The object path
:returns: The delete request
*/
public func deleteObject(path: String) -> Request {
let deleteRequest = amazonURLRequest(.DELETE, path: path)
return requestManager.request(deleteRequest)
}
/**
MARK: ACL Requests
*/
/**
Gets the access control list (ACL) for the current `bucket`
:note: To use this operation, you must have the `AmazonS3ACLPermission.ReadACL` for the bucket.
:see: For more information on the ACL response headers for this request, see "http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETacl.html"
:returns: A GET request for the bucket's ACL
*/
public func getBucketACL() -> Request {
return requestManager.request(amazonURLRequest(.GET, path: "", subresource: "acl", acl: nil))
}
/**
Sets the access control list (ACL) for the current `bucket`
:note: To use this operation, you must have the `AmazonS3ACLPermission.WriteACL` for the bucket.
:see: For more information on the ACL response headers for this request, see "http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTacl.html"
:returns: A PUT request to set the bucket's ACL
*/
public func setBucketACL(acl: AmazonS3ACL) -> Request {
return requestManager.request(amazonURLRequest(.PUT, path: "", subresource: "acl", acl: acl))
}
/**
Gets the access control list (ACL) for the object at the given path.
:note: To use this operation, you must have the `AmazonS3ACLPermission.ReadACL` for the object.
:see: For more information on the ACL response headers for this request, see "http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGETacl.html"
:param: path The object path
:returns: A GET request for the object's ACL
*/
public func getACL(forObjectAtPath path:String) -> Request {
return requestManager.request(amazonURLRequest(.GET, path: path, subresource: "acl"))
}
/**
Sets the access control list (ACL) for the object at the given path.
:note: To use this operation, you must have the `AmazonS3ACLPermission.WriteACL` for the object.
:see: For more information on the ACL response headers for this request, see "http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUTacl.html"
:returns: A PUT request to set the objects's ACL
*/
public func setACL(forObjectAtPath path: String, acl: AmazonS3ACL) -> Request {
return requestManager.request(amazonURLRequest(.PUT, path: path, subresource: "acl", acl: acl))
}
/**
MARK: Amazon S3 Request Serialization
:discussion: These methods serialize requests for use with the Amazon S3 service. The `NSURLRequest`s returned from these methods may be used with `Alamofire`, `NSURLSession` or any other network request manager.
*/
/**
This method serializes a request for the Amazon S3 service with the given method and path.
:param: method The HTTP method for the request. For more information see `Alamofire.Method`.
:param: path The desired path, including the file name and extension, in the Amazon S3 Bucket.
:param: acl The optional access control list to set the acl headers for the request. For more information see `AmazonS3ACL`.
:returns: An `NSURLRequest`, serialized for use with the Amazon S3 service.
*/
public func amazonURLRequest(method: Alamofire.Method, path: String, subresource: String? = nil, acl: AmazonS3ACL? = nil) -> NSURLRequest {
var url = endpointURL.URLByAppendingPathComponent(path).URLByAppendingS3Subresource(subresource)
var mutableURLRequest = NSMutableURLRequest(URL: url)
mutableURLRequest.HTTPMethod = method.rawValue
setContentType(forRequest: &mutableURLRequest)
acl?.setACLHeaders(forRequest: &mutableURLRequest)
let error = setAuthorizationHeaders(forRequest: &mutableURLRequest)
return mutableURLRequest
}
private func setContentType(inout forRequest request: NSMutableURLRequest) {
var contentTypeString = MIMEType(request) ?? "application/octet-stream"
request.setValue(contentTypeString, forHTTPHeaderField: "Content-Type")
}
private func MIMEType(request: NSURLRequest) -> String? {
if let fileExtension = request.URL?.pathExtension {
if !fileExtension.isEmpty {
let UTIRef = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, nil)
let UTI = UTIRef.takeUnretainedValue()
UTIRef.release()
if let MIMETypeRef = UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType) {
let MIMEType = MIMETypeRef.takeUnretainedValue()
MIMETypeRef.release()
return MIMEType as String
}
}
}
return nil
}
private func setAuthorizationHeaders(inout forRequest request: NSMutableURLRequest) -> NSError? {
request.cachePolicy = .ReloadIgnoringLocalCacheData
let error = validateCredentials()
if error == nil {
if sessionToken != nil {
request.setValue(sessionToken!, forHTTPHeaderField: "x-amz-security-token")
}
let timestamp = currentTimeStamp()
let signature = AmazonS3SignatureHelpers.AWSSignatureForRequest(request,
timeStamp: timestamp,
secret: secret)
request.setValue(timestamp ?? "", forHTTPHeaderField: "Date")
request.setValue("AWS \(accessKey!):\(signature)", forHTTPHeaderField: "Authorization")
}
return error
}
private func currentTimeStamp() -> String {
return requestDateFormatter.stringFromDate(NSDate())
}
private lazy var requestDateFormatter: NSDateFormatter = {
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone(name: "GMT")
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
return dateFormatter
}()
/**
MARK: Validation
*/
private func validateCredentials() -> NSError? {
if accessKey == nil || accessKey!.isEmpty {
return accessKeyMissingError
}
if secret == nil || secret!.isEmpty {
return secretMissingError
}
return nil
}
/**
MARK: Error Handling
*/
private lazy var accessKeyMissingError: NSError = NSError(
domain: AmazonS3RequestManagerErrorDomain,
code: AmazonS3RequestManagerErrorCodes.AccessKeyMissing.rawValue,
userInfo: [NSLocalizedDescriptionKey: "Access Key Missing",
NSLocalizedFailureReasonErrorKey: "The 'accessKey' must be set in order to make requests with 'AmazonS3RequestManager'."]
)
private lazy var secretMissingError: NSError = NSError(
domain: AmazonS3RequestManagerErrorDomain,
code: AmazonS3RequestManagerErrorCodes.SecretMissing.rawValue,
userInfo: [NSLocalizedDescriptionKey: "Secret Missing",
NSLocalizedFailureReasonErrorKey: "The 'secret' must be set in order to make requests with 'AmazonS3RequestManager'."]
)
}
private extension NSURL {
private func URLByAppendingS3Subresource(subresource: String?) -> NSURL {
if subresource != nil && !subresource!.isEmpty {
let URLString = self.absoluteString!.stringByAppendingString("?\(subresource!)")
return NSURL(string: URLString)!
}
return self
}
} | mit |
JackLeeMing/PocketSVG | PocketSVG iOS Example/PocketSVG iOS ExampleTests/PocketSVG_iOS_ExampleTests.swift | 3 | 942 | //
// PocketSVG_iOS_ExampleTests.swift
// PocketSVG iOS ExampleTests
//
// Created by Ariel Elkin on 08/03/2015.
// Copyright (c) 2015 Arielito. All rights reserved.
//
import UIKit
import XCTest
class PocketSVG_iOS_ExampleTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
vanyaland/Popular-Movies | iOS/PopularMovies/PopularMovies/MovieDateUtils.swift | 1 | 1804 | /**
* Copyright (c) 2016 Ivan Magda
*
* 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: MovieDateUtils
final class MovieDateUtils {
// MARK: Formatters
private static let dateFormatter: DateFormatter = {
var formatter = DateFormatter()
formatter.locale = Locale.current
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
// MARK: Init
private init() {
}
// MARK: Date Format
static func date(from dateString: String) -> Date? {
return dateFormatter.date(from: dateString)
}
static func year(from movie: Movie) -> Int {
let date = dateFormatter.date(from: movie.releaseDateString)!
let calendar = Calendar.current
return calendar.component(.year, from: date)
}
}
| mit |
prolificinteractive/Optik | Optik/Classes/ImageViewController.swift | 1 | 9956 | //
// ImageViewController.swift
// Optik
//
// Created by Htin Linn on 5/5/16.
// Copyright © 2016 Prolific Interactive. All rights reserved.
//
import UIKit
/// View controller for displaying a single photo.
internal final class ImageViewController: UIViewController {
fileprivate struct Constants {
static let MaximumZoomScale: CGFloat = 3
static let MinimumZoomScale: CGFloat = 1
static let ZoomAnimationDuration: TimeInterval = 0.3
}
// MARK: - Properties
var image: UIImage? {
didSet {
imageView?.image = image
resetImageView()
if let _ = image {
activityIndicatorView?.stopAnimating()
}
}
}
private(set) var imageView: UIImageView?
let index: Int
// MARK: - Private properties
private var activityIndicatorColor: UIColor?
private var scrollView: UIScrollView? {
didSet {
guard let scrollView = scrollView else {
return
}
scrollView.decelerationRate = UIScrollView.DecelerationRate.fast
scrollView.showsVerticalScrollIndicator = false
scrollView.showsHorizontalScrollIndicator = false
scrollView.minimumZoomScale = Constants.MinimumZoomScale
scrollView.maximumZoomScale = Constants.MaximumZoomScale
if #available(iOS 11.0, *) {
scrollView.contentInsetAdjustmentBehavior = .never
}
}
}
private var activityIndicatorView: UIActivityIndicatorView? {
didSet {
activityIndicatorView?.color = activityIndicatorColor
}
}
private var effectiveImageSize: CGSize?
// MARK: - Init/Deinit
init(image: UIImage? = nil, activityIndicatorColor: UIColor? = nil, index: Int) {
self.image = image
self.activityIndicatorColor = activityIndicatorColor
self.index = index
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("Invalid initializer.")
}
// MARK: - Override functions
override func viewDidLoad() {
super.viewDidLoad()
setupDesign()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
resizeScrollViewFrame(to: view.bounds.size)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { (_) in
self.resizeScrollViewFrame(to: size)
}, completion: nil)
}
// MARK: - Instance functions
/**
Resets and re-centers the image view.
*/
func resetImageView() {
scrollView?.zoomScale = Constants.MinimumZoomScale
calculateEffectiveImageSize()
if let effectiveImageSize = effectiveImageSize {
imageView?.frame = CGRect(x: 0, y: 0, width: effectiveImageSize.width, height: effectiveImageSize.height)
scrollView?.contentSize = effectiveImageSize
}
centerImage()
}
// MARK: - Private functions
private func setupDesign() {
let scrollView = UIScrollView(frame: view.bounds)
scrollView.delegate = self
view.addSubview(scrollView)
let imageView = UIImageView(frame: scrollView.bounds)
scrollView.addSubview(imageView)
self.scrollView = scrollView
self.imageView = imageView
if let image = image {
imageView.image = image
resetImageView()
} else {
let activityIndicatorView = UIActivityIndicatorView(style: .whiteLarge)
activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false
activityIndicatorView.hidesWhenStopped = true
activityIndicatorView.startAnimating()
view.addSubview(activityIndicatorView)
activityIndicatorView.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0).isActive = true
activityIndicatorView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 0).isActive = true
self.activityIndicatorView = activityIndicatorView
}
setupTapGestureRecognizer()
}
private func setupTapGestureRecognizer() {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ImageViewController.didDoubleTap(_:)))
tapGestureRecognizer.numberOfTouchesRequired = 1
tapGestureRecognizer.numberOfTapsRequired = 2 // Only allow double tap.
view.addGestureRecognizer(tapGestureRecognizer)
}
private func calculateEffectiveImageSize() {
guard
let image = image,
let scrollView = scrollView else {
return
}
let imageViewSize = scrollView.frame.size
let imageSize = image.size
let widthFactor = imageViewSize.width / imageSize.width
let heightFactor = imageViewSize.height / imageSize.height
let scaleFactor = (widthFactor < heightFactor) ? widthFactor : heightFactor
effectiveImageSize = CGSize(width: scaleFactor * imageSize.width, height: scaleFactor * imageSize.height)
}
fileprivate func centerImage() {
guard
let effectiveImageSize = effectiveImageSize,
let scrollView = scrollView else {
return
}
let scaledImageSize = CGSize(width: effectiveImageSize.width * scrollView.zoomScale,
height: effectiveImageSize.height * scrollView.zoomScale)
let verticalInset: CGFloat
let horizontalInset: CGFloat
if scrollView.frame.size.width > scaledImageSize.width {
horizontalInset = (scrollView.frame.size.width - scrollView.contentSize.width) / 2
} else {
horizontalInset = 0
}
if scrollView.frame.size.height > scaledImageSize.height {
verticalInset = (scrollView.frame.size.height - scrollView.contentSize.height) / 2
} else {
verticalInset = 0
}
scrollView.contentInset = UIEdgeInsets(top: verticalInset, left: horizontalInset, bottom: verticalInset, right: horizontalInset)
}
@objc private func didDoubleTap(_ sender: UITapGestureRecognizer) {
guard
let effectiveImageSize = effectiveImageSize,
let imageView = imageView,
let scrollView = scrollView else {
return
}
let tapPointInContainer = sender.location(in: view)
let scrollViewSize = scrollView.frame.size
let scaledImageSize = CGSize(width: effectiveImageSize.width * scrollView.zoomScale,
height: effectiveImageSize.height * scrollView.zoomScale)
let scaledImageRect = CGRect(x: (scrollViewSize.width - scaledImageSize.width) / 2,
y: (scrollViewSize.height - scaledImageSize.height) / 2,
width: scaledImageSize.width,
height: scaledImageSize.height)
guard scaledImageRect.contains(tapPointInContainer) else {
return
}
if scrollView.zoomScale > scrollView.minimumZoomScale {
// Zoom out if the image was zoomed in at all.
UIView.animate(
withDuration: Constants.ZoomAnimationDuration,
delay: 0,
options: [],
animations: {
scrollView.zoomScale = scrollView.minimumZoomScale
self.centerImage()
},
completion: nil
)
} else {
// Otherwise, zoom into the location of the tap point.
let width = scrollViewSize.width / scrollView.maximumZoomScale
let height = scrollViewSize.height / scrollView.maximumZoomScale
let tapPointInImageView = sender.location(in: imageView)
let originX = tapPointInImageView.x - (width / 2)
let originY = tapPointInImageView.y - (height / 2)
let zoomRect = CGRect(x: originX, y: originY, width: width, height: height)
UIView.animate(
withDuration: Constants.ZoomAnimationDuration,
delay: 0,
options: [],
animations: {
scrollView.zoom(to: zoomRect.enclose(imageView.bounds), animated: false)
},
completion: { (_) in
self.centerImage()
}
)
}
}
private func resizeScrollViewFrame(to size: CGSize) {
let oldSize = scrollView?.bounds.size
scrollView?.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
if oldSize != size {
resetImageView()
}
}
}
// MARK: - Protocol conformance
// MARK: UIScrollViewDelegate
extension ImageViewController: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
centerImage()
}
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
UIView.animate(withDuration: Constants.ZoomAnimationDuration, animations: {
self.centerImage()
})
}
}
| mit |
practicalswift/swift | test/PrintAsObjC/availability-real-sdk.swift | 36 | 9681 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o %t %s
// RUN: %target-swift-frontend -parse-as-library %t/availability-real-sdk.swiftmodule -typecheck -emit-objc-header-path %t/availability-real-sdk.h -import-objc-header %S/../Inputs/empty.h
// RUN: %FileCheck %s < %t/availability-real-sdk.h
// RUN: %check-in-clang %t/availability-real-sdk.h
// REQUIRES: objc_interop
// CHECK-LABEL: @interface NSArray<ObjectType> (SWIFT_EXTENSION(main))
// CHECK-NEXT: - (id _Nonnull)deprecatedMethodInFavorOfReverseObjectEnumerator SWIFT_WARN_UNUSED_RESULT
// CHECK-SAME: SWIFT_DEPRECATED_MSG("This method is deprecated in favor to the old reverseObjectEnumerator method", "reverseObjectEnumerator");
// CHECK-NEXT: - (id _Nonnull)deprecatedMethodOnMacOSInFavorOfReverseObjectEnumerator SWIFT_WARN_UNUSED_RESULT
// CHECK-SAME: SWIFT_AVAILABILITY(macos,deprecated=0.0.1,message="'deprecatedMethodOnMacOSInFavorOfReverseObjectEnumerator' has been renamed to 'reverseObjectEnumerator': This method is deprecated in favor to the old reverseObjectEnumerator method");
// CHECK-NEXT: - (id _Nonnull)unavailableMethodInFavorOfReverseObjectEnumerator SWIFT_WARN_UNUSED_RESULT
// CHECK-SAME: SWIFT_UNAVAILABLE_MSG("'unavailableMethodInFavorOfReverseObjectEnumerator' has been renamed to 'reverseObjectEnumerator': This method is unavailable in favor to the old reverseObjectEnumerator method");
// CHECK-NEXT: - (id _Nonnull)unavailableMethodOnMacOSInFavorOfReverseObjectEnumerator SWIFT_WARN_UNUSED_RESULT
// CHECK-SAME: SWIFT_AVAILABILITY(macos,unavailable,message="'unavailableMethodOnMacOSInFavorOfReverseObjectEnumerator' has been renamed to 'reverseObjectEnumerator': This method is unavailable in favor to the old reverseObjectEnumerator method");
// CHECK-NEXT: - (NSArray * _Nonnull)deprecatedMethodInFavorOfAddingObjectWithObject:(id _Nonnull)object SWIFT_WARN_UNUSED_RESULT
// CHECK-SAME: SWIFT_DEPRECATED_MSG("This method is deprecated in favor to the old adding method", "arrayByAddingObject:");
// CHECK-NEXT: - (NSArray * _Nonnull)deprecatedMethodOnMacOSInFavorOfAddingObjectWithObject:(id _Nonnull)object SWIFT_WARN_UNUSED_RESULT
// CHECK-SAME: SWIFT_AVAILABILITY(macos,deprecated=0.0.1,message="'deprecatedMethodOnMacOSInFavorOfAddingObject' has been renamed to 'arrayByAddingObject:': This method is deprecated in favor to the old adding method");
// CHECK-NEXT: - (NSArray * _Nonnull)unavailableMethodInFavorOfAddingObjectWithObject:(id _Nonnull)object SWIFT_WARN_UNUSED_RESULT
// CHECK-SAME: SWIFT_UNAVAILABLE_MSG("'unavailableMethodInFavorOfAddingObject' has been renamed to 'arrayByAddingObject:': This method is unavailable in favor to the old adding method");
// CHECK-NEXT: - (NSArray * _Nonnull)unavailableMethodOnMacOSInFavorOfAddingObjectWithObject:(id _Nonnull)object SWIFT_WARN_UNUSED_RESULT
// CHECK-SAME: SWIFT_AVAILABILITY(macos,unavailable,message="'unavailableMethodOnMacOSInFavorOfAddingObject' has been renamed to 'arrayByAddingObject:': This method is unavailable in favor to the old adding method");
// CHECK-NEXT: @end
// CHECK-LABEL: @interface SubClassOfSet : NSSet
// CHECK-NEXT: - (id _Nonnull)deprecatedMethodInFavorOfAnyObject SWIFT_WARN_UNUSED_RESULT
// CHECK-SAME: SWIFT_DEPRECATED_MSG("This method is deprecated in favor to the old anyObject method", "anyObject");
// CHECK-NEXT: - (id _Nonnull)deprecatedMethodOnMacOSInFavorOfAnyObject SWIFT_WARN_UNUSED_RESULT
// CHECK-SAME: SWIFT_AVAILABILITY(macos,deprecated=0.0.1,message="'deprecatedMethodOnMacOSInFavorOfAnyObject' has been renamed to 'anyObject': This method is deprecated in favor to the old anyObject method");
// CHECK-NEXT: - (id _Nonnull)unavailableMethodInFavorOfAnyObject SWIFT_WARN_UNUSED_RESULT
// CHECK-SAME: SWIFT_UNAVAILABLE_MSG("'unavailableMethodInFavorOfAnyObject' has been renamed to 'anyObject': This method is unavailable in favor to the old anyObject method");
// CHECK-NEXT: - (id _Nonnull)unavailableMethodOnMacOSInFavorOfAnyObject SWIFT_WARN_UNUSED_RESULT
// CHECK-SAME: SWIFT_AVAILABILITY(macos,unavailable,message="'unavailableMethodOnMacOSInFavorOfAnyObject' has been renamed to 'anyObject': This method is unavailable in favor to the old anyObject method");
// CHECK-NEXT: @property (nonatomic, readonly) NSInteger deprecatedPropertyInFavorOfCount
// CHECK-SAME: SWIFT_DEPRECATED_MSG("This property is deprecated in favor to the old count property", "count");
// CHECK-NEXT: @property (nonatomic, readonly) NSInteger deprecatedOnMacOSPropertyInFavorOfCount
// CHECK-SAME: SWIFT_AVAILABILITY(macos,deprecated=0.0.1,message="'deprecatedOnMacOSPropertyInFavorOfCount' has been renamed to 'count': This property is deprecated in favor to the old count property");
// CHECK-NEXT: @property (nonatomic, readonly) NSInteger unavailablePropertyInFavorOfCount
// CHECK-SAME: SWIFT_UNAVAILABLE_MSG("'unavailablePropertyInFavorOfCount' has been renamed to 'count': This property is unavailable in favor to the old count property");
// CHECK-NEXT: @property (nonatomic, readonly) NSInteger unavailableOnMacOSPropertyInFavorOfCount
// CHECK-SAME: SWIFT_AVAILABILITY(macos,unavailable,message="'unavailableOnMacOSPropertyInFavorOfCount' has been renamed to 'count': This property is unavailable in favor to the old count property");
// CHECK-NEXT: - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
// CHECK-NEXT: - (nonnull instancetype)initWithObjects:(id _Nonnull const * _Nullable)objects count:(NSUInteger)cnt OBJC_DESIGNATED_INITIALIZER;
// CHECK-NEXT: - (nullable instancetype)initWithCoder:(NSCoder * _Nonnull){{[a-zA-Z]+}} OBJC_DESIGNATED_INITIALIZER;
// CHECK-NEXT: @end
import Foundation
public class SubClassOfSet: NSSet {
@available(*, deprecated,
message: "This method is deprecated in favor to the old anyObject method",
renamed: "anyObject()")
@objc func deprecatedMethodInFavorOfAnyObject() -> Any { return 0 }
@available(macOS, deprecated,
message: "This method is deprecated in favor to the old anyObject method",
renamed: "anyObject()")
@objc func deprecatedMethodOnMacOSInFavorOfAnyObject() -> Any { return 0 }
@available(*, unavailable,
message: "This method is unavailable in favor to the old anyObject method",
renamed: "anyObject()")
@objc func unavailableMethodInFavorOfAnyObject() -> Any { return 0 }
@available(macOS, unavailable,
message: "This method is unavailable in favor to the old anyObject method",
renamed: "anyObject()")
@objc func unavailableMethodOnMacOSInFavorOfAnyObject() -> Any { return 0 }
@available(*, deprecated,
message: "This property is deprecated in favor to the old count property",
renamed: "count")
@objc var deprecatedPropertyInFavorOfCount: Int {
get {
return 0
}
}
@available(macOS, deprecated,
message: "This property is deprecated in favor to the old count property",
renamed: "count")
@objc var deprecatedOnMacOSPropertyInFavorOfCount: Int {
get {
return 0
}
}
@available(*, unavailable,
message: "This property is unavailable in favor to the old count property",
renamed: "count")
@objc var unavailablePropertyInFavorOfCount: Int {
get {
return 0
}
}
@available(macOS, unavailable,
message: "This property is unavailable in favor to the old count property",
renamed: "count")
@objc var unavailableOnMacOSPropertyInFavorOfCount: Int {
get {
return 0
}
}
}
extension NSArray {
@available(*, deprecated,
message: "This method is deprecated in favor to the old reverseObjectEnumerator method",
renamed: "reverseObjectEnumerator()")
@objc func deprecatedMethodInFavorOfReverseObjectEnumerator() -> Any { return 0 }
@available(macOS, deprecated,
message: "This method is deprecated in favor to the old reverseObjectEnumerator method",
renamed: "reverseObjectEnumerator()")
@objc func deprecatedMethodOnMacOSInFavorOfReverseObjectEnumerator() -> Any { return 0 }
@available(*, unavailable,
message: "This method is unavailable in favor to the old reverseObjectEnumerator method",
renamed: "reverseObjectEnumerator()")
@objc func unavailableMethodInFavorOfReverseObjectEnumerator() -> Any { return 0 }
@available(macOS, unavailable,
message: "This method is unavailable in favor to the old reverseObjectEnumerator method",
renamed: "reverseObjectEnumerator()")
@objc func unavailableMethodOnMacOSInFavorOfReverseObjectEnumerator() -> Any { return 0 }
@available(*, deprecated,
message: "This method is deprecated in favor to the old adding method",
renamed: "adding(_:)")
@objc func deprecatedMethodInFavorOfAddingObject(object: Any) -> NSArray {
return self.adding(object) as NSArray
}
@available(macOS, deprecated,
message: "This method is deprecated in favor to the old adding method",
renamed: "adding(_:)")
@objc func deprecatedMethodOnMacOSInFavorOfAddingObject(object: Any) -> NSArray {
return self.adding(object) as NSArray
}
@available(*, unavailable,
message: "This method is unavailable in favor to the old adding method",
renamed: "adding(_:)")
@objc func unavailableMethodInFavorOfAddingObject(object: Any) -> NSArray {
return self.adding(object) as NSArray
}
@available(macOS, unavailable,
message: "This method is unavailable in favor to the old adding method",
renamed: "adding(_:)")
@objc func unavailableMethodOnMacOSInFavorOfAddingObject(object: Any) -> NSArray {
return self.adding(object) as NSArray
}
}
| apache-2.0 |
avtr/bluejay | Bluejay/Bluejay/WriteResult.swift | 1 | 458 | //
// WriteResult.swift
// Bluejay
//
// Created by Jeremy Chiang on 2017-01-05.
// Copyright © 2017 Steamclock Software. All rights reserved.
//
import Foundation
/// Indicates a successful, cancelled, or failed write attempt.
public enum WriteResult {
/// The write is successful.
case success
/// The write is cancelled for a reason.
case cancelled
/// The write has failed unexpectedly with an error.
case failure(Error)
}
| mit |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/0354-swift-modulefile-maybereadpattern.swift | 13 | 398 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
false
func f<r>() -> (r, r -> r) -> r {
f r f.j = {
r) {
}
protocol j {
}
}
return { rray<T>) {
}
}, e)
class A {
class func a {
return static let d: String = {
return self.a()
}()
| apache-2.0 |
HongxiangShe/STV | STV/STV/Classes/Base/Model/BaseModel.swift | 1 | 484 | //
// BaseModel.swift
// SHXPageView
//
// Created by 佘红响 on 2017/6/12.
// Copyright © 2017年 she. All rights reserved.
//
import UIKit
class BaseModel: NSObject {
override init() {
super.init()
}
init(_ dict: [String: Any]) {
super.init()
setValuesForKeys(dict)
}
// 实现了该方法, 当找不到key的时候程序不至于崩溃
override func setValue(_ value: Any?, forUndefinedKey key: String) {}
}
| apache-2.0 |
drmohundro/Nimble | Nimble/Matchers/BeGreaterThan.swift | 1 | 1425 | import Foundation
public func beGreaterThan<T: Comparable>(expectedValue: T?) -> MatcherFunc<T?> {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be greater than <\(expectedValue)>"
return actualExpression.evaluate() > expectedValue
}
}
public func beGreaterThan(expectedValue: NMBComparable?) -> MatcherFunc<NMBComparable?> {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be greater than <\(expectedValue)>"
let actualValue = actualExpression.evaluate()
let matches = actualValue.hasValue && actualValue!.NMB_compare(expectedValue) == NSComparisonResult.OrderedDescending
return matches
}
}
public func ><T: Comparable>(lhs: Expectation<T?>, rhs: T) -> Bool {
lhs.to(beGreaterThan(rhs))
return true
}
public func >(lhs: Expectation<NMBComparable?>, rhs: NMBComparable?) -> Bool {
lhs.to(beGreaterThan(rhs))
return true
}
extension NMBObjCMatcher {
public class func beGreaterThanMatcher(expected: NMBComparable?) -> NMBObjCMatcher {
return NMBObjCMatcher { actualBlock, failureMessage, location in
let block = ({ actualBlock() as NMBComparable? })
let expr = Expression(expression: block, location: location)
return beGreaterThan(expected).matches(expr, failureMessage: failureMessage)
}
}
}
| apache-2.0 |
stefanoa/Spectrogram | Spectogram/fft.playground/Contents.swift | 1 | 1598 | import UIKit
import Accelerate
func sqrtq(_ x: [Float]) -> [Float] {
var results = [Float](repeating: 0.0, count: x.count)
vvsqrtf(&results, x, [Int32(x.count)])
return results
}
let sliceSize = 128
var inputSlice = [Float](repeating: 0, count: sliceSize)
var window = [Float](repeating: 0, count: sliceSize)
var transfer = [Float](repeating: 0, count: sliceSize)
vDSP_hann_window(&window, vDSP_Length(sliceSize), Int32(vDSP_HANN_NORM))
let log2n = UInt(round(log2(Double(sliceSize))))
let fftSetup = vDSP_create_fftsetup(log2n, Int32(kFFTRadix2))
var realp = [Float](repeating: 0, count: sliceSize/2)
var imagp = [Float](repeating: 0, count: sliceSize/2)
var outputSlice = DSPSplitComplex(realp: &realp, imagp: &imagp)
let f1:Float = 8.1
for i in 0...sliceSize-1{
let x:Float = 2 * .pi * Float(i)/Float(sliceSize)
inputSlice[i] = sin(f1*x)
}
//vDSP_vmul(&inputSlice, 1, &window, 1, &transfer, 1, vDSP_Length(sliceSize))
let temp = UnsafePointer<Float>(inputSlice)
temp.withMemoryRebound(to: DSPComplex.self, capacity: transfer.count) { (typeConvertedTransferBuffer) -> Void in
vDSP_ctoz(typeConvertedTransferBuffer, 2, &outputSlice, 1, vDSP_Length(sliceSize/2))
}
vDSP_fft_zrip(fftSetup!, &outputSlice, 1, log2n, FFTDirection(FFT_FORWARD))
var magnitudes = [Float](repeating: 0.0, count: sliceSize/2)
vDSP_zvmags(&outputSlice, 1, &magnitudes, 1, vDSP_Length(Int(sliceSize/2)))
var normalizedMagnitudes = [Float](repeating: 0.0, count: sliceSize/2)
let csize = sliceSize/2
for i in 0...csize-1{
normalizedMagnitudes[i] = sqrt(magnitudes[i])/Float(csize)
}
| mit |
kripple/bti-watson | ios-app/Carthage/Checkouts/AlamofireObjectMapper/Carthage/Checkouts/ObjectMapper/Carthage/Checkouts/Nimble/Nimble/Adapters/NimbleXCTestHandler.swift | 147 | 1532 | import Foundation
import XCTest
/// Default handler for Nimble. This assertion handler passes failures along to
/// XCTest.
public class NimbleXCTestHandler : AssertionHandler {
public func assert(assertion: Bool, message: FailureMessage, location: SourceLocation) {
if !assertion {
XCTFail("\(message.stringValue)\n", file: location.file, line: location.line)
}
}
}
/// Alternative handler for Nimble. This assertion handler passes failures along
/// to XCTest by attempting to reduce the failure message size.
public class NimbleShortXCTestHandler: AssertionHandler {
public func assert(assertion: Bool, message: FailureMessage, location: SourceLocation) {
if !assertion {
let msg: String
if let actual = message.actualValue {
msg = "got: \(actual) \(message.postfixActual)"
} else {
msg = "expected \(message.to) \(message.postfixMessage)"
}
XCTFail("\(msg)\n", file: location.file, line: location.line)
}
}
}
/// Fallback handler in case XCTest is unavailable. This assertion handler will abort
/// the program if it is invoked.
class NimbleXCTestUnavailableHandler : AssertionHandler {
func assert(assertion: Bool, message: FailureMessage, location: SourceLocation) {
fatalError("XCTest is not available and no custom assertion handler was configured. Aborting.")
}
}
func isXCTestAvailable() -> Bool {
return NSClassFromString("XCTestCase") != nil
}
| mit |
cherrythia/FYP | BarInsertVariables.swift | 1 | 6206 | //
// BarInsertVariables.swift
// FYP Table
//
// Created by Chia Wei Zheng Terry on 1/3/15.
// Copyright (c) 2015 Chia Wei Zheng Terry. All rights reserved.
//
import UIKit
import CoreData
class BarInsertVariables: UIViewController {
@IBOutlet weak var arrowOutlet: ForceArrow!
@IBOutlet weak var leftLabel: UILabel!
@IBOutlet weak var rightLabel: UILabel!
@IBOutlet weak var barImage: UIImageView!
var barImageArray : [UIImage] = [UIImage(named: "barAtWall.jpg")!,
UIImage(named: "bar.jpg")!,
UIImage(named: "BarAtWall1.jpg")!]
@IBOutlet weak var image: UIImageView!
@IBOutlet weak var forceLabel: UILabel!
@IBOutlet weak var forceEntered: UITextField!
@IBOutlet weak var lengthLabel: UILabel!
@IBOutlet weak var lengthEntered: UITextField!
@IBOutlet weak var modulusLabel: UILabel!
@IBOutlet weak var modulusEntered: UITextField!
@IBOutlet weak var areaLabel: UILabel!
@IBOutlet weak var areaEntered: UITextField!
@IBOutlet weak var isCheckedOutlet: CheckBox2!
var tempForce : Float = 0.0
var tempArea : Float = 0.0
var tempLength : Float = 0.0
var tempMod : Float = 0.0
var tempCount : Int = 0
var tempCheckedGlobal : Bool = false
var tempArrow : Bool = false
var tempMangObj : NSManagedObject!
var tempCanCheckCheckedBox : Bool = false
override func viewDidLoad() {
//disable the checkedbox function when user clicks on the detail view
if(tempMangObj != nil && tempCanCheckCheckedBox == false){
isCheckedOutlet.isEnabled = false
}
else{
isCheckedOutlet.isEnabled = true
}
leftLabel.text = "Node \(tempCount)"
rightLabel.text = "Node \(tempCount + 1)"
if(isCheckedGlobal == false) {
forceEntered.isEnabled = true
arrowOutlet.isEnabled = true
arrowOutlet.isHidden = false
if(tempCount != 0)
{
image.image = barImageArray[1]
} else
{
image.image = barImageArray[0]
}
}
if(isCheckedGlobal == true && tempCount != 0) {
barImage.image = barImageArray[2]
forceEntered.isEnabled = false
forceEntered.text = "0"
arrowOutlet.isEnabled = false
arrowOutlet.isHidden = true
}
}
override func viewDidAppear(_ animated: Bool) {
if(tempMangObj != nil)
{
forceEntered.text = "\(tempForce)N"
areaEntered.text = "\(tempArea)m^2"
lengthEntered.text = "\(tempLength)m"
modulusEntered.text = "\(tempMod)N/m^2"
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
@IBAction func barCheckboxed(_ sender: AnyObject) {
if(tempCount != 0){
if(isCheckedGlobal == true){
isCheckedGlobal = false
}
else{
isCheckedGlobal = true
}
}
else {
//Warming for the first bar element
let first_bar_alert = UIAlertController(title: "First bar must be inputted here", message: "First bar must always be attached on the left war here", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "OK", style: .default) {(ACTION: UIAlertAction!) -> Void in}
first_bar_alert.addAction(cancelAction)
present(first_bar_alert, animated: true, completion: nil)
}
self.viewDidLoad()
}
@IBAction func arrow(_ sender: AnyObject) {
if let force = forceEntered.text {
if(ArrowGlobal == true) {
ArrowGlobal = false
let tempForceConversion = (force as NSString).floatValue
forceEntered.text = "\(abs(tempForceConversion))"
}
else{
ArrowGlobal = true
forceEntered.text = "-\(force)"
}
}
}
@IBAction func barSubmit(_ sender: AnyObject) {
//CoreData
//Reference to App Delegate
let appDel : AppDelegate = UIApplication.shared.delegate as! AppDelegate
//Reference moc
let context : NSManagedObjectContext = appDel.managedObjectContext!
let en = NSEntityDescription.entity(forEntityName: "BarVariables", in: context)
if(tempMangObj != nil) { //save changes here
tempMangObj.setValue(NSString(string: forceEntered.text!).floatValue, forKey: "force")
tempMangObj.setValue(NSString(string: areaEntered.text!).floatValue, forKey: "area")
tempMangObj.setValue(NSString(string: lengthEntered.text!).floatValue, forKey: "length")
tempMangObj.setValue(NSString(string: modulusEntered.text!).floatValue, forKey: "youngMod")
tempMangObj.setValue((Bool: isCheckedGlobal), forKey: "globalChecked")
tempMangObj.setValue((Bool: ArrowGlobal), forKey: "arrowChecked")
}
else { //create new item here
var newItem = BarModel(entity:en!,insertInto: context)
newItem.area = NSString(string: areaEntered.text!).floatValue
newItem.length = NSString(string: lengthEntered.text!).floatValue
newItem.youngMod = NSString(string: modulusEntered.text!).floatValue
if(isCheckedGlobal == true){
newItem.force = 0
}
else{
newItem.force = NSString(string: forceEntered.text!).floatValue
}
print(newItem)
}
//save our context
do {
try context.save()
} catch {
}
self.navigationController?.popViewController(animated: true)
}
}
| mit |
netguru/inbbbox-ios | Inbbbox/Source Files/Collection View Layouts/TwoColumnsCollectionViewFlowLayout.swift | 1 | 2599 | //
// TwoColumnsCollectionViewFlowLayout.swift
// Inbbbox
//
// Created by Aleksander Popko on 25.01.2016.
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import UIKit
class TwoColumnsCollectionViewFlowLayout: UICollectionViewFlowLayout {
var itemHeightToWidthRatio = CGFloat(1)
var containsHeader = false
override func prepare() {
if let collectionView = collectionView {
let spacings = CollectionViewLayoutSpacings()
let calculatedItemWidth = (round(collectionView.bounds.width) -
3 * spacings.twoColumnsItemMargin) / 2
let calculatedItemHeight = calculatedItemWidth * itemHeightToWidthRatio
itemSize = CGSize(width: calculatedItemWidth, height: calculatedItemHeight)
minimumLineSpacing = spacings.twoColumnsMinimumLineSpacing
minimumInteritemSpacing = spacings.twoColumnsMinimymInterimSpacing
sectionInset = UIEdgeInsets(
top: spacings.twoColumnsSectionMarginVertical,
left: spacings.twoColumnsSectionMarginVertical,
bottom: spacings.twoColumnsSectionMarginHorizontal,
right: spacings.twoColumnsSectionMarginVertical
)
if containsHeader {
headerReferenceSize = CGSize(
width: collectionView.bounds.width,
height: 150
)
}
}
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
override func layoutAttributesForElements(in rect: CGRect)
-> [UICollectionViewLayoutAttributes]? {
let attributes = super.layoutAttributesForElements(in: rect)
guard let collectionView = collectionView else {
return attributes
}
let insets = collectionView.contentInset
let offset = collectionView.contentOffset
let minY = -insets.top
if offset.y < minY {
let deltaY = fabsf(Float(offset.y - minY))
attributes?.forEach {
if $0.representedElementKind == UICollectionElementKindSectionHeader {
var headerRect = $0.frame
headerRect.size.height = max(minY, headerReferenceSize.height + CGFloat(deltaY))
headerRect.origin.y = headerRect.origin.y - CGFloat(deltaY)
$0.frame = headerRect
$0.zIndex = 64
}
}
}
return attributes
}
}
| gpl-3.0 |
threefoldphotos/VWWAnnotationFanoutView | VWWAnnotationFanoutViewExampleSwift/HotelAnnotation.swift | 2 | 132 | //
// HotelAnnotation.swift
//
//
// Created by Zakk Hoyt on 6/16/15.
//
//
import Cocoa
class HotelAnnotation: NSObject {
}
| apache-2.0 |
sergiog90/PagedUITableViewController | PagedUITableViewControllerExample/PagedUITableViewControllerExample/AppDelegate.swift | 1 | 445 | //
// AppDelegate.swift
// PagedUITableViewControllerExample
//
// Created by Sergio Garcia on 23/9/16.
// Copyright © 2016 Sergio Garcia. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
return true
}
}
| mit |
austinzheng/swift | validation-test/compiler_crashers_fixed/00234-llvm-foldingset-swift-genericfunctiontype-nodeequals.swift | 65 | 4246 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func k<q {
enum k {
func j
var _ = j
}
}
class x {
s m
func j(m)
}
struct j<u> : r {
func j(j: j.n) {
}
}
enum q<v> { let k: v
let u: v.l
}
protocol y {
o= p>(r: m<v>)
}
struct D : y {
s p = Int
func y<v k r {
s m
}
class y<D> {
w <r:
func j<v x: v) {
x.k()
}
func x(j: Int = a) {
}
let k = x
protocol A {
func c() -> String
}
class B {
func d() -> String {
return ""
}
}
class C: B, A {
override func d() -> String {
return ""
}
func c() -> String {
return ""
}
}
func e<T where T: A, T: B>(t: T) {
t.c()
}
struct c<d : Sequence> {
var b: d
}
func a<d>() -> [c<d>] {
return []
}
b
protocol c : b { func b
func f<r>() -> (r, r -> r) -> r {
f r f.j = {
}
{
r) {
s }
}
protocol f {
class func j()
}
class f: f{ class func j {}
protocol j {
class func m()
}
class r: j {
class func m() { }
}
(r() n j).p.m()
j=k n j=k
protocol r {
class func q()
}
s m {
m f: r.q
func q() {
f.q()
}
(l, () -> ())
}
func f<l : o>(r: l)
func f<e>() -> (e, e -> e) -> e {
e b e.c = {}
{
e)
{
f
}
}
protocol f {
class func c()
}
class e: f {
class func c
}
}
func C<D, E: A where D.C == E> {
}
func prefix(with: String) -> <T>(() -> T) -> String {
{ g in "\(withing
}
clasnintln(some(xs))
protocol A {
func c()l k {
func l() -> g {
m ""
}
}
class C: k, A {
j func l()q c() -> g {
m ""
}
}
func e<r where r: A, r: k>(n: r) {
n.c()
}
protocol A {
typealias h
}
c k<r : A> {
p f: r
p p: r.h
}
protocol C l.e()
}
}
class o {
typealias l = l
w
class x<u>: d {
l i: u
init(i: u) {
o.i = j {
r { w s "\(f): \(w())" }
}
protocol h {
q k {
t w
}
w
protocol k : w { func v <h: h m h.p == k>(l: h.p) {
}
}
protocol h {
n func w(w:
}
class h<u : h> {
}
}
class b<i : b> i: g{ func c {}
e g {
: g {
h func i() -> }
struct c<d: Sequence, b where Optional<b> == d.Iterator.Element>
}
class p {
u _ = q() {
}
}
u l = r
u s: k -> k = {
n $h: m.j) {
}
}
o l() {
({})
}
struct m<t> {
let p: [(t, () -> ())] = []
}
protocol p : p {
}
protocol m {
o u() -> String
}
class j {
o m() -> String {
n ""
}
}
class h: j, m {
q o m() -> String {
n ""
}
o u() -> S, q> {
}
protocol u {
typealias u
}
class p {
typealias u = u
func a<d>() -> [c{ enum b {
case c
1, g(f, j)))
m k {
class h k()
}
struct i {
i d: k.l h k() {
n k
}
class g {
typealias k = k
}
class k {
func l((Any, k))(m }
}
func j<f: l: e -> e = {
{
l) {
m }
}
protocol k {
class func j()
}
class e: k{ class func j
func d<b: Sequence, e where Optional<e> == b.Iterator.Element>(c : b) -> e? {
for (mx : e?) in c {
}
}
func o() -> i) -> b {
n { o f "\(k): \(o())" }
}
struct d<d : n, o:j n {
l p
}
protocol o : o {
}
func o<
func i(c: () -> ()) {
}
class a {
var _ = i() {
}
}
() {
g g h g
}
}
func e(i: d) -> <f>(() -> f)>
>(f: B<{ }
})
}
func prefix(with: ng) -> <T>(() -> T)
func b(c) -> <d>(() -> d) {
}
func f() {
({})
}
func j(d: h) -> <k>(() -> k) -> h {
return { n n "\(}
c i<k : i> {
}
c i: i {
}
c e : l {
}
f = e
protocol m : o h = h
}
struct l<e : Sequence> {
l g: e
}
func h<e>() -> [l<e>] {
f []
}
func i(e: g) -> <j>(() -> j) -> k
func c<e>() -> (e -> e) -> e {
e, e -> e) n }
}
protocol f {
class func n()
}
class l: f{ class func n {}
func a<i>() {
b b {
l j
}
}
class a<f : b, l : b m f.l == l> {
}
protocol b {
typealias l
typealias k
}
struct j<n : b> : b {
typealias l = n
typealias k = a<j<n>, l>
}
d ""
e}
class d {
fun
| apache-2.0 |
yaobanglin/viossvc | viossvc/General/Helper/ChatSessionHelper.swift | 1 | 5045 | //
// ChatSessionHelper.swift
// viossvc
//
// Created by yaowang on 2016/12/3.
// Copyright © 2016年 com.yundian. All rights reserved.
//
import UIKit
protocol ChatSessionsProtocol : NSObjectProtocol {
func updateChatSessions(chatSession:[ChatSessionModel])
}
protocol ChatSessionProtocol : NSObjectProtocol {
func receiveMsg(chatMsgModel:ChatMsgModel)
func sessionUid() ->Int
}
class ChatSessionHelper: NSObject {
static let shared = ChatSessionHelper()
private var _chatSessions:[ChatSessionModel] = []
var chatSessions:[ChatSessionModel] {
return _chatSessions
}
weak var chatSessionsDelegate:ChatSessionsProtocol?
weak private var currentChatSessionDelegate:ChatSessionProtocol?
func findHistorySession() {
_chatSessions = ChatDataBaseHelper.ChatSession.findHistorySession()
syncUserInfos()
chatSessionSort()
}
func openChatSession(chatSessionDelegate:ChatSessionProtocol) {
currentChatSessionDelegate = chatSessionDelegate
let chatSession = findChatSession(currentChatSessionDelegate!.sessionUid())
if chatSession != nil {
if UIApplication.sharedApplication().applicationIconBadgeNumber < chatSession.noReading {
UIApplication.sharedApplication().applicationIconBadgeNumber = 0
} else {
UIApplication.sharedApplication().applicationIconBadgeNumber -= chatSession.noReading
}
chatSession.noReading = 0
updateChatSession(chatSession)
}
}
func closeChatSession() {
currentChatSessionDelegate = nil
}
func receiveMsg(chatMsgModel:ChatMsgModel) {
let sessionId = chatMsgModel.from_uid == CurrentUserHelper.shared.uid ? chatMsgModel.to_uid : chatMsgModel.from_uid
var chatSession = findChatSession(sessionId)
if chatSession == nil {
chatSession = createChatSession(sessionId)
chatSession.lastChatMsg = chatMsgModel
}
else if chatSession.lastChatMsg == nil
|| chatSession.lastChatMsg.msg_time < chatMsgModel.msg_time {
chatSession.lastChatMsg = chatMsgModel
chatSessionSort()
}
if currentChatSessionDelegate != nil {
currentChatSessionDelegate?.receiveMsg(chatMsgModel)
}
else if chatMsgModel.from_uid != CurrentUserHelper.shared.uid {
chatSession.noReading += 1
}
updateChatSession(chatSession)
}
func didReqeustUserInfoComplete(userInfo:UserInfoModel!) {
if userInfo != nil {
if let chatSession = findChatSession(userInfo.uid) {
chatSession.title = userInfo.nickname!
chatSession.icon = userInfo.head_url!
updateChatSession(chatSession)
}
}
}
func updateChatSession(chatSession:ChatSessionModel) {
ChatDataBaseHelper.ChatSession.updateModel(chatSession)
chatSessionsDelegate?.updateChatSessions(_chatSessions)
}
private func syncUserInfos() {
var getInfoIds = [String]()
for chatSesion in _chatSessions {
if chatSesion.type == ChatSessionType.Chat.rawValue && NSString.isEmpty(chatSesion.title) {
getInfoIds.append("\(chatSesion.sessionId)")
}
}
if getInfoIds.count > 0 {
AppAPIHelper.userAPI().getUserInfos(getInfoIds, complete: { [weak self] (array) in
let userInfos = array as? [UserInfoModel]
if userInfos != nil {
for userInfo in userInfos! {
self?.didReqeustUserInfoComplete(userInfo)
}
}
}, error: nil)
}
}
private func chatSessionSort() {
_chatSessions.sortInPlace({ (chatSession1, chatSession2) -> Bool in
return chatSession1.lastChatMsg?.msg_time > chatSession2.lastChatMsg?.msg_time
})
}
private func updateChatSessionUserInfo(uid:Int) {
AppAPIHelper.userAPI().getUserInfo(uid, complete: { [weak self](model) in
self?.didReqeustUserInfoComplete(model as? UserInfoModel)
}, error: {(error) in})
}
private func createChatSession(uid:Int) -> ChatSessionModel {
let chatSession = ChatSessionModel()
chatSession.sessionId = uid
_chatSessions.insert(chatSession, atIndex: 0)
if chatSession.type == 0 {
updateChatSessionUserInfo(uid)
}
ChatDataBaseHelper.ChatSession.addModel(chatSession)
return chatSession
}
private func findChatSession(uid:Int) ->ChatSessionModel! {
for chatSession in _chatSessions {
if chatSession.sessionId == uid {
return chatSession
}
}
return nil
}
}
| apache-2.0 |
jakerockland/Swisp | Sources/SwispFramework/Environment/Environment.swift | 1 | 4170 | //
// Environment.swift
// SwispFramework
//
// MIT License
//
// Copyright (c) 2018 Jake Rockland (http://jakerockland.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.
//
/// An environment with some Scheme standard procedures
public let standardEnv = Env([
// Constants
"π": Double.pi,
"pi": Double.pi,
"𝑒": Double.e,
"e": Double.e,
// Operators
"+": Operators.add,
"-": Operators.subtract,
"*": Operators.multiply,
"/": Operators.divide,
"%": Operators.mod,
">": Operators.greaterThan,
"<": Operators.lessThan,
">=": Operators.greaterThanEqual,
"<=": Operators.lessThanEqual,
"=": Operators.equal,
// Number-theoretic and representation functions
"ceil": Math.ceil,
"copysign": Math.copysign,
"fabs": Math.fabs,
"factorial":Math.factorial,
"floor": Math.floor,
"fmod": Math.fmod,
"frexp": Math.frexp,
"fsum": Math.fsum,
"isinf": Math.isinf,
"isnan": Math.isnan,
"ldexp": Math.ldexp,
"trunc": Math.trunc,
// Power and logarithmic functions
"exp": Math.exp,
"log": Math.log,
"log1p": Math.log1p,
"log10": Math.log10,
"pow": Math.pow,
"sqrt": Math.sqrt,
// Trigonometric functions
"acos": Math.acos,
"asin": Math.asin,
"atan": Math.atan,
"atan2": Math.atan2,
"cos": Math.cos,
"hypot": Math.hypot,
"sin": Math.sin,
"tan": Math.tan,
// Angular conversion
"degrees": Math.degrees,
"radians": Math.radians,
// Hyperbolic functions
"acosh": Math.acosh,
"asinh": Math.asinh,
"atanh": Math.atanh,
"cosh": Math.cosh,
"sinh": Math.sinh,
"tanh": Math.tanh,
// Special functions
"erf": Math.erf,
"erfc": Math.erfc,
"gamma": Math.gamma,
"lgamma": Math.lgamma,
// // Misc.
"abs": Library.abs,
"append": Library.append,
// // "apply": apply, // [TODO](https://www.drivenbycode.com/the-missing-apply-function-in-swift/)
// "begin": { $0[-1] },
"car": Library.car,
"cdr": Library.cdr,
// "cons": { [$0] + $1 },
// "eq?": { $0 === $1 },
// "equal?": { $0 == $1 },
// "length": { $0.count },
// "list": { List($0) },
// "list?": { $0 is List },
// // "map": map, // [TODO](https://www.weheartswift.com/higher-order-functions-map-filter-reduce-and-more/)
// "max": max,
// "min": min,
"not": Library.not,
// "null?": { $0 == nil },
// "number?": { $0 is Number },
// "procedure?": { String(type(of: $0)).containsString("->") },
// "round": round,
// "symbol?": { $0 is Symbol }
] as [Symbol: Any])
| mit |
aroyarexs/PASTA | Example/Pods/Metron/Metron/Classes/Extensions/CGRectEdge.swift | 1 | 1060 | import CoreGraphics
extension CGRectEdge : Opposable {
public static var allOpposites: [(CGRectEdge, CGRectEdge)] {
return [(.minXEdge, .maxXEdge), (.minYEdge, .maxYEdge)]
}
}
extension CGRectEdge : EdgeType {
public typealias CornerType = Corner
public var corners: (CornerType, CornerType) {
switch self {
case .minXEdge: return (.minXminY, .minXmaxY)
case .minYEdge: return (.minXminY, .maxXminY)
case .maxXEdge: return (.maxXminY, .maxXmaxY)
case .maxYEdge: return (.minXmaxY, .maxXmaxY)
}
}
public var axis: Axis {
switch self {
case .minXEdge, .maxXEdge: return .xAxis
case .minYEdge, .maxYEdge: return .yAxis
}
}
}
extension CGRectEdge : CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case .minXEdge: return "minXEdge"
case .maxXEdge: return "maxXEdge"
case .minYEdge: return "minYEdge"
case .maxYEdge: return "maxYEdge"
}
}
}
| mit |
aestesis/Aether | Sources/Aether/Foundation/Future.swift | 1 | 14195 | //
// Future.swift
// Aether
//
// Created by renan jegouzo on 29/03/2016.
// Copyright © 2016 aestesis. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public class Future : Atom {
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public enum State {
case inProgress
case cancel
case done
case error
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public let onDetach=Event<Void>()
private var _done=Event<Future>()
private var _cancel=Event<Future>()
private var _progress=Event<Future>()
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public private(set) var state:State = .inProgress
public private(set) var result:Any?
public private(set) var progress:Double=0
public private(set) var context:String?
public var autodetach = true
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
var prop:[String:Any]=[String:Any]()
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public subscript(k:String) -> Any? {
get {
return prop[k]
}
set(v) {
prop[k]=v
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public func then(_ fn:@escaping (Future)->()) {
let _ = _done.always(fn)
}
public func pulse(_ fn:@escaping (Future)->()) {
let _ = _progress.always(fn)
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public func cancel() {
if state == .inProgress {
state = .cancel
_cancel.dispatch(self)
if autodetach {
self.detach()
}
}
}
public func done(_ result:Any?=nil) {
if state == .inProgress {
self.result = result
state = .done
progress = 1
_progress.dispatch(self)
_done.dispatch(self)
if autodetach {
self.detach()
}
}
}
public func error(_ error:Error,_ f:String=#file,_ l:Int=#line) {
if state == .inProgress {
self.result=Error(error,f,l)
state = .error
_done.dispatch(self)
if autodetach {
self.detach()
}
}
}
public func error(_ reason:String,_ f:String=#file,_ l:Int=#line) {
error(Error(reason,f,l))
}
public func progress(_ value:Double) {
if state == .inProgress {
progress = value
_progress.dispatch(self)
}
}
public func onCancel(_ fn:@escaping (Future)->()) {
let _ = _cancel.always(fn)
}
/*
// TODO: leaking, must think about unpipe
public func pipe(to:Future) {
self.then { f in
switch f.state {
case .done:
to.done(f.result)
case .error:
let e = f.result as! Error
to.error(e)
default:
Debug.error("strange behavior",#file,#line)
break
}
}
self.pulse { f in
to.progress(f.progress)
}
to.onCancel { f in
self.cancel()
}
}
*/
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#if DEBUG
private let function:String
private let file:String
private let line:Int
public override var debugDescription: String {
return "Future.init(file:\(file),line:\(line),function:\(function))"
}
#endif
public init(context:String?=nil,file:String=#file,line:Int=#line,function:String=#function) {
#if DEBUG
self.file = file
self.line = line
self.function = function
#endif
self.context=context
super.init()
}
public func detach() {
onDetach.dispatch(())
onDetach.removeAll()
_done.removeAll()
_cancel.removeAll()
_progress.removeAll()
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public class Job : Future {
public let priority: Priority
public private(set) var action:(()->())?
public private(set) var owner : Node
public let info:String
public enum Priority : Int {
case high=0x0100
case normal=0x0200
case low=0x0300
}
public init(owner: Node, priority:Priority=Priority.normal, info:String="", action:@escaping ()->()) {
self.owner=owner
self.info=info
self.action=action
self.priority=priority
super.init()
}
public override func detach() {
action = nil
super.detach()
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public class Worker : NodeUI {
public var paused:Bool=false
var jobs=[Job]()
let lock=Lock()
var release:Bool=false
var threads:Int=0
#if DEBUG
var running=[String:Int]()
public func debugInfo() {
for k in running.keys {
if running[k]!>5 {
Debug.info("running \(k) \(running[k]!)")
}
}
}
#endif
public var count:Int {
var c=0
self.lock.synced {
c = self.jobs.count
}
return c
}
public func stop() {
var jl:[Job]?
release=true
self.lock.synced {
jl = self.jobs
self.jobs.removeAll()
}
for j in jl! {
j.cancel()
}
var wait = true
let w = self.wait(1) {
Debug.error("one thread takes too long, stop waiting...",#file,#line)
wait = false
}
while threads>0 && wait {
Thread.sleep(0.01)
}
if wait {
w.cancel()
}
}
public func cancel(_ owner:NodeUI) {
var cancel=[Job]()
lock.synced {
self.jobs = self.jobs.filter({ (j) -> Bool in
if j.owner == owner {
cancel.append(j)
return false
}
return true
})
}
for j in cancel {
j.cancel()
j.detach()
}
}
public func run(_ owner:NodeUI,priority:Job.Priority=Job.Priority.normal,info:String="",action:@escaping ()->()) -> Job {
let j=Job(owner:owner,priority:priority,info:info,action:action)
if release {
Debug.error("returning fake job",#file,#line)
return j // returns fake job
}
lock.synced {
self.jobs.append(j)
self.jobs.sort(by: { (a, b) -> Bool in
return a.priority.rawValue < b.priority.rawValue
})
}
j.onCancel { (p) in
self.lock.synced {
self.jobs=self.jobs.filter({ (ij) -> Bool in
return ij != j
})
}
}
return j
}
override public func detach() {
self.stop()
super.detach()
}
public init(parent:NodeUI,threads:Int=1) {
super.init(parent:parent)
for _ in 1...threads {
let _=Thread {
self.threads += 1
while !self.release {
if !self.paused {
var j:Job?=nil
self.lock.synced {
j=self.jobs.dequeue()
#if DEBUG
if let j=j {
if let r=self.running[j.owner.className] {
self.running[j.owner.className] = r+1
} else {
self.running[j.owner.className] = 1
}
}
#endif
}
if let j=j {
let owner = j.owner
if !self.release {
autoreleasepool {
j.done(j.action!())
}
}
#if DEBUG
self.lock.synced {
if let r=self.running[owner.className] {
if owner.className == "CacheNet" {
Debug.warning("removing CacheNet -> \(r-1)")
}
if r > 1 {
self.running[owner.className] = r-1
} else {
self.running.remove(at: self.running.index(forKey: owner.className)!)
}
}
}
#endif
j.detach()
} else {
Thread.sleep(0.001)
}
} else {
Thread.sleep(0.01)
}
}
self.threads -= 1
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public class Error : Atom, Swift.Error {
public let message:String
public let file:String
public let line:Int
public private(set) var origin:Error?
public override var description: String {
return "{ error:\"\(message)\" file:\"\(Debug.truncfile(file))\" line:\(line) }"
}
public init(_ message:String,_ file:String=#file,_ line:Int=#line) {
self.message=message
self.file=file
self.line=line
super.init()
}
public init(_ error:Error,_ file:String=#file,_ line:Int=#line) {
self.origin=error
self.message=error.message
self.file=file
self.line=line
super.init()
}
public func get<T>() -> T? {
if let v = self as? T {
return v
}
if let s = self.origin {
let v:T? = s.get()
return v
}
return nil
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#if os(Linux) // https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20161031/003823.html
func autoreleasepool(fn:()->()) {
fn()
}
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
| apache-2.0 |
SmallElephant/FESwiftDemo | 13-DashLine/13-DashLine/ViewController.swift | 1 | 5614 | //
// ViewController.swift
// 13-DashLine
//
// Created by keso on 2017/3/26.
// Copyright © 2017年 FlyElephant. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.lor.red
setUp()
setUp1()
setUp2()
setUp3()
setUp4()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK:SetUp
func setUp() {
let imgView:UIImageView = UIImageView(frame: CGRect(x: 0, y: 100, width: self.view.frame.width, height: 20))
self.view.addSubview(imgView)
UIGraphicsBeginImageContext(imgView.frame.size) // 位图上下文绘制区域
imgView.image?.draw(in: imgView.bounds)
let context:CGContext = UIGraphicsGetCurrentContext()!
context.setLineCap(CGLineCap.square)
let lengths:[CGFloat] = [10,20] // 绘制 跳过 无限循环
context.setStrokeColor(UIColor.red.cgColor)
context.setLineWidth(5)
context.setLineDash(phase: 0, lengths: lengths)
context.move(to: CGPoint(x: 0, y: 10))
context.addLine(to: CGPoint(x: self.view.frame.width, y: 10))
context.strokePath()
imgView.image = UIGraphicsGetImageFromCurrentImageContext()
}
func setUp1() {
let imgView:UIImageView = UIImageView(frame: CGRect(x: 0, y: 150, width: self.view.frame.width, height: 20))
self.view.addSubview(imgView)
UIGraphicsBeginImageContext(imgView.frame.size) // 位图上下文绘制区域
imgView.image?.draw(in: imgView.bounds)
let context:CGContext = UIGraphicsGetCurrentContext()!
context.setLineCap(CGLineCap.square)
let lengths:[CGFloat] = [10,20] // 绘制 跳过 无限循环
context.setStrokeColor(UIColor.red.cgColor)
context.setLineWidth(5)
context.setLineDash(phase: 5, lengths: lengths)
context.move(to: CGPoint(x: 0, y: 10))
context.addLine(to: CGPoint(x: self.view.frame.width, y: 10))
context.strokePath()
imgView.image = UIGraphicsGetImageFromCurrentImageContext()
}
func setUp2() {
let imgView:UIImageView = UIImageView(frame: CGRect(x: 0, y: 200, width: self.view.frame.width, height: 20))
self.view.addSubview(imgView)
UIGraphicsBeginImageContext(imgView.frame.size) // 位图上下文绘制区域
imgView.image?.draw(in: imgView.bounds)
let context:CGContext = UIGraphicsGetCurrentContext()!
context.setLineCap(CGLineCap.square)
let lengths:[CGFloat] = [10,20,10] // 绘制 跳过 无限循环
context.setStrokeColor(UIColor.red.cgColor)
context.setLineWidth(5)
context.setLineDash(phase: 0, lengths: lengths)
context.move(to: CGPoint(x: 0, y: 10))
context.addLine(to: CGPoint(x: self.view.frame.width, y: 10))
context.strokePath()
imgView.image = UIGraphicsGetImageFromCurrentImageContext()
}
func setUp3() {
let imgView:UIImageView = UIImageView(frame: CGRect(x: 0, y: 250, width: self.view.frame.width, height: 20))
self.view.addSubview(imgView)
UIGraphicsBeginImageContext(imgView.frame.size) // 位图上下文绘制区域 FlyElephant
imgView.image?.draw(in: imgView.bounds)
let context:CGContext = UIGraphicsGetCurrentContext()!
context.setLineCap(CGLineCap.square)
let lengths:[CGFloat] = [10,20] // 绘制 跳过 无限循环
context.setStrokeColor(UIColor.red.cgColor)
context.setLineWidth(2)
context.setLineDash(phase: 0, lengths: lengths)
context.move(to: CGPoint(x: 0, y: 10))
context.addLine(to: CGPoint(x: self.view.frame.width, y: 10))
context.strokePath()
context.setStrokeColor(UIColor.blue.cgColor)
context.setLineWidth(2)
context.setLineDash(phase: 0, lengths: lengths)
context.move(to: CGPoint(x: 15, y: 10))
context.addLine(to: CGPoint(x: self.view.frame.width, y: 10))
context.strokePath()
imgView.image = UIGraphicsGetImageFromCurrentImageContext()
}
func setUp4() {
let lineView:UIView = UIView(frame: CGRect(x: 0, y: 300, width: self.view.frame.width, height: 20))
self.view.addSubview(lineView)
let shapeLayer:CAShapeLayer = CAShapeLayer()
shapeLayer.bounds = lineView.bounds
shapeLayer.position = CGPoint(x: lineView.frame.width / 2, y: lineView.frame.height / 2)
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = UIColor.red.cgColor
shapeLayer.lineWidth = 5
shapeLayer.lineJoin = kCALineJoinRound
shapeLayer.lineDashPhase = 0
shapeLayer.lineDashPattern = [NSNumber(value: 10), NSNumber(value: 20)]
let path:CGMutablePath = CGMutablePath()
path.move(to: CGPoint(x: 0, y: 10))
path.addLine(to: CGPoint(x: lineView.frame.width, y: 10))
shapeLayer.path = path
lineView.layer.addSublayer(shapeLayer)
}
}
| mit |
abelsanchezali/ViewBuilder | Source/Layout/View/ManualLayoutHelper.swift | 1 | 1530 | //
// ManualLayoutHelper.swift
// ViewBuilder
//
// Created by Abel Sanchez on 8/13/16.
// Copyright © 2016 Abel Sanchez. All rights reserved.
//
import UIKit
extension CGFloat {
public static let largeValue: CGFloat = 100000000
}
open class ManualLayoutHelper: NSObject {
open class func linearLayout(_ size: CGFloat, before: CGFloat, after: CGFloat, available: CGFloat, alignment: LayoutAlignment) -> (CGFloat, CGFloat) {
switch alignment {
case .minimum:
return (before, before + size)
case .maximum:
let start = available - size - after
return (start, start + size)
case .center:
let start = (available - size + before - after) * 0.5
return (start, start + size)
case .stretch:
return (before, available - after)
}
}
open class func fitViewInContainer(_ view: UIView, container: UIView, margin: UIEdgeInsets = UIEdgeInsets.zero) {
let margin = view.margin
view.translatesAutoresizingMaskIntoConstraints = true
view.autoresizesSubviews = true
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
let bounds = container.bounds
let frame = CGRect(x: bounds.origin.x + margin.left,
y: bounds.origin.y + margin.top,
width: bounds.size.width - margin.totalWidth,
height: bounds.size.height - margin.totalHeight)
view.frame = frame
}
}
| mit |
apple/swift-syntax | Tests/SwiftParserTest/translated/ObjcEnumTests.swift | 1 | 1997 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This test file has been translated from swift/test/Parse/objc_enum.swift
import XCTest
final class ObjcEnumTests: XCTestCase {
func testObjcEnum1() {
AssertParse(
"""
@objc enum Foo: Int32 {
case Zim, Zang, Zung
}
"""
)
}
func testObjcEnum2() {
AssertParse(
"""
@objc enum Generic<T>: Int32 {
case Zim, Zang, Zung
}
"""
)
}
func testObjcEnum3() {
AssertParse(
"""
@objc(EnumRuntimeName) enum RuntimeNamed: Int32 {
case Zim, Zang, Zung
}
"""
)
}
func testObjcEnum4() {
AssertParse(
"""
@objc enum NoRawType {
case Zim, Zang, Zung
}
"""
)
}
func testObjcEnum5() {
AssertParse(
"""
@objc enum NonIntegerRawType: Float {
case Zim = 1.0, Zang = 1.5, Zung = 2.0
}
"""
)
}
func testObjcEnum6() {
AssertParse(
"""
enum NonObjCEnum: Int {
case Zim, Zang, Zung
}
"""
)
}
func testObjcEnum7() {
AssertParse(
"""
class Bar {
@objc func foo(x: Foo) {}
@objc func nonObjC(x: NonObjCEnum) {}
}
"""
)
}
func testObjcEnum8() {
AssertParse(
"""
// <rdar://problem/23681566> @objc enums with payloads rejected with no source location info
@objc enum r23681566 : Int32 {
case Foo(progress: Int)
}
"""
)
}
}
| apache-2.0 |
blue42u/swift-t | stc/tests/349-multidimensional-10.swift | 4 | 562 |
(int ret) f (int x) {
ret = x - 1;
}
() printArrays (int X[], int xoff,
int Y[], int yoff) {
trace(X[0+xoff], X[1+xoff], X[2+xoff], X[3+xoff],
Y[0+yoff], Y[1+yoff], Y[2+yoff], Y[3+yoff]);
}
main {
int M[][];
int M1[];
int M2[];
M[0] = M1;
M[1] = M2;
M1[2] = 1;
M1[3] = 2;
M1[4] = 3;
M1[5] = 4;
M2[5] = 4;
M2[6] = 3;
M2[7] = 2;
M2[8] = 1;
// Check that we can pass in array refs
// mixed with other arguments ok
printArrays(M[f(1)], 2, M[f(2)], 5);
}
| apache-2.0 |
merlos/iOS-Open-GPX-Tracker | OpenGpxTracker/UIColor+Keyboard.swift | 1 | 787 | //
// UIColor+Keyboard.swift
// OpenGpxTracker
//
// Created by Vincent Neo on 17/4/20.
//
import UIKit
/// For `DateFieldTypeView`. Meant to match default keyboard colors.
extension UIColor {
/// Default Light Appearance Keyboard
static let lightKeyboard = UIColor(red: 209/255, green: 213/255, blue: 219/255, alpha: 1.00)
/// Default Dark Appearance Keyboard
static let darkKeyboard = UIColor(red: 36/255, green: 36/255, blue: 36/255, alpha: 1.00)
/// Button Highlight Light Appearance Keyboard
static let highlightLightKeyboard = UIColor(red: 229/255, green: 233/255, blue: 239/255, alpha: 1.00)
/// Button Highlight Dark Appearance Keyboard
static let highlightDarkKeyboard = UIColor(red: 56/255, green: 56/255, blue: 56/255, alpha: 1.00)
}
| gpl-3.0 |
eigengo/best-intentions | ios/BestIntentionsFramework/Model.swift | 1 | 1255 | /*
* Best Intentions
* Copyright (C) 2016 Jan Machacek
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
struct Vice {
var name: String
}
struct Weather {
enum Overall {
case sun
case cloud
case rain
case snow
case other
}
var overall: Overall
var temperature: Measurement<UnitTemperature>
}
enum Mood {
case free
case normal
case busy
case veryBusy
case other
}
import CoreLocation
protocol LocationCoordinate {
var latitude: CLLocationDegrees { get }
var longitude: CLLocationDegrees { get }
}
extension CLLocationCoordinate2D : LocationCoordinate { }
| gpl-3.0 |
danlozano/Requestr | Example/TinyApiClientExample/AppDelegate.swift | 1 | 2195 | //
// AppDelegate.swift
// TinyApiClientExample
//
// Created by Daniel Lozano Valdés on 11/29/16.
// Copyright © 2016 danielozano. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
tjw/swift | test/IRGen/objc_properties_imported.swift | 2 | 1014 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-source-import -emit-ir -o - -primary-file %s | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
// FIXME: This test uses IRGen with -enable-source-import; it may fail with -g.
import Properties
// CHECK: @_INSTANCE_METHODS__TtC24objc_properties_imported21OverridesBoolProperty{{.*}}_selector_data(isEnabled){{.*}}L_selector_data(setIsEnabled:)
class OverridesBoolProperty : HasProperties {
override var enabled : Bool {
@objc(isEnabled) get {
return super.enabled
}
@objc(setIsEnabled:) set {
super.enabled = newValue
}
}
}
// CHECK-LABEL: define hidden swiftcc void @"$S24objc_properties_imported16testBoolProperty{{[_0-9a-zA-Z]*}}F"
func testBoolProperty(hp: HasProperties) {
// CHECK-NOT: ret void
// CHECK: load i8*, i8** @"\01L_selector(isEnabled)"
// CHECK-NOT: ret void
// CHECK: load i8*, i8** @"\01L_selector(setIsEnabled:)"
hp.enabled = !hp.enabled
// CHECK: ret void
}
| apache-2.0 |
Limon-O-O/Lego | Modules/Door/Door/Services/DoorUserDefaults.swift | 1 | 1594 | //
// DoorUserDefaults.swift
// Door
//
// Created by Limon on 27/02/2017.
// Copyright © 2017 Limon.F. All rights reserved.
//
import Foundation
import LegoContext
struct DoorUserDefaults {
fileprivate static let defaults = UserDefaults(suiteName: "top.limon.door")!
private init() {}
static func synchronize() {
defaults.synchronize()
}
static func clear() {
accessToken = nil
for key in defaults.dictionaryRepresentation().keys {
defaults.removeObject(forKey: key)
}
defaults.synchronize()
}
}
extension DoorUserDefaults {
fileprivate enum Keys: String {
case userID
case accessTokenV1
}
}
extension DoorUserDefaults {
static var didLogin: Bool {
return accessToken != nil && userID != nil
}
fileprivate static var _accessToken: String?
static var accessToken: String? {
get {
if _accessToken == nil {
_accessToken = defaults.string(forKey: Keys.accessTokenV1.rawValue)
}
return _accessToken
}
set {
_accessToken = newValue
defaults.set(newValue, forKey: Keys.accessTokenV1.rawValue)
LegoContext.accessToken = newValue
}
}
static var userID: Int? {
get {
let id = defaults.integer(forKey: Keys.userID.rawValue)
return id == 0 ? nil : id
}
set {
LegoContext.userID = newValue
defaults.set(newValue, forKey: Keys.userID.rawValue)
}
}
}
| mit |
modnovolyk/MAVLinkSwift | Sources/Data96ArdupilotmegaMsg.swift | 1 | 1141 | //
// Data96ArdupilotmegaMsg.swift
// MAVLink Protocol Swift Library
//
// Generated from ardupilotmega.xml, common.xml, uAvionix.xml on Tue Jan 17 2017 by mavgen_swift.py
// https://github.com/modnovolyk/MAVLinkSwift
//
import Foundation
/// Data packet, size 96
public struct Data96 {
/// data type
public let type: UInt8
/// data length
public let len: UInt8
/// raw data
public let data: [UInt8]
}
extension Data96: Message {
public static let id = UInt8(172)
public static var typeName = "DATA96"
public static var typeDescription = "Data packet, size 96"
public static var fieldDefinitions: [FieldDefinition] = [("type", 0, "UInt8", 0, "data type"), ("len", 1, "UInt8", 0, "data length"), ("data", 2, "[UInt8]", 96, "raw data")]
public init(data: Data) throws {
type = try data.number(at: 0)
len = try data.number(at: 1)
self.data = try data.array(at: 2, capacity: 96)
}
public func pack() throws -> Data {
var payload = Data(count: 98)
try payload.set(type, at: 0)
try payload.set(len, at: 1)
try payload.set(data, at: 2, capacity: 96)
return payload
}
}
| mit |
kaojohnny/CoreStore | Sources/ObjectiveC/CSOrderBy.swift | 1 | 3767 | //
// CSOrderBy.swift
// CoreStore
//
// Copyright © 2016 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
// MARK: - CSOrderBy
/**
The `CSOrderBy` serves as the Objective-C bridging type for `OrderBy`.
- SeeAlso: `OrderBy`
*/
@objc
public final class CSOrderBy: NSObject, CSFetchClause, CSQueryClause, CSDeleteClause, CoreStoreObjectiveCType {
/**
The list of sort descriptors
*/
@objc
public var sortDescriptors: [NSSortDescriptor] {
return self.bridgeToSwift.sortDescriptors
}
/**
Initializes a `CSOrderBy` clause with a single sort descriptor
```
MyPersonEntity *people = [transaction
fetchAllFrom:CSFromClass([MyPersonEntity class])
fetchClauses:@[CSOrderByKey(CSSortAscending(@"fullname"))]]];
```
- parameter sortDescriptor: a `NSSortDescriptor`
*/
@objc
public convenience init(sortDescriptor: NSSortDescriptor) {
self.init(OrderBy(sortDescriptor))
}
/**
Initializes a `CSOrderBy` clause with a list of sort descriptors
```
MyPersonEntity *people = [transaction
fetchAllFrom:CSFromClass([MyPersonEntity class])
fetchClauses:@[CSOrderByKeys(CSSortAscending(@"fullname"), CSSortDescending(@"age"), nil))]]];
```
- parameter sortDescriptors: an array of `NSSortDescriptor`s
*/
@objc
public convenience init(sortDescriptors: [NSSortDescriptor]) {
self.init(OrderBy(sortDescriptors))
}
// MARK: NSObject
public override var hash: Int {
return self.bridgeToSwift.hashValue
}
public override func isEqual(object: AnyObject?) -> Bool {
guard let object = object as? CSOrderBy else {
return false
}
return self.bridgeToSwift == object.bridgeToSwift
}
public override var description: String {
return "(\(String(reflecting: self.dynamicType))) \(self.bridgeToSwift.coreStoreDumpString)"
}
// MARK: CSFetchClause, CSQueryClause, CSDeleteClause
@objc
public func applyToFetchRequest(fetchRequest: NSFetchRequest) {
self.bridgeToSwift.applyToFetchRequest(fetchRequest)
}
// MARK: CoreStoreObjectiveCType
public let bridgeToSwift: OrderBy
public init(_ swiftValue: OrderBy) {
self.bridgeToSwift = swiftValue
super.init()
}
}
// MARK: - OrderBy
extension OrderBy: CoreStoreSwiftType {
// MARK: CoreStoreSwiftType
public typealias ObjectiveCType = CSOrderBy
}
| mit |
williamFalcon/Bolt_Swift | Source/NSDictionary/NSDictionary.swift | 2 | 692 | //
// NSDictionary.swift
// Poké Prism
//
// Created by William Falcon on 7/22/16.
// Copyright © 2016 William Falcon. All rights reserved.
//
import UIKit
public extension NSDictionary {
class func _jsonFromFileName(name:String) -> AnyObject? {
let masterDataUrl: NSURL = NSBundle.mainBundle().URLForResource(name, withExtension: "json")!
let jsonData: NSData = NSData(contentsOfURL: masterDataUrl)!
do {
let object = try NSJSONSerialization.JSONObjectWithData(jsonData, options: .AllowFragments)
return object
} catch {
// Handle Error
print(error)
return nil
}
}
}
| mit |
itsaboutcode/WordPress-iOS | WordPress/Classes/System/3DTouch/WP3DTouchShortcutCreator.swift | 1 | 8762 | import UIKit
import WordPressAuthenticator
public protocol ApplicationShortcutsProvider {
var shortcutItems: [UIApplicationShortcutItem]? { get set }
var is3DTouchAvailable: Bool { get }
}
extension UIApplication: ApplicationShortcutsProvider {
@objc public var is3DTouchAvailable: Bool {
return mainWindow?.traitCollection.forceTouchCapability == .available
}
}
open class WP3DTouchShortcutCreator: NSObject {
enum LoggedIn3DTouchShortcutIndex: Int {
case notifications = 0,
stats,
newPhotoPost,
newPost
}
var shortcutsProvider: ApplicationShortcutsProvider
@objc let mainContext = ContextManager.sharedInstance().mainContext
@objc let blogService: BlogService
fileprivate let logInShortcutIconImageName = "icon-shortcut-signin"
fileprivate let notificationsShortcutIconImageName = "icon-shortcut-notifications"
fileprivate let statsShortcutIconImageName = "icon-shortcut-stats"
fileprivate let newPhotoPostShortcutIconImageName = "icon-shortcut-new-photo"
fileprivate let newPostShortcutIconImageName = "icon-shortcut-new-post"
public init(shortcutsProvider: ApplicationShortcutsProvider) {
self.shortcutsProvider = shortcutsProvider
blogService = BlogService(managedObjectContext: mainContext)
super.init()
registerForNotifications()
}
public convenience override init() {
self.init(shortcutsProvider: UIApplication.shared)
}
@objc open func createShortcutsIf3DTouchAvailable(_ loggedIn: Bool) {
guard shortcutsProvider.is3DTouchAvailable else {
return
}
if loggedIn {
if hasBlog() {
createLoggedInShortcuts()
} else {
clearShortcuts()
}
} else {
createLoggedOutShortcuts()
}
}
fileprivate func registerForNotifications() {
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(WP3DTouchShortcutCreator.createLoggedInShortcuts), name: NSNotification.Name(rawValue: WordPressAuthenticator.WPSigninDidFinishNotification), object: nil)
notificationCenter.addObserver(self, selector: #selector(WP3DTouchShortcutCreator.createLoggedInShortcuts), name: .WPRecentSitesChanged, object: nil)
notificationCenter.addObserver(self, selector: #selector(WP3DTouchShortcutCreator.createLoggedInShortcuts), name: .WPBlogUpdated, object: nil)
notificationCenter.addObserver(self, selector: #selector(WP3DTouchShortcutCreator.createLoggedInShortcuts), name: .WPAccountDefaultWordPressComAccountChanged, object: nil)
}
fileprivate func loggedOutShortcutArray() -> [UIApplicationShortcutItem] {
let logInShortcut = UIMutableApplicationShortcutItem(type: WP3DTouchShortcutHandler.ShortcutIdentifier.LogIn.type,
localizedTitle: NSLocalizedString("Log In", comment: "Log In 3D Touch Shortcut"),
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: logInShortcutIconImageName),
userInfo: [WP3DTouchShortcutHandler.applicationShortcutUserInfoIconKey: WP3DTouchShortcutHandler.ShortcutIdentifier.LogIn.rawValue as NSSecureCoding])
return [logInShortcut]
}
fileprivate func loggedInShortcutArray() -> [UIApplicationShortcutItem] {
var defaultBlogName: String?
if blogService.blogCountForAllAccounts() > 1 {
defaultBlogName = blogService.lastUsedOrFirstBlog()?.settings?.name
}
let notificationsShortcut = UIMutableApplicationShortcutItem(type: WP3DTouchShortcutHandler.ShortcutIdentifier.Notifications.type,
localizedTitle: NSLocalizedString("Notifications", comment: "Notifications 3D Touch Shortcut"),
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: notificationsShortcutIconImageName),
userInfo: [WP3DTouchShortcutHandler.applicationShortcutUserInfoIconKey: WP3DTouchShortcutHandler.ShortcutIdentifier.Notifications.rawValue as NSSecureCoding])
let statsShortcut = UIMutableApplicationShortcutItem(type: WP3DTouchShortcutHandler.ShortcutIdentifier.Stats.type,
localizedTitle: NSLocalizedString("Stats", comment: "Stats 3D Touch Shortcut"),
localizedSubtitle: defaultBlogName,
icon: UIApplicationShortcutIcon(templateImageName: statsShortcutIconImageName),
userInfo: [WP3DTouchShortcutHandler.applicationShortcutUserInfoIconKey: WP3DTouchShortcutHandler.ShortcutIdentifier.Stats.rawValue as NSSecureCoding])
let newPhotoPostShortcut = UIMutableApplicationShortcutItem(type: WP3DTouchShortcutHandler.ShortcutIdentifier.NewPhotoPost.type,
localizedTitle: NSLocalizedString("New Photo Post", comment: "New Photo Post 3D Touch Shortcut"),
localizedSubtitle: defaultBlogName,
icon: UIApplicationShortcutIcon(templateImageName: newPhotoPostShortcutIconImageName),
userInfo: [WP3DTouchShortcutHandler.applicationShortcutUserInfoIconKey: WP3DTouchShortcutHandler.ShortcutIdentifier.NewPhotoPost.rawValue as NSSecureCoding])
let newPostShortcut = UIMutableApplicationShortcutItem(type: WP3DTouchShortcutHandler.ShortcutIdentifier.NewPost.type,
localizedTitle: NSLocalizedString("New Post", comment: "New Post 3D Touch Shortcut"),
localizedSubtitle: defaultBlogName,
icon: UIApplicationShortcutIcon(templateImageName: newPostShortcutIconImageName),
userInfo: [WP3DTouchShortcutHandler.applicationShortcutUserInfoIconKey: WP3DTouchShortcutHandler.ShortcutIdentifier.NewPost.rawValue as NSSecureCoding])
return [notificationsShortcut, statsShortcut, newPhotoPostShortcut, newPostShortcut]
}
@objc fileprivate func createLoggedInShortcuts() {
DispatchQueue.main.async {[weak self]() in
guard let strongSelf = self else {
return
}
let entireShortcutArray = strongSelf.loggedInShortcutArray()
var visibleShortcutArray = [UIApplicationShortcutItem]()
if strongSelf.hasWordPressComAccount() {
visibleShortcutArray.append(entireShortcutArray[LoggedIn3DTouchShortcutIndex.notifications.rawValue])
}
if strongSelf.doesCurrentBlogSupportStats() {
visibleShortcutArray.append(entireShortcutArray[LoggedIn3DTouchShortcutIndex.stats.rawValue])
}
if AppConfiguration.allowsNewPostShortcut {
visibleShortcutArray.append(entireShortcutArray[LoggedIn3DTouchShortcutIndex.newPhotoPost.rawValue])
visibleShortcutArray.append(entireShortcutArray[LoggedIn3DTouchShortcutIndex.newPost.rawValue])
}
strongSelf.shortcutsProvider.shortcutItems = visibleShortcutArray
}
}
fileprivate func clearShortcuts() {
shortcutsProvider.shortcutItems = nil
}
fileprivate func createLoggedOutShortcuts() {
shortcutsProvider.shortcutItems = loggedOutShortcutArray()
}
fileprivate func is3DTouchAvailable() -> Bool {
let window = UIApplication.shared.mainWindow
return window?.traitCollection.forceTouchCapability == .available
}
fileprivate func hasWordPressComAccount() -> Bool {
return AccountHelper.isDotcomAvailable()
}
fileprivate func doesCurrentBlogSupportStats() -> Bool {
guard let currentBlog = blogService.lastUsedOrFirstBlog() else {
return false
}
return hasWordPressComAccount() && currentBlog.supports(BlogFeature.stats)
}
fileprivate func hasBlog() -> Bool {
return blogService.blogCountForAllAccounts() > 0
}
}
| gpl-2.0 |
amnuaym/TiAppBuilder | Day1/MyFirstiOSApp/MyFirstiOSApp/ViewController.swift | 1 | 503 | //
// ViewController.swift
// MyFirstiOSApp
//
// Created by Amnuay M on 8/7/17.
// Copyright © 2017 Amnuay M. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-3.0 |
colbylwilliams/bugtrap | iOS/Code/Swift/bugTrap/bugTrapKit/Services/Protocols/Stringable.swift | 1 | 314 | //
// Stringable.swift
// bugTrap
//
// Created by Nate Rickard on 9/10/14.
// Copyright (c) 2014 bugTrap. All rights reserved.
//
import Foundation
protocol Stringable {
var string: String { get }
// func toString() -> String
}
extension String : Stringable {
var string: String {
return self
}
} | mit |
ethan605/dev-with-ethan | assets/media/snippets/posts/2016-06-30/swift-3.swift | 1 | 268 | var optionalInt: Int? = nil
print(optionalInt!) // fatal error: unexpectedly found nil while unwrapping an Optional value
optionalInt = 10
print(optionalInt!) // 10
"optionalInt = \(optionalInt)" // "optionalInt = 10"
| mit |
rb-de0/Fluxer | Sources/Flux/Action.swift | 1 | 155 | //
// Action.swift
// Fluxer
//
// Created by rb_de0 on 2017/03/21.
// Copyright © 2017年 rb_de0. All rights reserved.
//
public protocol Action {}
| mit |
krzysztofzablocki/Sourcery | SourceryRuntime/Sources/FileParserResult.swift | 1 | 4507 | //
// FileParserResult.swift
// Sourcery
//
// Created by Krzysztof Zablocki on 11/01/2017.
// Copyright © 2017 Pixle. All rights reserved.
//
import Foundation
// sourcery: skipJSExport
/// :nodoc:
@objcMembers public final class FileParserResult: NSObject, SourceryModel {
public let path: String?
public let module: String?
public var types = [Type]() {
didSet {
types.forEach { type in
guard type.module == nil, type.kind != "extensions" else { return }
type.module = module
}
}
}
public var functions = [SourceryMethod]()
public var typealiases = [Typealias]()
public var inlineRanges = [String: NSRange]()
public var inlineIndentations = [String: String]()
public var modifiedDate: Date
public var sourceryVersion: String
var isEmpty: Bool {
types.isEmpty && functions.isEmpty && typealiases.isEmpty && inlineRanges.isEmpty && inlineIndentations.isEmpty
}
public init(path: String?, module: String?, types: [Type], functions: [SourceryMethod], typealiases: [Typealias] = [], inlineRanges: [String: NSRange] = [:], inlineIndentations: [String: String] = [:], modifiedDate: Date = Date(), sourceryVersion: String = "") {
self.path = path
self.module = module
self.types = types
self.functions = functions
self.typealiases = typealiases
self.inlineRanges = inlineRanges
self.inlineIndentations = inlineIndentations
self.modifiedDate = modifiedDate
self.sourceryVersion = sourceryVersion
types.forEach { type in type.module = module }
}
// sourcery:inline:FileParserResult.AutoCoding
/// :nodoc:
required public init?(coder aDecoder: NSCoder) {
self.path = aDecoder.decode(forKey: "path")
self.module = aDecoder.decode(forKey: "module")
guard let types: [Type] = aDecoder.decode(forKey: "types") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["types"])); fatalError() }; self.types = types
guard let functions: [SourceryMethod] = aDecoder.decode(forKey: "functions") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["functions"])); fatalError() }; self.functions = functions
guard let typealiases: [Typealias] = aDecoder.decode(forKey: "typealiases") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["typealiases"])); fatalError() }; self.typealiases = typealiases
guard let inlineRanges: [String: NSRange] = aDecoder.decode(forKey: "inlineRanges") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["inlineRanges"])); fatalError() }; self.inlineRanges = inlineRanges
guard let inlineIndentations: [String: String] = aDecoder.decode(forKey: "inlineIndentations") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["inlineIndentations"])); fatalError() }; self.inlineIndentations = inlineIndentations
guard let modifiedDate: Date = aDecoder.decode(forKey: "modifiedDate") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["modifiedDate"])); fatalError() }; self.modifiedDate = modifiedDate
guard let sourceryVersion: String = aDecoder.decode(forKey: "sourceryVersion") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["sourceryVersion"])); fatalError() }; self.sourceryVersion = sourceryVersion
}
/// :nodoc:
public func encode(with aCoder: NSCoder) {
aCoder.encode(self.path, forKey: "path")
aCoder.encode(self.module, forKey: "module")
aCoder.encode(self.types, forKey: "types")
aCoder.encode(self.functions, forKey: "functions")
aCoder.encode(self.typealiases, forKey: "typealiases")
aCoder.encode(self.inlineRanges, forKey: "inlineRanges")
aCoder.encode(self.inlineIndentations, forKey: "inlineIndentations")
aCoder.encode(self.modifiedDate, forKey: "modifiedDate")
aCoder.encode(self.sourceryVersion, forKey: "sourceryVersion")
}
// sourcery:end
}
| mit |
uhnmdi/CCContinuousGlucose | CCContinuousGlucose/Classes/ContinuousGlucoseSOCP.swift | 1 | 5096 | //
// ContinuousGlucoseSOCP.swift
// Pods
//
// Created by Kevin Tallevi on 4/19/17.
//
// https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.cgm_specific_ops_control_point.xml
import Foundation
import CoreBluetooth
import CCBluetooth
public class ContinuousGlucoseSOCP : NSObject {
private let socpResponseOpCodeRange = NSRange(location:0, length: 1)
private let cgmCommunicationIntervalRange = NSRange(location:1, length: 1)
private let patientHighAlertLevelRange = NSRange(location:1, length: 2)
private let patientLowAlertLevelRange = NSRange(location:1, length: 2)
private let hypoAlertLevelRange = NSRange(location:1, length: 2)
private let hyperAlertLevelRange = NSRange(location:1, length: 2)
private let rateOfDecreaseAlertLevelRange = NSRange(location:1, length: 2)
private let rateOfIncreaseAlertLevelRange = NSRange(location:1, length: 2)
public var cgmCommunicationInterval: Int = 0
public var patientHighAlertLevel: UInt16 = 0
public var patientLowAlertLevel: UInt16 = 0
public var hypoAlertLevel: UInt16 = 0
public var hyperAlertLevel: UInt16 = 0
public var rateOfDecreaseAlertLevel: Float = 0
public var rateOfIncreaseAlertLevel: Float = 0
public var continuousGlucoseCalibration: ContinuousGlucoseCalibration!
enum Fields: Int {
case reserved,
setCGMCommunicationInterval,
getCGMCommunicationInterval,
cgmCommunicationIntervalResponse,
setGlucoseCalibrationValue,
getGlucoseCalibrationValue,
glucoseCalibrationValueResponse,
setPatientHighAlertLevel,
getPatientHighAlertLevel,
patientHighAlertLevelResponse,
setPatientLowAlertLevel,
getPatientLowAlertLevel,
patientLowAlertLevelResponse,
setHypoAlertLevel,
getHypoAlertLevel,
hypoAlertLevelResponse,
setHyperAlertLevel,
getHyperAlertLevel,
hyperAlertLevelResponse,
setRateOfDecreaseAlertLevel,
getRateOfDecreaseAlertLevel,
rateOfDecreaseAlertLevelResponse,
setRateOfIncreaseAlertLevel,
getRateOfIncreaseAlertLevel,
rateOfIncreaseAlertLevelResponse,
resetDeviceSpecificAlert,
startTheSession,
stopTheSession,
responseCode
}
public override init() {
super.init()
}
public func parseSOCP(data: NSData) {
let socpResponseType = (data.subdata(with: socpResponseOpCodeRange) as NSData!)
var socpResponse: Int = 0
socpResponseType?.getBytes(&socpResponse, length: 1)
switch (socpResponse) {
case ContinuousGlucoseSOCP.Fields.cgmCommunicationIntervalResponse.rawValue:
let communicationIntervalData = (data.subdata(with: cgmCommunicationIntervalRange) as NSData!)
communicationIntervalData?.getBytes(&self.cgmCommunicationInterval, length: 1)
return
case ContinuousGlucoseSOCP.Fields.glucoseCalibrationValueResponse.rawValue:
self.continuousGlucoseCalibration = ContinuousGlucoseCalibration(data: data)
return
case ContinuousGlucoseSOCP.Fields.patientHighAlertLevelResponse.rawValue:
let patientHighAlertLevelData = (data.subdata(with: patientHighAlertLevelRange) as NSData!)
patientHighAlertLevelData?.getBytes(&self.patientHighAlertLevel, length: 2)
return
case ContinuousGlucoseSOCP.Fields.patientLowAlertLevelResponse.rawValue:
let patientLowAlertLevelData = (data.subdata(with: patientLowAlertLevelRange) as NSData!)
patientLowAlertLevelData?.getBytes(&self.patientLowAlertLevel, length: 2)
return
case ContinuousGlucoseSOCP.Fields.hypoAlertLevelResponse.rawValue:
let hypoAlertLevelData = (data.subdata(with: hypoAlertLevelRange) as NSData!)
hypoAlertLevelData?.getBytes(&self.hypoAlertLevel, length: 2)
return
case ContinuousGlucoseSOCP.Fields.hyperAlertLevelResponse.rawValue:
let hyperAlertLevelData = (data.subdata(with: hyperAlertLevelRange) as NSData!)
hyperAlertLevelData?.getBytes(&self.hyperAlertLevel, length: 2)
return
case ContinuousGlucoseSOCP.Fields.rateOfDecreaseAlertLevelResponse.rawValue:
let rateOfDecreaseAlertLevelData = (data.subdata(with: rateOfDecreaseAlertLevelRange) as NSData!)
self.rateOfDecreaseAlertLevel = (rateOfDecreaseAlertLevelData?.shortFloatToFloat())!
return
case ContinuousGlucoseSOCP.Fields.rateOfIncreaseAlertLevelResponse.rawValue:
let rateOfIncreaseAlertLevelData = (data.subdata(with: rateOfIncreaseAlertLevelRange) as NSData!)
self.rateOfIncreaseAlertLevel = (rateOfIncreaseAlertLevelData?.shortFloatToFloat())!
return
default:
return
}
}
}
| mit |
PiXeL16/SwiftDelayer | SwiftDelayer/Delayer.swift | 1 | 1125 | //
// Delayer.swift
// SwiftDelayer
//
// Created by Chris Jimenez on 2/2/16.
// Copyright © 2016 Chris Jimenez. All rights reserved.
//
import Foundation
//Small util to suply a delay on the main queue
public class Delayer {
/**
Delays a call to a closure for the number of seconds
- parameter delay: Seconds to delay the call of the closure
- parameter closure: closure to be call
*/
public class func delayOnMainQueue(seconds seconds:Double, closure:()->()) {
return delayOnQueue(seconds: seconds, queue: dispatch_get_main_queue(), closure: closure)
}
/**
Delay on a specific queue for the number of seconds
- parameter seconds: seconds to delay
- parameter queue: queue
- parameter closure: closure to be call
*/
public class func delayOnQueue(seconds seconds:Double, queue:dispatch_queue_t, closure:()->()) {
let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC)))
dispatch_after(dispatchTime,queue, closure)
}
} | mit |
muyang00/YEDouYuTV | YEDouYuZB/YEDouYuZB/Home/Controller/GameViewController.swift | 1 | 4640 | //
// GameViewController.swift
// YEDouYuZB
//
// Created by yongen on 17/2/10.
// Copyright © 2017年 yongen. All rights reserved.
//
import UIKit
private let kEdgeMargin : CGFloat = 10
private let kItemW : CGFloat = (kScreenW - 2 * kEdgeMargin) / 3
private let kItemH = kItemW * 6 / 5
private let kGameHeadViewH : CGFloat = 90
private let kGameCellID = "kGameCellID"
private let kHeaderViewID = "kHeaderViewID"
class GameViewController: BaseViewController {
fileprivate lazy var gameVM : GameViewModel = GameViewModel()
fileprivate lazy var collectionView : UICollectionView = {[unowned self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.headerReferenceSize = CGSize(width: kScreenW, height: kGameHeadViewH)
layout.sectionInset = UIEdgeInsets(top: 0, left: kEdgeMargin, bottom: 0, right: kEdgeMargin)
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID)
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
return collectionView
}()
fileprivate lazy var gameView : RecommendGameView = {
let gameView = RecommendGameView.recommedGameView()
gameView.frame = CGRect(x: 0, y: -kGameHeadViewH, width: kScreenW, height: kGameHeadViewH)
return gameView
}()
fileprivate lazy var topHeaderView : CollectionHeaderView = {
let topHeaderView = CollectionHeaderView.collectionHeaderView()
topHeaderView.frame = CGRect(x: 0, y: -(kGameHeadViewH + kHeaderViewH), width: kScreenW, height: kHeaderViewH)
topHeaderView.headIconImageView.image = UIImage(named: "Img_orange")
topHeaderView.headNameLabel.text = "常用"
topHeaderView.headMoreBtn.isHidden = true
return topHeaderView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
//MARK: - 设置UI界面内容
extension GameViewController {
override func setupUI(){
contentView = collectionView
collectionView.contentInset = UIEdgeInsets(top: kGameHeadViewH + kHeaderViewH, left: 0, bottom: 0, right: 0)
view.addSubview(collectionView)
collectionView.addSubview(topHeaderView)
collectionView.addSubview(gameView)
super.setupUI()
}
}
//MARK: - 设置请求数据
extension GameViewController {
func loadData(){
gameVM.loadAllGameData {
self.collectionView.reloadData()
self.gameView.groups = Array(self.gameVM.games[0..<10])
self.loadDataFinished()
}
}
}
extension GameViewController : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.gameVM.games.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell
cell.baseGame = self.gameVM.games[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
// 1.取出HeaderView
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView
// 2.给HeaderView设置属性
headerView.headNameLabel.text = "全部"
headerView.headIconImageView.image = UIImage(named: "Img_orange")
headerView.headMoreBtn.isHidden = true
return headerView
}
}
extension GameViewController : UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("GameViewController ---- ", indexPath)
}
}
| apache-2.0 |
apple/swift-corelibs-foundation | Sources/FoundationNetworking/URLSession/HTTP/HTTPMessage.swift | 1 | 26755 | // Foundation/URLSession/HTTPMessage.swift - HTTP Message parsing
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
///
/// Helpers for parsing HTTP responses.
/// These are libcurl helpers for the URLSession API code.
/// - SeeAlso: https://curl.haxx.se/libcurl/c/
/// - SeeAlso: URLSession.swift
///
// -----------------------------------------------------------------------------
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import SwiftFoundation
#else
import Foundation
#endif
@_implementationOnly import CoreFoundation
internal extension _HTTPURLProtocol._ResponseHeaderLines {
/// Create an `NSHTTPRULResponse` from the lines.
///
/// This will parse the header lines.
/// - Returns: `nil` if an error occurred while parsing the header lines.
func createHTTPURLResponse(for URL: URL) -> HTTPURLResponse? {
guard let message = createHTTPMessage() else { return nil }
return HTTPURLResponse(message: message, URL: URL)
}
/// Parse the lines into a `_HTTPURLProtocol.HTTPMessage`.
func createHTTPMessage() -> _HTTPURLProtocol._HTTPMessage? {
guard let (head, tail) = lines.decompose else { return nil }
guard let startline = _HTTPURLProtocol._HTTPMessage._StartLine(line: head) else { return nil }
guard let headers = createHeaders(from: tail) else { return nil }
return _HTTPURLProtocol._HTTPMessage(startLine: startline, headers: headers)
}
}
extension HTTPURLResponse {
fileprivate convenience init?(message: _HTTPURLProtocol._HTTPMessage, URL: URL) {
/// This needs to be a request, i.e. it needs to have a status line.
guard case .statusLine(let version, let status, _) = message.startLine else { return nil }
let fields = message.headersAsDictionary
self.init(url: URL, statusCode: status, httpVersion: version.rawValue, headerFields: fields)
}
}
extension _HTTPURLProtocol {
/// HTTP Message
///
/// A message consist of a *start-line* optionally followed by one or multiple
/// message-header lines, and optionally a message body.
///
/// This represents everything except for the message body.
///
/// - SeeAlso: https://tools.ietf.org/html/rfc2616#section-4
struct _HTTPMessage {
let startLine: _HTTPURLProtocol._HTTPMessage._StartLine
let headers: [_HTTPURLProtocol._HTTPMessage._Header]
}
}
extension _HTTPURLProtocol._HTTPMessage {
var headersAsDictionary: [String: String] {
var result: [String: String] = [:]
headers.forEach {
if result[$0.name] == nil {
result[$0.name] = $0.value
}
else {
result[$0.name]! += (", " + $0.value)
}
}
return result
}
}
extension _HTTPURLProtocol._HTTPMessage {
/// A single HTTP message header field
///
/// Most HTTP messages have multiple header fields.
struct _Header {
let name: String
let value: String
}
/// The first line of a HTTP message
///
/// This can either be the *request line* (RFC 2616 Section 5.1) or the
/// *status line* (RFC 2616 Section 6.1)
enum _StartLine {
/// RFC 2616 Section 5.1 *Request Line*
/// - SeeAlso: https://tools.ietf.org/html/rfc2616#section-5.1
case requestLine(method: String, uri: URL, version: _HTTPURLProtocol._HTTPMessage._Version)
/// RFC 2616 Section 6.1 *Status Line*
/// - SeeAlso: https://tools.ietf.org/html/rfc2616#section-6.1
case statusLine(version: _HTTPURLProtocol._HTTPMessage._Version, status: Int, reason: String)
}
/// A HTTP version, e.g. "HTTP/1.1"
struct _Version: RawRepresentable {
let rawValue: String
}
/// An authentication challenge parsed from `WWW-Authenticate` header field.
///
/// Only parts necessary for Basic auth scheme are implemented at the moment.
/// - SeeAlso: https://tools.ietf.org/html/rfc7235#section-4.1
struct _Challenge {
static let AuthSchemeBasic = "basic"
static let AuthSchemeDigest = "digest"
/// A single auth challenge parameter
struct _AuthParameter {
let name: String
let value: String
}
let authScheme: String
let authParameters: [_AuthParameter]
}
}
extension _HTTPURLProtocol._HTTPMessage._Version {
init?(versionString: String) {
rawValue = versionString
}
}
extension _HTTPURLProtocol._HTTPMessage._Challenge {
/// Case-insensitively searches for auth parameter with specified name
func parameter(withName name: String) -> _AuthParameter? {
return authParameters.first { $0.name.caseInsensitiveCompare(name) == .orderedSame }
}
}
extension _HTTPURLProtocol._HTTPMessage._Challenge {
/// Creates authentication challenges from provided `HTTPURLResponse`.
///
/// The value of `WWW-Authenticate` field is used for parsing authentication challenges
/// of supported type.
///
/// - note: `Basic` is the only supported scheme at the moment.
/// - parameter response: A response to get header value from.
/// - returns: An array of supported challenges found in response.
/// # Reference
/// - [RFC 7235 - Hypertext Transfer Protocol (HTTP/1.1): Authentication](https://tools.ietf.org/html/rfc7235)
/// - [RFC 7617 - The 'Basic' HTTP Authentication Scheme](https://tools.ietf.org/html/rfc7617)
static func challenges(from response: HTTPURLResponse) -> [_HTTPURLProtocol._HTTPMessage._Challenge] {
guard let authenticateValue = response.value(forHTTPHeaderField: "WWW-Authenticate") else {
return []
}
return challenges(from: authenticateValue)
}
/// Creates authentication challenges from provided field value.
///
/// Field value is expected to conform [RFC 7235 Section 4.1](https://tools.ietf.org/html/rfc7235#section-4.1)
/// as much as needed to define supported authorization schemes.
///
/// - note: `Basic` is the only supported scheme at the moment.
/// - parameter authenticateFieldValue: A value of `WWW-Authenticate` field
/// - returns: array of supported challenges found.
/// # Reference
/// - [RFC 7235 - Hypertext Transfer Protocol (HTTP/1.1): Authentication](https://tools.ietf.org/html/rfc7235)
/// - [RFC 7617 - The 'Basic' HTTP Authentication Scheme](https://tools.ietf.org/html/rfc7617)
static func challenges(from authenticateFieldValue: String) -> [_HTTPURLProtocol._HTTPMessage._Challenge] {
var challenges = [_HTTPURLProtocol._HTTPMessage._Challenge]()
// Typical WWW-Authenticate header is something like
// WWWW-Authenticate: Digest realm="test", domain="/HTTP/Digest", nonce="e3d002b9b2080453fdacea2d89f2d102"
//
// https://tools.ietf.org/html/rfc7235#section-4.1
// WWW-Authenticate = 1#challenge
//
// https://tools.ietf.org/html/rfc7235#section-2.1
// challenge = auth-scheme [ 1*SP ( token68 / #auth-param ) ]
// auth-scheme = token
// auth-param = token BWS "=" BWS ( token / quoted-string )
// token68 = 1*( ALPHA / DIGIT /
// "-" / "." / "_" / "~" / "+" / "/" ) *"="
//
// https://tools.ietf.org/html/rfc7230#section-3.2.3
// OWS = *( SP / HTAB ) ; optional whitespace
// BWS = OWS ; "bad" whitespace
//
// https://tools.ietf.org/html/rfc7230#section-3.2.6
// token = 1*tchar
// tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
// / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
// / DIGIT / ALPHA
// ; any VCHAR, except delimiters
// quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
// qdtext = HTAB / SP /%x21 / %x23-5B / %x5D-7E / obs-text
// obs-text = %x80-FF
// quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
//
// https://tools.ietf.org/html/rfc5234#appendix-B.1
// ALPHA = %x41-5A / %x61-7A ; A-Z / a-z
// SP = %x20
// HTAB = %x09 ; horizontal tab
// VCHAR = %x21-7E ; visible (printing) characters
// DQUOTE = %x22
// DIGIT = %x30-39 ; 0-9
var authenticateView = authenticateFieldValue.unicodeScalars[...]
// Do an "eager" search of supported auth schemes. Same as it implemented in CURL.
// This means we will look after every comma on every step, no matter what was
// (or wasn't) parsed on previous step.
//
// WWW-Authenticate field could contain some sort of ambiguity, because, in general,
// it is a comma-separated list of comma-separated lists. As mentioned
// in https://tools.ietf.org/html/rfc7235#section-4.1, user agents are advised to
// take special care of parsing all challenges completely.
while !authenticateView.isEmpty {
guard let authSchemeRange = authenticateView.rangeOfTokenPrefix else {
break
}
let authScheme = String(authenticateView[authSchemeRange])
if authScheme.caseInsensitiveCompare(AuthSchemeBasic) == .orderedSame {
let authDataView = authenticateView[authSchemeRange.upperBound...]
let authParameters = _HTTPURLProtocol._HTTPMessage._Challenge._AuthParameter.parameters(from: authDataView)
let challenge = _HTTPURLProtocol._HTTPMessage._Challenge(authScheme: authScheme, authParameters: authParameters)
// "realm" is the only mandatory parameter for Basic auth scheme. Otherwise consider parsed data invalid.
if challenge.parameter(withName: "realm") != nil {
challenges.append(challenge)
}
}
// read up to the next comma
guard let commaIndex = authenticateView.firstIndex(of: _Delimiters.Comma) else {
break
}
// skip comma
authenticateView = authenticateView[authenticateView.index(after: commaIndex)...]
// consume spaces
authenticateView = authenticateView.trimSPPrefix
}
return challenges
}
}
private extension _HTTPURLProtocol._HTTPMessage._Challenge._AuthParameter {
/// Reads authorization challenge parameters from provided Unicode Scalar view
static func parameters(from parametersView: String.UnicodeScalarView.SubSequence) -> [_HTTPURLProtocol._HTTPMessage._Challenge._AuthParameter] {
var parametersView = parametersView
var parameters = [_HTTPURLProtocol._HTTPMessage._Challenge._AuthParameter]()
while true {
parametersView = parametersView.trimSPPrefix
guard let parameter = parameter(from: ¶metersView) else {
break
}
parameters.append(parameter)
// trim spaces and expect comma
parametersView = parametersView.trimSPPrefix
guard parametersView.first == _Delimiters.Comma else {
break
}
// drop comma
parametersView = parametersView.dropFirst()
}
return parameters
}
/// Reads a single challenge parameter from provided Unicode Scalar view
private static func parameter(from parametersView: inout String.UnicodeScalarView.SubSequence) -> _HTTPURLProtocol._HTTPMessage._Challenge._AuthParameter? {
// Read parameter name. Return nil if name is not readable.
guard let parameterName = parameterName(from: ¶metersView) else {
return nil
}
// Trim BWS, expect '='
parametersView = parametersView.trimSPHTPrefix ?? parametersView
guard parametersView.first == _Delimiters.Equals else {
return nil
}
// Drop '='
parametersView = parametersView.dropFirst()
// Read parameter value. Return nil if parameter is not readable.
guard let parameterValue = parameterValue(from: ¶metersView) else {
return nil
}
return _HTTPURLProtocol._HTTPMessage._Challenge._AuthParameter(name: parameterName, value: parameterValue)
}
/// Reads a challenge parameter name from provided Unicode Scalar view
private static func parameterName(from nameView: inout String.UnicodeScalarView.SubSequence) -> String? {
guard let nameRange = nameView.rangeOfTokenPrefix else {
return nil
}
let name = String(nameView[nameRange])
nameView = nameView[nameRange.upperBound...]
return name
}
/// Reads a challenge parameter value from provided Unicode Scalar view
private static func parameterValue(from valueView: inout String.UnicodeScalarView.SubSequence) -> String? {
// Trim BWS
valueView = valueView.trimSPHTPrefix ?? valueView
if valueView.first == _Delimiters.DoubleQuote {
// quoted-string
if let valueRange = valueView.rangeOfQuotedStringPrefix {
let value = valueView[valueRange].dequotedString()
valueView = valueView[valueRange.upperBound...]
return value
}
}
else {
// token
if let valueRange = valueView.rangeOfTokenPrefix {
let value = String(valueView[valueRange])
valueView = valueView[valueRange.upperBound...]
return value
}
}
return nil
}
}
private extension _HTTPURLProtocol._HTTPMessage._StartLine {
init?(line: String) {
guard let r = line.splitRequestLine() else { return nil }
if let version = _HTTPURLProtocol._HTTPMessage._Version(versionString: r.0) {
// Status line:
guard let status = Int(r.1), 100 <= status && status <= 999 else { return nil }
self = .statusLine(version: version, status: status, reason: r.2)
} else if let version = _HTTPURLProtocol._HTTPMessage._Version(versionString: r.2),
let URI = URL(string: r.1) {
// The request method must be a token (i.e. without separators):
let separatorIdx = r.0.unicodeScalars.firstIndex(where: { !$0.isValidMessageToken } )
guard separatorIdx == nil else { return nil }
self = .requestLine(method: r.0, uri: URI, version: version)
} else {
return nil
}
}
}
private extension String {
/// Split a request line into its 3 parts: *Method*, *Request-URI*, and *HTTP-Version*.
/// - SeeAlso: https://tools.ietf.org/html/rfc2616#section-5.1
func splitRequestLine() -> (String, String, String)? {
let scalars = self.unicodeScalars[...]
guard let firstSpace = scalars.rangeOfSpace else { return nil }
let remainingRange = firstSpace.upperBound..<scalars.endIndex
let remainder = scalars[remainingRange]
guard let secondSpace = remainder.rangeOfSpace else { return nil }
let methodRange = scalars.startIndex..<firstSpace.lowerBound
let uriRange = remainder.startIndex..<secondSpace.lowerBound
let versionRange = secondSpace.upperBound..<remainder.endIndex
//TODO: is this necessary? If yes, this guard needs an alternate implementation
//guard 0 < methodRange.count && 0 < uriRange.count && 0 < versionRange.count else { return nil }
let m = String(scalars[methodRange])
let u = String(remainder[uriRange])
let v = String(remainder[versionRange])
return (m, u, v)
}
}
/// Parses an array of lines into an array of
/// `URLSessionTask.HTTPMessage.Header`.
///
/// This respects the header folding as described by
/// https://tools.ietf.org/html/rfc2616#section-2.2 :
///
/// - SeeAlso: `_HTTPURLProtocol.HTTPMessage.Header.createOne(from:)`
private func createHeaders(from lines: ArraySlice<String>) -> [_HTTPURLProtocol._HTTPMessage._Header]? {
var headerLines = Array(lines)
var headers: [_HTTPURLProtocol._HTTPMessage._Header] = []
while !headerLines.isEmpty {
guard let (header, remaining) = _HTTPURLProtocol._HTTPMessage._Header.createOne(from: headerLines) else { return nil }
headers.append(header)
headerLines = remaining
}
return headers
}
private extension _HTTPURLProtocol._HTTPMessage._Header {
/// Parse a single HTTP message header field
///
/// Each header field consists
/// of a name followed by a colon (":") and the field value. Field names
/// are case-insensitive. The field value MAY be preceded by any amount
/// of LWS, though a single SP is preferred. Header fields can be
/// extended over multiple lines by preceding each extra line with at
/// least one SP or HT. Applications ought to follow "common form", where
/// one is known or indicated, when generating HTTP constructs, since
/// there might exist some implementations that fail to accept anything
/// beyond the common forms.
///
/// Consumes lines from the given array of lines to produce a single HTTP
/// message header and returns the resulting header plus the remainder.
///
/// If an error occurs, it returns `nil`.
///
/// - SeeAlso: https://tools.ietf.org/html/rfc2616#section-4.2
static func createOne(from lines: [String]) -> (_HTTPURLProtocol._HTTPMessage._Header, [String])? {
// HTTP/1.1 header field values can be folded onto multiple lines if the
// continuation line begins with a space or horizontal tab. All linear
// white space, including folding, has the same semantics as SP. A
// recipient MAY replace any linear white space with a single SP before
// interpreting the field value or forwarding the message downstream.
guard let (head, tail) = lines.decompose else { return nil }
let headView = head.unicodeScalars[...]
guard let nameRange = headView.rangeOfTokenPrefix else { return nil }
guard headView.index(after: nameRange.upperBound) <= headView.endIndex && headView[nameRange.upperBound] == _Delimiters.Colon else { return nil }
let name = String(headView[nameRange])
var value: String?
let line = headView[headView.index(after: nameRange.upperBound)..<headView.endIndex]
if !line.isEmpty {
if line.hasSPHTPrefix && line.count == 1 {
// to handle empty headers i.e header without value
value = ""
} else {
guard let v = line.trimSPHTPrefix else { return nil }
value = String(v)
}
}
do {
var t = tail
while t.first?.unicodeScalars[...].hasSPHTPrefix ?? false {
guard let (h2, t2) = t.decompose else { return nil }
t = t2
guard let v = h2.unicodeScalars[...].trimSPHTPrefix else { return nil }
let valuePart = String(v)
value = value.map { $0 + " " + valuePart } ?? valuePart
}
return (_HTTPURLProtocol._HTTPMessage._Header(name: name, value: value ?? ""), Array(t))
}
}
}
private extension Collection {
/// Splits the collection into its first element and the remainder.
var decompose: (Iterator.Element, Self.SubSequence)? {
guard let head = self.first else { return nil }
let tail = self[self.index(after: startIndex)..<endIndex]
return (head, tail)
}
}
private extension String.UnicodeScalarView.SubSequence {
/// The range of *Token* characters as specified by RFC 2616.
var rangeOfTokenPrefix: Range<Index>? {
guard !isEmpty else { return nil }
var end = startIndex
while self[end].isValidMessageToken {
end = self.index(after: end)
}
guard end != startIndex else { return nil }
return startIndex..<end
}
/// The range of space (U+0020) characters.
var rangeOfSpace: Range<Index>? {
guard !isEmpty else { return startIndex..<startIndex }
guard let idx = firstIndex(of: _Delimiters.Space!) else { return nil }
return idx..<self.index(after: idx)
}
// Has a space (SP) or horizontal tab (HT) prefix
var hasSPHTPrefix: Bool {
guard !isEmpty else { return false }
return self[startIndex] == _Delimiters.Space || self[startIndex] == _Delimiters.HorizontalTab
}
/// Unicode scalars after removing the leading spaces (SP) and horizontal tabs (HT).
/// Returns `nil` if the unicode scalars do not start with a SP or HT.
var trimSPHTPrefix: SubSequence? {
guard !isEmpty else { return nil }
var idx = startIndex
while idx < endIndex {
if self[idx] == _Delimiters.Space || self[idx] == _Delimiters.HorizontalTab {
idx = self.index(after: idx)
} else {
guard startIndex < idx else { return nil }
return self[idx..<endIndex]
}
}
return nil
}
var trimSPPrefix: SubSequence {
var idx = startIndex
while idx < endIndex {
if self[idx] == _Delimiters.Space {
idx = self.index(after: idx)
} else {
return self[idx..<endIndex]
}
}
return self
}
/// Returns range of **quoted-string** starting from first index of sequence.
///
/// - returns: range of **quoted-string** or `nil` if value can not be parsed.
var rangeOfQuotedStringPrefix: Range<Index>? {
// quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
// qdtext = HTAB / SP /%x21 / %x23-5B / %x5D-7E / obs-text
// obs-text = %x80-FF
// quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
guard !isEmpty else {
return nil
}
var idx = startIndex
// Expect and consume dquote
guard self[idx] == _Delimiters.DoubleQuote else {
return nil
}
idx = self.index(after: idx)
var isQuotedPair = false
while idx < endIndex {
let currentScalar = self[idx]
if currentScalar == _Delimiters.Backslash && !isQuotedPair {
isQuotedPair = true
} else if isQuotedPair {
guard currentScalar.isQuotedPairEscapee else {
return nil
}
isQuotedPair = false
} else if currentScalar == _Delimiters.DoubleQuote {
break
} else {
guard currentScalar.isQdtext else {
return nil
}
}
idx = self.index(after: idx)
}
// Expect stop on dquote
guard idx < endIndex, self[idx] == _Delimiters.DoubleQuote else {
return nil
}
return startIndex..<self.index(after: idx)
}
/// Returns dequoted string if receiver contains **quoted-string**
///
/// - returns: dequoted string or `nil` if receiver does not contain valid quoted string
func dequotedString() -> String? {
guard !isEmpty else {
return nil
}
var resultView = String.UnicodeScalarView()
resultView.reserveCapacity(self.count)
var idx = startIndex
// Expect and consume dquote
guard self[idx] == _Delimiters.DoubleQuote else {
return nil
}
idx = self.index(after: idx)
var isQuotedPair = false
while idx < endIndex {
let currentScalar = self[idx]
if currentScalar == _Delimiters.Backslash && !isQuotedPair {
isQuotedPair = true
} else if isQuotedPair {
guard currentScalar.isQuotedPairEscapee else {
return nil
}
isQuotedPair = false
resultView.append(currentScalar)
} else if currentScalar == _Delimiters.DoubleQuote {
break
} else {
guard currentScalar.isQdtext else {
return nil
}
resultView.append(currentScalar)
}
idx = self.index(after: idx)
}
// Expect stop on dquote
guard idx < endIndex, self[idx] == _Delimiters.DoubleQuote else {
return nil
}
return String(resultView)
}
}
private extension UnicodeScalar {
/// Is this a valid **token** as defined by RFC 2616 ?
///
/// - SeeAlso: https://tools.ietf.org/html/rfc2616#section-2
var isValidMessageToken: Bool {
guard UnicodeScalar(32) <= self && self <= UnicodeScalar(126) else { return false }
return !_Delimiters.Separators.characterIsMember(UInt16(self.value))
}
/// Is this a valid **qdtext** character
///
/// - SeeAlso: https://tools.ietf.org/html/rfc7230#section-3.2.6
var isQdtext: Bool {
// qdtext = HTAB / SP /%x21 / %x23-5B / %x5D-7E / obs-text
// obs-text = %x80-FF
let value = self.value
return self == _Delimiters.HorizontalTab
|| self == _Delimiters.Space
|| value == 0x21
|| 0x23 <= value && value <= 0x5B
|| 0x5D <= value && value <= 0x7E
|| 0x80 <= value && value <= 0xFF
}
/// Is this a valid second octet of **quoted-pair**
///
/// - SeeAlso: https://tools.ietf.org/html/rfc7230#section-3.2.6
/// - SeeAlso: https://tools.ietf.org/html/rfc5234#appendix-B.1
var isQuotedPairEscapee: Bool {
// quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
// obs-text = %x80-FF
let value = self.value
return self == _Delimiters.HorizontalTab
|| self == _Delimiters.Space
|| 0x21 <= value && value <= 0x7E
|| 0x80 <= value && value <= 0xFF
}
}
| apache-2.0 |
MillmanY/MMPlayerView | MMPlayerView/Classes/Subtitles/MMSubtitleSetting.swift | 1 | 2021 | //
// MMSubtitleSetting.swift
// MMPlayerView
//
// Created by Millman on 2019/12/18.
//
import UIKit
public protocol MMSubtitleSettingProtocol: class {
func setting(_ mmsubtitleSetting: MMSubtitleSetting, fontChange: UIFont)
func setting(_ mmsubtitleSetting: MMSubtitleSetting, textColorChange: UIColor)
func setting(_ mmsubtitleSetting: MMSubtitleSetting, labelEdgeChange: (bottom: CGFloat, left: CGFloat, right: CGFloat))
func setting(_ mmsubtitleSetting: MMSubtitleSetting, typeChange: MMSubtitleSetting.SubtitleType?)
}
extension MMSubtitleSetting {
public enum SubtitleType {
case srt(info: String)
}
}
public class MMSubtitleSetting: NSObject {
weak var delegate: MMSubtitleSettingProtocol?
public init(delegate: MMSubtitleSettingProtocol) {
self.delegate = delegate
}
var subtitleObj: AnyObject?
public var defaultFont: UIFont = UIFont.systemFont(ofSize: 17) {
didSet {
self.delegate?.setting(self, fontChange: defaultFont)
}
}
public var defaultTextColor: UIColor = UIColor.white {
didSet {
self.delegate?.setting(self, textColorChange: defaultTextColor)
}
}
public var defaultTextBackground: UIColor = UIColor.clear {
didSet {
}
}
public var defaultLabelEdge: (bottom: CGFloat, left: CGFloat, right: CGFloat) = (20,10,10) {
didSet {
self.delegate?.setting(self, labelEdgeChange: defaultLabelEdge)
}
}
public var subtitleType: SubtitleType? {
didSet {
guard let type = self.subtitleType else {
subtitleObj = nil
subtitleType = nil
return
}
switch type {
case .srt(let info):
let obj = SubtitleConverter(SRT())
obj.parseText(info)
subtitleObj = obj
}
self.delegate?.setting(self, typeChange: subtitleType)
}
}
}
| mit |
roambotics/swift | test/ConstExtraction/fields.swift | 2 | 3580 | // RUN: %empty-directory(%t)
// RUN: %empty-directory(%t/inputs)
// RUN: echo "[MyProto]" > %t/inputs/protocols.json
// RUN: %target-swift-frontend -typecheck -emit-const-values-path %t/fields.swiftconstvalues -const-gather-protocols-file %t/inputs/protocols.json -primary-file %s
// RUN: cat %t/fields.swiftconstvalues 2>&1 | %FileCheck %s
// CHECK: [
// CHECK-NEXT: {
// CHECK-NEXT: "typeName": "fields.Foo",
// CHECK-NEXT: "kind": "struct",
// CHECK-NEXT: "properties": [
// CHECK-NEXT: {
// CHECK-NEXT: "label": "p1",
// CHECK-NEXT: "type": "Swift.String",
// CHECK-NEXT: "isStatic": "false",
// CHECK-NEXT: "isComputed": "false",
// CHECK-NEXT: "value": "\"Hello, World\""
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "label": "p5",
// CHECK-NEXT: "type": "[Swift.Int]",
// CHECK-NEXT: "isStatic": "false",
// CHECK-NEXT: "isComputed": "false",
// CHECK-NEXT: "value": "[1, 2, 3, 4, 5, 6, 7, 8, 9]"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "label": "p6",
// CHECK-NEXT: "type": "Swift.Bool",
// CHECK-NEXT: "isStatic": "false",
// CHECK-NEXT: "isComputed": "false",
// CHECK-NEXT: "value": "false"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "label": "p7",
// CHECK-NEXT: "type": "Swift.Bool?",
// CHECK-NEXT: "isStatic": "false",
// CHECK-NEXT: "isComputed": "false",
// CHECK-NEXT: "value": "nil"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "label": "p8",
// CHECK-NEXT: "type": "(Swift.Int, Swift.Float)",
// CHECK-NEXT: "isStatic": "false",
// CHECK-NEXT: "isComputed": "false",
// CHECK-NEXT: "value": "(42, 6.6)"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "label": "p9",
// CHECK-NEXT: "type": "[Swift.String : Swift.Int]",
// CHECK-NEXT: "isStatic": "false",
// CHECK-NEXT: "isComputed": "false",
// CHECK-NEXT: "value": "[(\"One\", 1), (\"Two\", 2), (\"Three\", 3)]"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "label": "p0",
// CHECK-NEXT: "type": "Swift.Int",
// CHECK-NEXT: "isStatic": "true",
// CHECK-NEXT: "isComputed": "false",
// CHECK-NEXT: "value": "11"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "label": "p2",
// CHECK-NEXT: "type": "Swift.Float",
// CHECK-NEXT: "isStatic": "true",
// CHECK-NEXT: "isComputed": "false",
// CHECK-NEXT: "value": "42.2"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "label": "p3",
// CHECK-NEXT: "type": "Swift.Int",
// CHECK-NEXT: "isStatic": "false",
// CHECK-NEXT: "isComputed": "true",
// CHECK-NEXT: "value": "Unknown"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "label": "p4",
// CHECK-NEXT: "type": "Swift.Int",
// CHECK-NEXT: "isStatic": "true",
// CHECK-NEXT: "isComputed": "true",
// CHECK-NEXT: "value": "Unknown"
// CHECK-NEXT: }
// CHECK-NEXT: ]
// CHECK-NEXT: }
// CHECK-NEXT:]
protocol MyProto {}
public struct Foo {
static _const let p0: Int = 11
let p1: String = "Hello, World"
static let p2: Float = 42.2
var p3: Int {3}
static var p4: Int {3}
let p5: [Int] = [1,2,3,4,5,6,7,8,9]
let p6: Bool = false
let p7: Bool? = nil
let p8: (Int, Float) = (42, 6.6)
let p9: [String: Int] = ["One": 1, "Two": 2, "Three": 3]
}
extension Foo : MyProto {}
| apache-2.0 |
TrustWallet/trust-wallet-ios | Trust/Transfer/Types/GasLimitConfiguration.swift | 1 | 336 | // Copyright DApps Platform Inc. All rights reserved.
import Foundation
import BigInt
public struct GasLimitConfiguration {
static let `default` = BigInt(90_000)
static let min = BigInt(21_000)
static let max = BigInt(600_000)
static let tokenTransfer = BigInt(144_000)
static let dappTransfer = BigInt(600_000)
}
| gpl-3.0 |
roambotics/swift | test/SourceKit/Diagnostics/diags.swift | 2 | 1718 | // Use -print-raw-response on the first request so we don't wait for semantic info which will never come.
// RUN: %sourcekitd-test -req=open %s -req-opts=syntactic_only=1 -print-raw-response -- %s == \
// RUN: -req=stats == \
// RUN: -req=diags %s -print-raw-response -- %s == \
// RUN: -req=stats == \
// RUN: -req=diags %s -print-raw-response -- %s == \
// RUN: -req=stats | %FileCheck %s
func foo(y: String) {
foo(y: 1)
}
// We shouldn't build an AST for the syntactic open
// CHECK: 0 {{.*}} source.statistic.num-ast-builds
// Retrieving diagnostics should work
// CHECK: {
// CHECK: key.diagnostics: [
// CHECK: {
// CHECK: key.line: 10,
// CHECK: key.column: 10,
// CHECK: key.filepath: "{{.*}}",
// CHECK: key.severity: source.diagnostic.severity.error,
// CHECK: key.id: "cannot_convert_argument_value",
// CHECK: key.description: "cannot convert value of type 'Int' to expected argument type 'String'"
// CHECK: }
// CHECK: ]
// CHECK: }
// ... and we should have built an AST for it
// CHECK: 1 {{.*}} source.statistic.num-ast-builds
// Retrieving diagnostics again should work
// CHECK: {
// CHECK: key.diagnostics: [
// CHECK: {
// CHECK: key.line: 10,
// CHECK: key.column: 10,
// CHECK: key.filepath: "{{.*}}",
// CHECK: key.severity: source.diagnostic.severity.error,
// CHECK: key.id: "cannot_convert_argument_value",
// CHECK: key.description: "cannot convert value of type 'Int' to expected argument type 'String'"
// CHECK: }
// CHECK: ]
// CHECK: }
// ... but we shouldn't rebuild an AST
// CHECK: 1 {{.*}} source.statistic.num-ast-builds
// CHECK: 1 {{.*}} source.statistic.num-ast-cache-hits
| apache-2.0 |
cohena100/Shimi | Carthage/Checkouts/Action/Tests/ActionTests/AlertActionTests.swift | 1 | 2551 | import Quick
import Nimble
import RxSwift
import RxBlocking
import Action
class AlertActionTests: QuickSpec {
override func spec() {
it("is nil by default") {
let subject = UIAlertAction.Action("Hi", style: .default)
expect(subject.rx.action).to( beNil() )
}
it("respects setter") {
var subject = UIAlertAction.Action("Hi", style: .default)
let action = emptyAction()
subject.rx.action = action
expect(subject.rx.action) === action
}
it("disables the alert action while executing") {
var subject = UIAlertAction.Action("Hi", style: .default)
var observer: AnyObserver<Void>!
let action = CocoaAction(workFactory: { _ in
return Observable.create { (obsv) -> Disposable in
observer = obsv
return Disposables.create()
}
})
subject.rx.action = action
action.execute()
expect(subject.isEnabled).toEventually( beFalse() )
observer.onCompleted()
expect(subject.isEnabled).toEventually( beTrue() )
}
it("disables the alert action if the Action is disabled") {
var subject = UIAlertAction.Action("Hi", style: .default)
let disposeBag = DisposeBag()
subject.rx.action = emptyAction(.just(false))
waitUntil { done in
subject.rx.observe(Bool.self, "enabled")
.take(1)
.subscribe(onNext: { _ in
done()
})
.disposed(by: disposeBag)
}
expect(subject.isEnabled) == false
}
it("disposes of old action subscriptions when re-set") {
var subject = UIAlertAction.Action("Hi", style: .default)
var disposed = false
autoreleasepool {
let disposeBag = DisposeBag()
let action = emptyAction()
subject.rx.action = action
action
.elements
.subscribe(onNext: nil, onError: nil, onCompleted: nil, onDisposed: {
disposed = true
})
.disposed(by: disposeBag)
}
subject.rx.action = nil
expect(disposed) == true
}
}
}
| mit |
roambotics/swift | test/attr/attr_availability_transitive_osx.swift | 2 | 6644 | // RUN: %target-typecheck-verify-swift -parse-as-library
// REQUIRES: OS=macosx
// Allow referencing unavailable API in situations where the caller is marked unavailable in the same circumstances.
@available(OSX, unavailable)
@discardableResult
func osx() -> Int { return 0 } // expected-note * {{'osx()' has been explicitly marked unavailable here}}
@available(OSXApplicationExtension, unavailable)
func osx_extension() {}
@available(OSX, unavailable)
func osx_pair() -> (Int, Int) { return (0, 0) } // expected-note * {{'osx_pair()' has been explicitly marked unavailable here}}
func call_osx_extension() {
osx_extension() // OK; osx_extension is only unavailable if -application-extension is passed.
}
func call_osx() {
osx() // expected-error {{'osx()' is unavailable}}
}
@available(OSX, unavailable)
func osx_call_osx_extension() {
osx_extension() // OK; osx_extension is only unavailable if -application-extension is passed.
}
@available(OSX, unavailable)
func osx_call_osx() {
osx() // OK; same
}
@available(OSXApplicationExtension, unavailable)
func osx_extension_call_osx_extension() {
osx_extension()
}
@available(OSXApplicationExtension, unavailable)
func osx_extension_call_osx() {
osx() // expected-error {{'osx()' is unavailable}}
}
@available(OSX, unavailable)
var osx_init_osx = osx() // OK
@available(OSXApplicationExtension, unavailable)
var osx_extension_init_osx = osx() // expected-error {{'osx()' is unavailable}}
@available(OSX, unavailable)
var osx_inner_init_osx = { let inner_var = osx() } // OK
@available(OSXApplicationExtension, unavailable)
var osx_extension_inner_init_osx = { let inner_var = osx() } // expected-error {{'osx()' is unavailable}}
struct Outer {
@available(OSX, unavailable)
var osx_init_osx = osx() // OK
@available(OSX, unavailable)
lazy var osx_lazy_osx = osx() // OK
@available(OSXApplicationExtension, unavailable)
var osx_extension_init_osx = osx() // expected-error {{'osx()' is unavailable}}
@available(OSXApplicationExtension, unavailable)
var osx_extension_lazy_osx = osx() // expected-error {{'osx()' is unavailable}}
@available(OSX, unavailable)
var osx_init_multi1_osx = osx(), osx_init_multi2_osx = osx() // OK
@available(OSXApplicationExtension, unavailable)
var osx_extension_init_multi1_osx = osx(), osx_extension_init_multi2_osx = osx() // expected-error 2 {{'osx()' is unavailable}}
@available(OSX, unavailable)
var (osx_init_deconstruct1_osx, osx_init_deconstruct2_osx) = osx_pair() // OK
@available(OSXApplicationExtension, unavailable)
var (osx_extension_init_deconstruct1_osx, osx_extension_init_deconstruct2_osx) = osx_pair() // expected-error {{'osx_pair()' is unavailable}}
@available(OSX, unavailable)
var (_, osx_init_deconstruct2_only_osx) = osx_pair() // OK
@available(OSXApplicationExtension, unavailable)
var (_, osx_extension_init_deconstruct2_only_osx) = osx_pair() // expected-error {{'osx_pair()' is unavailable}}
@available(OSX, unavailable)
var (osx_init_deconstruct1_only_osx, _) = osx_pair() // OK
@available(OSXApplicationExtension, unavailable)
var (osx_extension_init_deconstruct1_only_osx, _) = osx_pair() // expected-error {{'osx_pair()' is unavailable}}
@available(OSX, unavailable)
var osx_inner_init_osx = { let inner_var = osx() } // OK
@available(OSXApplicationExtension, unavailable)
var osx_extension_inner_init_osx = { let inner_var = osx() } // expected-error {{'osx()' is unavailable}}
}
extension Outer {
@available(OSX, unavailable)
static var also_osx_init_osx = osx() // OK
@available(OSXApplicationExtension, unavailable)
static var also_osx_extension_init_osx = osx() // expected-error {{'osx()' is unavailable}}
}
@available(OSX, unavailable)
// expected-note@+1 {{enclosing scope has been explicitly marked unavailable here}}
extension Outer {
// expected-note@+1 {{'outer_osx_init_osx' has been explicitly marked unavailable here}}
static var outer_osx_init_osx = osx() // OK
// expected-note@+1 {{'osx_call_osx()' has been explicitly marked unavailable here}}
func osx_call_osx() {
osx() // OK
}
func osx_call_osx_extension() {
osx_extension() // OK; osx_extension is only unavailable if -application-extension is passed.
}
func takes_and_returns_osx(_ x: NotOnOSX) -> NotOnOSX {
return x // OK
}
// This @available should be ignored; inherited unavailability takes precedence
@available(OSX 999, *) // expected-warning {{instance method cannot be more available than unavailable enclosing scope}}
// expected-note@+1 {{'osx_more_available_but_still_unavailable_call_osx()' has been explicitly marked unavailable here}}
func osx_more_available_but_still_unavailable_call_osx() {
osx() // OK
}
// rdar://92551870
func osx_call_osx_more_available_but_still_unavailable() {
osx_more_available_but_still_unavailable_call_osx() // OK
}
}
func takesOuter(_ o: Outer) {
_ = Outer.outer_osx_init_osx // expected-error {{'outer_osx_init_osx' is unavailable in macOS}}
o.osx_call_osx() // expected-error {{'osx_call_osx()' is unavailable in macOS}}
o.osx_more_available_but_still_unavailable_call_osx() // expected-error {{'osx_more_available_but_still_unavailable_call_osx()' is unavailable in macOS}}
}
@available(OSX, unavailable)
struct NotOnOSX { // expected-note {{'NotOnOSX' has been explicitly marked unavailable here}}
var osx_init_osx = osx() // OK
lazy var osx_lazy_osx = osx() // OK
var osx_init_multi1_osx = osx(), osx_init_multi2_osx = osx() // OK
var (osx_init_deconstruct1_osx, osx_init_deconstruct2_osx) = osx_pair() // OK
var (_, osx_init_deconstruct2_only_osx) = osx_pair() // OK
var (osx_init_deconstruct1_only_osx, _) = osx_pair() // OK
}
@available(OSX, unavailable)
extension NotOnOSX {
func osx_call_osx() {
osx() // OK
}
func osx_call_osx_extension() {
osx_extension() // OK; osx_extension is only unavailable if -application-extension is passed.
}
}
@available(OSXApplicationExtension, unavailable)
extension NotOnOSX { } // expected-error {{'NotOnOSX' is unavailable in macOS}}
@available(OSXApplicationExtension, unavailable)
struct NotOnOSXApplicationExtension { }
@available(OSX, unavailable)
extension NotOnOSXApplicationExtension { } // OK; NotOnOSXApplicationExtension is only unavailable if -application-extension is passed.
@available(OSXApplicationExtension, unavailable)
extension NotOnOSXApplicationExtension {
func osx_call_osx() {
osx() // expected-error {{'osx()' is unavailable in macOS}}
}
func osx_call_osx_extension() {
osx_extension() // OK
}
}
| apache-2.0 |
li-wenxue/Weibo | 新浪微博/新浪微博/Class/Tools/Networking/WBNetworkingManager+Extension.swift | 1 | 3850 | //
// WBNetworkingManager+Extension.swift
// 新浪微博
//
// Created by win_学 on 16/8/20.
// Copyright © 2016年 win_学. All rights reserved.
//
import Foundation
// MARK: - 封装新浪微博的网络请求方法
extension WBNetworkingManager {
/// 加载微博数据字典数组
///
/// - parameter since_id 返回ID比since_id大的微博(即比since_id时间晚的微博),默认为0(下拉)
/// - parameter max_id 返回ID小于或等于max_id的微博,默认为0 (上拉)
/// - parameter completion 完成回调
func statusList(since_id: Int64 = 0, max_id: Int64 = 0, completion:(list: [[String: AnyObject]]?, isSuccess: Bool) -> ()) {
let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
// swift中 Int 可以转换成 AnyObject ,但是 Int64 不行
let parameters = ["since_id": "\(since_id)", "max_id": "\(max_id > 0 ? max_id - 1 : 0)"]
tokenRequest(urlString: urlString, parameters: parameters) { (json: AnyObject?, isSuccess: Bool) -> () in
// 从json 中获取 statuses 字典数组
// 如果 as? 失败,返回为nil
let result = json?["statuses"] as? [[String: AnyObject]]
completion(list: result, isSuccess: isSuccess)
}
}
func unreadStatus(completion:(count: Int)->()) {
guard let uid = userAccount.uid else {
return
}
// 1. url
let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
// 2. 参数
let parameters = ["uid":uid]
tokenRequest(urlString: urlString, parameters: parameters) { (json: AnyObject?, isSuccess: Bool) -> () in
completion(count: (json as? [String:AnyObject])?["status"] as? Int ?? 0)
}
}
}
// MARK: - 用户信息相关
extension WBNetworkingManager {
// 加载当前用户信息,一旦登录成功应立即调用
func loadUserInfo(completion:(dict:[String: AnyObject])->()) {
let urlString = "https://api.weibo.com/2/users/show.json"
guard let uid = userAccount.uid else {
return
}
let parameters = ["uid": uid]
tokenRequest(urlString: urlString, parameters: parameters) { (json, isSuccess) in
// 完成回调
completion(dict: (json as? [String: AnyObject]) ?? [:])
}
}
}
// MARK: - OAuth相关方法
extension WBNetworkingManager {
func loadOAuthToken(code: String, completion:(isSuccess: Bool)->()) {
let urlString = "https://api.weibo.com/oauth2/access_token"
let parameters = ["client_id": WBAppKey,
"client_secret": WBAppSecret,
"grant_type":"authorization_code",
"code": code,
"redirect_uri": WBRedirectURL]
request(method: .POST, urlString: urlString, parameters: parameters) {
(json, isSuccess) in
// 此时的json 已经是序列化后的 ‘泛型’ 了
// 字典转模型
self.userAccount.yy_modelSet(with: json as? [String: AnyObject] ?? [:])
self.loadUserInfo(completion: { (dict) in
// 使用用户字典给用户模型赋值
self.userAccount.yy_modelSet(with: dict)
print(self.userAccount)
// 磁盘存储用户信息
self.userAccount.saveAccount()
// 注意loadUserInfo中输出与下面的completion执行顺序的问题
completion(isSuccess: isSuccess)
})
}
}
}
| mit |
jvesala/teknappi | teknappi/Pods/RxCocoa/RxCocoa/iOS/UITableView+Rx.swift | 13 | 7261 | //
// UITableView+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 4/2/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
import UIKit
// Items
extension UITableView {
/**
Binds sequences of elements to table view rows.
- parameter source: Observable sequence of items.
- parameter cellFactory: Transform between sequence elements and view cells.
- returns: Disposable object that can be used to unbind.
*/
public func rx_itemsWithCellFactory<S: SequenceType, O: ObservableType where O.E == S>
(source: O)
(cellFactory: (UITableView, Int, S.Generator.Element) -> UITableViewCell)
-> Disposable {
let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper<S>(cellFactory: cellFactory)
return self.rx_itemsWithDataSource(dataSource)(source: source)
}
/**
Binds sequences of elements to table view rows.
- parameter cellIdentifier: Identifier used to dequeue cells.
- parameter source: Observable sequence of items.
- parameter configureCell: Transform between sequence elements and view cells.
- returns: Disposable object that can be used to unbind.
*/
public func rx_itemsWithCellIdentifier<S: SequenceType, Cell: UITableViewCell, O : ObservableType where O.E == S>
(cellIdentifier: String)
(source: O)
(configureCell: (Int, S.Generator.Element, Cell) -> Void)
-> Disposable {
let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper<S> { (tv, i, item) in
let indexPath = NSIndexPath(forItem: i, inSection: 0)
let cell = tv.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! Cell
configureCell(i, item, cell)
return cell
}
return self.rx_itemsWithDataSource(dataSource)(source: source)
}
/**
Binds sequences of elements to table view rows using a custom reactive data used to perform the transformation.
- parameter dataSource: Data source used to transform elements to view cells.
- parameter source: Observable sequence of items.
- returns: Disposable object that can be used to unbind.
*/
public func rx_itemsWithDataSource<DataSource: protocol<RxTableViewDataSourceType, UITableViewDataSource>, S: SequenceType, O: ObservableType where DataSource.Element == S, O.E == S>
(dataSource: DataSource)
(source: O)
-> Disposable {
return source.subscribeProxyDataSourceForObject(self, dataSource: dataSource, retainDataSource: false) { [weak self] (_: RxTableViewDataSourceProxy, event) -> Void in
guard let tableView = self else {
return
}
dataSource.tableView(tableView, observedEvent: event)
}
}
}
extension UITableView {
/**
Factory method that enables subclasses to implement their own `rx_delegate`.
- returns: Instance of delegate proxy that wraps `delegate`.
*/
override func rx_createDelegateProxy() -> RxScrollViewDelegateProxy {
return RxTableViewDelegateProxy(parentObject: self)
}
/**
Reactive wrapper for `dataSource`.
For more information take a look at `DelegateProxyType` protocol documentation.
*/
public var rx_dataSource: DelegateProxy {
return proxyForObject(self) as RxTableViewDataSourceProxy
}
/**
Installs data source as forwarding delegate on `rx_dataSource`.
It enables using normal delegate mechanism with reactive delegate mechanism.
- parameter dataSource: Data source object.
- returns: Disposable object that can be used to unbind the data source.
*/
public func rx_setDataSource(dataSource: UITableViewDataSource)
-> Disposable {
let proxy: RxTableViewDataSourceProxy = proxyForObject(self)
return installDelegate(proxy, delegate: dataSource, retainDelegate: false, onProxyForObject: self)
}
// events
/**
Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`.
*/
public var rx_itemSelected: ControlEvent<NSIndexPath> {
let source = rx_delegate.observe("tableView:didSelectRowAtIndexPath:")
.map { a in
return a[1] as! NSIndexPath
}
return ControlEvent(source: source)
}
/**
Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`.
*/
public var rx_itemInserted: ControlEvent<NSIndexPath> {
let source = rx_dataSource.observe("tableView:commitEditingStyle:forRowAtIndexPath:")
.filter { a in
return UITableViewCellEditingStyle(rawValue: (a[1] as! NSNumber).integerValue) == .Insert
}
.map { a in
return (a[2] as! NSIndexPath)
}
return ControlEvent(source: source)
}
/**
Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`.
*/
public var rx_itemDeleted: ControlEvent<NSIndexPath> {
let source = rx_dataSource.observe("tableView:commitEditingStyle:forRowAtIndexPath:")
.filter { a in
return UITableViewCellEditingStyle(rawValue: (a[1] as! NSNumber).integerValue) == .Delete
}
.map { a in
return (a[2] as! NSIndexPath)
}
return ControlEvent(source: source)
}
/**
Reactive wrapper for `delegate` message `tableView:moveRowAtIndexPath:toIndexPath:`.
*/
public var rx_itemMoved: ControlEvent<ItemMovedEvent> {
let source: Observable<ItemMovedEvent> = rx_dataSource.observe("tableView:moveRowAtIndexPath:toIndexPath:")
.map { a in
return ((a[1] as! NSIndexPath), (a[2] as! NSIndexPath))
}
return ControlEvent(source: source)
}
/**
Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`.
It can be only used when one of the `rx_itemsWith*` methods is used to bind observable sequence.
If custom data source is being bound, new `rx_modelSelected` wrapper needs to be written also.
public func rx_myModelSelected<T>() -> ControlEvent<T> {
let source: Observable<T> = rx_itemSelected.map { indexPath in
let dataSource: MyDataSource = self.rx_dataSource.forwardToDelegate() as! MyDataSource
return dataSource.modelAtIndex(indexPath.item)!
}
return ControlEvent(source: source)
}
*/
public func rx_modelSelected<T>() -> ControlEvent<T> {
let source: Observable<T> = rx_itemSelected.map { ip in
let dataSource: RxTableViewReactiveArrayDataSource<T> = castOrFatalError(self.rx_dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx_subscribeItemsTo` methods was used.")
return dataSource.modelAtIndex(ip.item)!
}
return ControlEvent(source: source)
}
} | gpl-3.0 |
matt-deboer/kuill | vendor/github.com/googleapis/gnostic/plugins/gnostic-swift-generator/Sources/gnostic-swift-generator/Renderer.swift | 25 | 12439 | // Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import Gnostic
extension String {
func capitalizingFirstLetter() -> String {
let first = String(characters.prefix(1)).capitalized
let other = String(characters.dropFirst())
return first + other
}
mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}
}
class ServiceType {
var name : String = ""
var fields : [ServiceTypeField] = []
var isInterfaceType : Bool = false
}
class ServiceTypeField {
var name : String = ""
var typeName : String = ""
var isArrayType : Bool = false
var isCastableType : Bool = false
var isConvertibleType : Bool = false
var elementType : String = ""
var jsonName : String = ""
var position: String = "" // "body", "header", "formdata", "query", or "path"
var initialValue : String = ""
func setTypeForName(_ name : String, _ format : String) {
switch name {
case "integer":
if format == "int32" {
self.typeName = "Int32"
} else if format == "int64" {
self.typeName = "Int64"
} else {
self.typeName = "Int"
}
self.initialValue = "0"
self.isCastableType = true
default:
self.typeName = name.capitalizingFirstLetter()
self.initialValue = self.typeName + "()"
self.isConvertibleType = true
}
}
func setTypeForSchema(_ schema : Openapi_V2_Schema, optional : Bool = false) {
let ref = schema.ref
if ref != "" {
self.typeName = typeForRef(ref)
self.isConvertibleType = true
self.initialValue = self.typeName + "()"
}
if schema.hasType {
let types = schema.type.value
let format = schema.format
if types.count == 1 && types[0] == "string" {
self.typeName = "String"
self.isCastableType = true
self.initialValue = "\"\""
}
if types.count == 1 && types[0] == "integer" && format == "int32" {
self.typeName = "Int32"
self.isCastableType = true
self.initialValue = "0"
}
if types.count == 1 && types[0] == "array" && schema.hasItems {
// we have an array.., but of what?
let items = schema.items.schema
if items.count == 1 && items[0].ref != "" {
self.isArrayType = true
self.elementType = typeForRef(items[0].ref)
self.typeName = "[" + self.elementType + "]"
self.initialValue = "[]"
}
}
}
// this function is incomplete... so return a string representing anything that we don't handle
if self.typeName == "" {
self.typeName = "\(schema)"
}
if optional {
self.typeName += "?"
self.initialValue = "nil"
}
}
}
class ServiceMethod {
var name : String = ""
var path : String = ""
var method : String = ""
var description : String = ""
var handlerName : String = ""
var processorName : String = ""
var clientName : String = ""
var resultTypeName : String?
var parametersTypeName : String?
var responsesTypeName : String?
var parametersType : ServiceType?
var responsesType : ServiceType?
}
func propertyNameForResponseCode(_ code:String) -> String {
switch code {
case "200":
return "ok"
case "default":
return "error"
default:
return code
}
}
func typeForRef(_ ref : String) -> String {
let parts = ref.components(separatedBy:"/")
return parts.last!.capitalizingFirstLetter()
}
class ServiceRenderer {
internal var name : String = ""
internal var package: String = ""
internal var types : [ServiceType] = []
internal var methods : [ServiceMethod] = []
internal var surface : Surface_V1_Model
public init(surface : Surface_V1_Model, document : Openapi_V2_Document) {
self.surface = surface
loadService(document:document)
}
private func loadServiceTypeFromParameters(_ name:String,
_ parameters:[Openapi_V2_ParametersItem])
-> ServiceType? {
let t = ServiceType()
t.name = name.capitalizingFirstLetter() + "Parameters"
for parametersItem in parameters {
let f = ServiceTypeField()
f.typeName = "\(parametersItem)"
switch parametersItem.oneof! {
case .parameter(let parameter):
switch parameter.oneof! {
case .bodyParameter(let bodyParameter):
f.name = bodyParameter.name
if bodyParameter.hasSchema {
f.setTypeForSchema(bodyParameter.schema)
f.position = "body"
}
case .nonBodyParameter(let nonBodyParameter):
switch (nonBodyParameter.oneof!) {
case .headerParameterSubSchema(let headerParameter):
f.name = headerParameter.name
f.position = "header"
case .formDataParameterSubSchema(let formDataParameter):
f.name = formDataParameter.name
f.position = "formdata"
case .queryParameterSubSchema(let queryParameter):
f.name = queryParameter.name
f.position = "query"
case .pathParameterSubSchema(let pathParameter):
f.name = pathParameter.name
f.jsonName = pathParameter.name
f.position = "path"
f.setTypeForName(pathParameter.type, pathParameter.format)
}
}
case .jsonReference: // (let reference):
Log("?")
}
t.fields.append(f)
}
if t.fields.count > 0 {
self.types.append(t)
return t
} else {
return nil
}
}
private func loadServiceTypeFromResponses(_ m:ServiceMethod,
_ name:String,
_ responses:Openapi_V2_Responses)
-> ServiceType? {
let t = ServiceType()
t.name = name.capitalizingFirstLetter() + "Responses"
for responseCode in responses.responseCode {
let f = ServiceTypeField()
f.name = propertyNameForResponseCode(responseCode.name)
f.jsonName = ""
if let responseCodeValueOneOf = responseCode.value.oneof {
switch responseCodeValueOneOf {
case .response(let response):
let schema = response.schema
if let schemaOneOf = schema.oneof {
switch schemaOneOf {
case .schema(let schema):
f.setTypeForSchema(schema, optional:true)
t.fields.append(f)
if f.name == "ok" {
m.resultTypeName = f.typeName.replacingOccurrences(of:"?", with:"")
}
default:
break
}
}
default:
break
}
}
}
if t.fields.count > 0 {
self.types.append(t)
return t
} else {
return nil
}
}
private func loadOperation(_ operation : Openapi_V2_Operation,
method : String,
path : String) {
let m = ServiceMethod()
m.name = operation.operationID
m.path = path
m.method = method
m.description = operation.description_p
m.handlerName = "handle" + m.name
m.processorName = "" + m.name
m.clientName = m.name
m.parametersType = loadServiceTypeFromParameters(m.name, operation.parameters)
if m.parametersType != nil {
m.parametersTypeName = m.parametersType!.name
}
m.responsesType = loadServiceTypeFromResponses(m, m.name, operation.responses)
if m.responsesType != nil {
m.responsesTypeName = m.responsesType!.name
}
self.methods.append(m)
}
private func loadService(document : Openapi_V2_Document) {
// collect service type descriptions
for pair in document.definitions.additionalProperties {
let t = ServiceType()
t.isInterfaceType = true
let schema = pair.value
for pair2 in schema.properties.additionalProperties {
let f = ServiceTypeField()
f.name = pair2.name
f.setTypeForSchema(pair2.value)
f.jsonName = pair2.name
t.fields.append(f)
}
t.name = pair.name.capitalizingFirstLetter()
self.types.append(t)
}
// collect service method descriptions
for pair in document.paths.path {
let v = pair.value
if v.hasGet {
loadOperation(v.get, method:"GET", path:pair.name)
}
if v.hasPost {
loadOperation(v.post, method:"POST", path:pair.name)
}
if v.hasPut {
loadOperation(v.put, method:"PUT", path:pair.name)
}
if v.hasDelete {
loadOperation(v.delete, method:"DELETE", path:pair.name)
}
}
}
public func generate(filenames : [String], response : inout Gnostic_Plugin_V1_Response) throws {
for filename in filenames {
var data : Data?
switch filename {
case "types.swift":
data = renderTypes().data(using:.utf8)
case "server.swift":
data = renderServer().data(using:.utf8)
case "client.swift":
data = renderClient().data(using:.utf8)
case "fetch.swift":
data = renderFetch().data(using:.utf8)
default:
print("error: unable to render \(filename)")
}
if let data = data {
var clientfile = Gnostic_Plugin_V1_File()
clientfile.name = filename
clientfile.data = data
response.files.append(clientfile)
}
}
}
}
let header = """
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
"""
| mit |
telip007/ChatFire | Pods/SwiftMessages/SwiftMessages/UIViewController+Utils.swift | 2 | 4460 | //
// UIViewController+Utils.swift
// SwiftMessages
//
// Created by Timothy Moose on 8/5/16.
// Copyright © 2016 SwiftKick Mobile LLC. All rights reserved.
//
import UIKit
private let fullScreenStyles: [UIModalPresentationStyle] = [.FullScreen, .OverFullScreen]
extension UIViewController {
func sm_selectPresentationContextTopDown(presentationStyle: SwiftMessages.PresentationStyle) -> UIViewController {
if let presented = sm_presentedFullScreenViewController() {
return presented.sm_selectPresentationContextTopDown(presentationStyle)
} else if case .Top = presentationStyle, let navigationController = sm_selectNavigationControllerTopDown() {
return navigationController
} else if case .Bottom = presentationStyle, let tabBarController = sm_selectTabBarControllerTopDown() {
return tabBarController
}
return WindowViewController(windowLevel: self.view.window?.windowLevel ?? UIWindowLevelNormal)
}
private func sm_selectNavigationControllerTopDown() -> UINavigationController? {
if let presented = sm_presentedFullScreenViewController() {
return presented.sm_selectNavigationControllerTopDown()
} else if let navigationController = self as? UINavigationController {
if navigationController.sm_isVisible(view: navigationController.navigationBar) {
return navigationController
}
return navigationController.topViewController?.sm_selectNavigationControllerTopDown()
} else if let tabBarController = self as? UITabBarController {
return tabBarController.selectedViewController?.sm_selectNavigationControllerTopDown()
}
return nil
}
private func sm_selectTabBarControllerTopDown() -> UITabBarController? {
if let presented = sm_presentedFullScreenViewController() {
return presented.sm_selectTabBarControllerTopDown()
} else if let navigationController = self as? UINavigationController {
return navigationController.topViewController?.sm_selectTabBarControllerTopDown()
} else if let tabBarController = self as? UITabBarController {
if tabBarController.sm_isVisible(view: tabBarController.tabBar) {
return tabBarController
}
return tabBarController.selectedViewController?.sm_selectTabBarControllerTopDown()
}
return nil
}
private func sm_presentedFullScreenViewController() -> UIViewController? {
if let presented = self.presentedViewController where fullScreenStyles.contains(presented.modalPresentationStyle) {
return presented
}
return nil
}
func sm_selectPresentationContextBottomUp(presentationStyle: SwiftMessages.PresentationStyle) -> UIViewController {
if let parent = parentViewController {
if let navigationController = parent as? UINavigationController {
if case .Top = presentationStyle where navigationController.sm_isVisible(view: navigationController.navigationBar) {
return navigationController
}
return navigationController.sm_selectPresentationContextBottomUp(presentationStyle)
} else if let tabBarController = parent as? UITabBarController {
if case .Bottom = presentationStyle where tabBarController.sm_isVisible(view: tabBarController.tabBar) {
return tabBarController
}
return tabBarController.sm_selectPresentationContextBottomUp(presentationStyle)
}
}
if self.view is UITableView {
// Never select scroll view as presentation context
// because, you know, it scrolls.
if let parent = self.parentViewController {
return parent.sm_selectPresentationContextBottomUp(presentationStyle)
} else {
return WindowViewController(windowLevel: self.view.window?.windowLevel ?? UIWindowLevelNormal)
}
}
return self
}
func sm_isVisible(view view: UIView) -> Bool {
if view.hidden { return false }
if view.alpha == 0.0 { return false }
let frame = self.view.convertRect(view.bounds, fromView: view)
if !CGRectIntersectsRect(self.view.bounds, frame) { return false }
return true
}
}
| apache-2.0 |
Off-Piste/Trolley.io-cocoa | Trolley/Database/TRLDatabaseCore/Extensions/Array+Core.swift | 2 | 843 | //
// Response+Core.swift
// Trolley.io
//
// Created by Harry Wright on 26.06.17.
// Copyright © 2017 Trolley. All rights reserved.
//
import Foundation
import PromiseKit
public extension Array where Element == Product {
/// <#Description#>
///
/// - Parameter text: <#text description#>
/// - Returns: <#return value description#>
func filter(for text: String) -> [Element] {
return self.filter { $0.name.contains(text) || $0.company.contains(text)}
}
}
public extension Array where Element == SearchableProducts {
/// <#Description#>
///
/// - Parameter text: <#text description#>
/// - Returns: <#return value description#>
func filter(for text: String) -> [Element] {
return self.filter { $0.productName.contains(text) || $0.companyName.contains(text) }
}
}
| mit |
andrzejsemeniuk/ASToolkit | ASToolkit/ExtensionForSwift.swift | 1 | 365 | //
// ExtensionForSwiftNumeric.swift
// ASToolkit
//
// Created by andrzej semeniuk on 10/9/16.
// Copyright © 2017 Andrzej Semeniuk. All rights reserved.
//
import Foundation
extension Comparable {
public func clamped (minimum:Self, maximum:Self) -> Self {
return self < minimum ? minimum : maximum < self ? maximum : self
}
}
| mit |
kingslay/KSSwiftExtension | CityPicker/View/CityMaskView.swift | 5 | 624 | //
// CityMaskView.swift
// CFCityPickerVC
//
// Created by 冯成林 on 15/8/6.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import UIKit
class CityMaskView: UIView {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
/** 视图准备 */
self.viewPrepare()
}
override init(frame: CGRect) {
super.init(frame: frame)
/** 视图准备 */
self.viewPrepare()
}
/** 视图准备 */
func viewPrepare(){
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
}
}
| mit |
Andruschenko/SeatTreat | SeatTreatTests/BackendAPITests.swift | 1 | 1757 | //
// BackendAPITests.swift
// SeatTreat
//
// Created by Jan Erik Herrmann on 18.10.15.
// Copyright © 2015 André Kovac. All rights reserved.
//
import XCTest
@testable import SeatTreat
class BackendAPITest: XCTestCase {
func testLoadAvailableSeats() {
let expectation = expectationWithDescription("Swift Expectations")
BackendAPI.loadAvailableSeats { seatList in
print("finished")
seatList[0].printSeat()
XCTAssert(true)
expectation.fulfill()
}
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
waitForExpectationsWithTimeout(5.0, handler:nil)
}
func testgetSeat() {
let expectation = expectationWithDescription("Swift Expectations")
BackendAPI.getSeat("1A") { seat in
seat.printSeat()
XCTAssert(true)
expectation.fulfill()
}
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
waitForExpectationsWithTimeout(5.0, handler:nil)
}
/*
func testbidSeat() {
let expectation = expectationWithDescription("Swift Expectations")
BackendAPI.bidSeat("1A", bid: 1000, user: "hannes") { seat in
seat.printSeat()
XCTAssert(true)
expectation.fulfill()
}
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
waitForExpectationsWithTimeout(5.0, handler:nil)
}
*/
} | gpl-2.0 |
FabrizioBrancati/BFKit-Swift | Sources/BFKit/Linux/BFKit/BFApp.swift | 1 | 6920 | //
// BFApp.swift
// BFKit-Swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 - 2019 Fabrizio Brancati.
//
// 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: - Global variables
/// NSLocalizedString without comment parameter.
///
/// - Parameter key: The key of the localized string.
/// - Returns: Returns a localized string.
public func NSLocalizedString(_ key: String) -> String {
NSLocalizedString(key, comment: "")
}
// MARK: - BFApp struct
/// This class adds some useful functions for the App.
public enum BFApp {
// MARK: - Variables
/// Used to store the BFHasBeenOpened in defaults.
internal static let BFAppHasBeenOpened = "BFAppHasBeenOpened"
/// Use this var to set you DEBUG or not builds.
/// More info on how to use it [here](http://stackoverflow.com/questions/26890537/disabling-nslog-for-production-in-swift-project/26891797#26891797).
public static var isDebug = false
// MARK: - Functions
/// Executes a block only if in DEBUG mode.
///
/// - Parameter block: The block to be executed.
public static func debug(_ block: () -> Void) {
if isDebug {
block()
}
}
/// Executes a block only if NOT in DEBUG mode.
///
/// - Parameter block: The block to be executed.
public static func release(_ block: () -> Void) {
if !isDebug {
block()
}
}
/// If version is set returns if is first start for that version,
/// otherwise returns if is first start of the App.
///
/// - Parameter version: Version to be checked, you can use the variable `BFApp.version` to pass the current App version.
/// - Returns: Returns if is first start of the App or for custom version.
public static func isFirstStart(version: String = "") -> Bool {
let key: String = BFAppHasBeenOpened + version
let defaults = UserDefaults.standard
let hasBeenOpened: Bool = defaults.bool(forKey: key)
return !hasBeenOpened
}
/// Executes a block on first start of the App, if version is set it will be for given version.
///
/// Remember to execute UI instuctions on main thread.
///
/// - Parameters:
/// - version: Version to be checked, you can use the variable `BFApp.version` to pass the current App version.
/// - block: The block to execute, returns isFirstStart.
public static func onFirstStart(version: String = "", block: (_ isFirstStart: Bool) -> Void) {
let key: String = BFAppHasBeenOpened + version
let defaults = UserDefaults.standard
let hasBeenOpened: Bool = defaults.bool(forKey: key)
if hasBeenOpened != true {
defaults.set(true, forKey: key)
}
block(!hasBeenOpened)
}
/// Reset the App like has never been started.
///
/// - Parameter version: Version to be checked, you can use the variable `BFApp.version` to pass the current App version.
public static func resetFirstStart(version: String = "") {
let key: String = BFAppHasBeenOpened + version
let defaults = UserDefaults.standard
defaults.removeObject(forKey: key)
}
/// Set the App setting for a given object and key. The file will be saved in the Library directory.
///
/// - Parameters:
/// - object: Object to set.
/// - objectKey: Key to set the object.
/// - Returns: Returns true if the operation was successful, otherwise false.
@discardableResult
public static func setAppSetting(object: Any, forKey objectKey: String) -> Bool {
FileManager.default.setSettings(filename: BFApp.name, object: object, forKey: objectKey)
}
/// Get the App setting for a given key.
///
/// - Parameter objectKey: Key to get the object.
/// - Returns: Returns the object for the given key.
public static func getAppSetting(objectKey: String) -> Any? {
FileManager.default.getSettings(filename: BFApp.name, forKey: objectKey)
}
/// Check if the app has been installed from TestFlight.
///
/// - Returns: Returns `true` if the app has been installed via TestFlight, otherwise `false`.
public static func isFromTestFlight() -> Bool {
guard let appStoreReceiptURL = Bundle.main.appStoreReceiptURL else {
return false
}
return appStoreReceiptURL.lastPathComponent == "sandboxReceipt"
}
}
// MARK: - BFApp extension
/// Extends BFApp with project infos.
public extension BFApp {
// MARK: - Variables
/// Return the App name.
static var name: String = {
BFApp.stringFromInfoDictionary(forKey: "CFBundleDisplayName")
}()
/// Returns the App version.
static var version: String = {
BFApp.stringFromInfoDictionary(forKey: "CFBundleShortVersionString")
}()
/// Returns the App build.
static var build: String = {
BFApp.stringFromInfoDictionary(forKey: "CFBundleVersion")
}()
/// Returns the App executable.
static var executable: String = {
BFApp.stringFromInfoDictionary(forKey: "CFBundleExecutable")
}()
/// Returns the App bundle.
static var bundle: String = {
BFApp.stringFromInfoDictionary(forKey: "CFBundleIdentifier")
}()
// MARK: - Functions
/// Returns a String from the Info dictionary of the App.
///
/// - Parameter key: Key to search.
/// - Returns: Returns a String from the Info dictionary of the App.
private static func stringFromInfoDictionary(forKey key: String) -> String {
guard let infoDictionary = Bundle.main.infoDictionary, let value = infoDictionary[key] as? String else {
return ""
}
return value
}
}
| mit |
wwu-pi/md2-framework | de.wwu.md2.framework/res/resources/ios/lib/controller/validator/MD2TimeRangeValidator.swift | 1 | 1924 | //
// MD2TimeRangeValidator.swift
// md2-ios-library
//
// Created by Christoph Rieger on 23.07.15.
// Copyright (c) 2015 Christoph Rieger. All rights reserved.
//
/**
Validator to check for a given time range.
*/
class MD2TimeRangeValidator: MD2Validator {
/// Unique identification string.
let identifier: MD2String
/// Custom message to display.
var message: (() -> MD2String)?
/// Default message to display.
var defaultMessage: MD2String {
get {
return MD2String("The time must be between \(min.toString()) and \(max.toString())!")
}
}
/// Minimum allowed time.
let min: MD2Time
/// Maximum allowed time.
let max: MD2Time
/**
Default initializer.
:param: identifier The unique validator identifier.
:param: message Closure of the custom method to display.
:param: min The minimum value of a valid time.
:param: max The maximum value of a valid time.
*/
init(identifier: MD2String, message: (() -> MD2String)?, min: MD2Time, max: MD2Time) {
self.identifier = identifier
self.message = message
self.min = min
self.max = max
}
/**
Validate a value.
:param: value The value to check.
:return: Validation result
*/
func isValid(value: MD2Type) -> Bool {
if value is MD2Time
&& (value as! MD2Time).gte(min)
&& (value as! MD2Time).lte(max) {
return true
} else {
return false
}
}
/**
Return the message to display on wrong validation.
Use custom method if set or else use default message.
*/
func getMessage() -> MD2String {
if let _ = message {
return message!()
} else {
return defaultMessage
}
}
} | apache-2.0 |
EcolabCompany/StaticTableViewDatasource | Tests/StaticTableViewDatasourceTests/XCTestManifests.swift | 1 | 175 | import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(StaticTableViewDatasourceTests.allTests),
]
}
#endif
| mit |
ibru/Swifter | Swifter/SwifterOAuthClient.swift | 2 | 8155 | //
// SwifterOAuthClient.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import Accounts
internal class SwifterOAuthClient: SwifterClientProtocol {
struct OAuth {
static let version = "1.0"
static let signatureMethod = "HMAC-SHA1"
}
var consumerKey: String
var consumerSecret: String
var credential: SwifterCredential?
var dataEncoding: NSStringEncoding
init(consumerKey: String, consumerSecret: String) {
self.consumerKey = consumerKey
self.consumerSecret = consumerSecret
self.dataEncoding = NSUTF8StringEncoding
}
init(consumerKey: String, consumerSecret: String, accessToken: String, accessTokenSecret: String) {
self.consumerKey = consumerKey
self.consumerSecret = consumerSecret
let credentialAccessToken = SwifterCredential.OAuthAccessToken(key: accessToken, secret: accessTokenSecret)
self.credential = SwifterCredential(accessToken: credentialAccessToken)
self.dataEncoding = NSUTF8StringEncoding
}
func get(path: String, baseURL: NSURL, parameters: Dictionary<String, Any>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: SwifterHTTPRequest.DownloadProgressHandler?, success: SwifterHTTPRequest.SuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) -> SwifterHTTPRequest {
let url = NSURL(string: path, relativeToURL: baseURL)!
let method = "GET"
let request = SwifterHTTPRequest(URL: url, method: method, parameters: parameters)
request.headers = ["Authorization": self.authorizationHeaderForMethod(method, url: url, parameters: parameters, isMediaUpload: false)]
request.downloadProgressHandler = downloadProgress
request.successHandler = success
request.failureHandler = failure
request.dataEncoding = self.dataEncoding
request.start()
return request
}
func post(path: String, baseURL: NSURL, var parameters: Dictionary<String, Any>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: SwifterHTTPRequest.DownloadProgressHandler?, success: SwifterHTTPRequest.SuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) -> SwifterHTTPRequest {
let url = NSURL(string: path, relativeToURL: baseURL)!
let method = "POST"
var postData: NSData?
var postDataKey: String?
if let key: Any = parameters[Swifter.DataParameters.dataKey] {
if let keyString = key as? String {
postDataKey = keyString
postData = parameters[postDataKey!] as? NSData
parameters.removeValueForKey(Swifter.DataParameters.dataKey)
parameters.removeValueForKey(postDataKey!)
}
}
var postDataFileName: String?
if let fileName: Any = parameters[Swifter.DataParameters.fileNameKey] {
if let fileNameString = fileName as? String {
postDataFileName = fileNameString
parameters.removeValueForKey(fileNameString)
}
}
let request = SwifterHTTPRequest(URL: url, method: method, parameters: parameters)
request.headers = ["Authorization": self.authorizationHeaderForMethod(method, url: url, parameters: parameters, isMediaUpload: postData != nil)]
request.downloadProgressHandler = downloadProgress
request.successHandler = success
request.failureHandler = failure
request.dataEncoding = self.dataEncoding
request.encodeParameters = postData == nil
if postData != nil {
let fileName = postDataFileName ?? "media.jpg"
request.addMultipartData(postData!, parameterName: postDataKey!, mimeType: "application/octet-stream", fileName: fileName)
}
request.start()
return request
}
func authorizationHeaderForMethod(method: String, url: NSURL, parameters: Dictionary<String, Any>, isMediaUpload: Bool) -> String {
var authorizationParameters = Dictionary<String, Any>()
authorizationParameters["oauth_version"] = OAuth.version
authorizationParameters["oauth_signature_method"] = OAuth.signatureMethod
authorizationParameters["oauth_consumer_key"] = self.consumerKey
authorizationParameters["oauth_timestamp"] = String(Int(NSDate().timeIntervalSince1970))
authorizationParameters["oauth_nonce"] = NSUUID().UUIDString
if self.credential?.accessToken != nil {
authorizationParameters["oauth_token"] = self.credential!.accessToken!.key
}
for (key, value): (String, Any) in parameters {
if key.hasPrefix("oauth_") {
authorizationParameters.updateValue(value, forKey: key)
}
}
let combinedParameters = authorizationParameters +| parameters
let finalParameters = isMediaUpload ? authorizationParameters : combinedParameters
authorizationParameters["oauth_signature"] = self.oauthSignatureForMethod(method, url: url, parameters: finalParameters, accessToken: self.credential?.accessToken)
var authorizationParameterComponents = authorizationParameters.urlEncodedQueryStringWithEncoding(self.dataEncoding).componentsSeparatedByString("&") as [String]
authorizationParameterComponents.sortInPlace { $0 < $1 }
var headerComponents = [String]()
for component in authorizationParameterComponents {
let subcomponent = component.componentsSeparatedByString("=") as [String]
if subcomponent.count == 2 {
headerComponents.append("\(subcomponent[0])=\"\(subcomponent[1])\"")
}
}
return "OAuth " + headerComponents.joinWithSeparator(", ")
}
func oauthSignatureForMethod(method: String, url: NSURL, parameters: Dictionary<String, Any>, accessToken token: SwifterCredential.OAuthAccessToken?) -> String {
var tokenSecret: NSString = ""
if token != nil {
tokenSecret = token!.secret.urlEncodedStringWithEncoding(self.dataEncoding)
}
let encodedConsumerSecret = self.consumerSecret.urlEncodedStringWithEncoding(self.dataEncoding)
let signingKey = "\(encodedConsumerSecret)&\(tokenSecret)"
var parameterComponents = parameters.urlEncodedQueryStringWithEncoding(self.dataEncoding).componentsSeparatedByString("&") as [String]
parameterComponents.sortInPlace { $0 < $1 }
let parameterString = parameterComponents.joinWithSeparator("&")
let encodedParameterString = parameterString.urlEncodedStringWithEncoding(self.dataEncoding)
let encodedURL = url.absoluteString.urlEncodedStringWithEncoding(self.dataEncoding)
let signatureBaseString = "\(method)&\(encodedURL)&\(encodedParameterString)"
// let signature = signatureBaseString.SHA1DigestWithKey(signingKey)
return signatureBaseString.SHA1DigestWithKey(signingKey).base64EncodedStringWithOptions([])
}
}
| mit |
russelhampton05/MenMew | App Prototypes/Test_004_QRScanner/Test_004_QRScanner/Test_004_QRScanner/CircleTransition.swift | 1 | 4587 | //
// CircleTransition.swift
// Test_004_QRScanner
//
// Created by Jon Calanio on 9/16/16.
// Copyright © 2016 Jon Calanio. All rights reserved.
//
import UIKit
class CircleTransition: NSObject {
var circle = UIView()
var startingPoint = CGPoint.zero {
didSet {
circle.center = startingPoint
}
}
var circleColor = UIColor.whiteColor()
var duration = 1.0
enum CircularTransitionMode: Int {
case present, dismiss, pop
}
var transitionMode: CircularTransitionMode = .present
}
extension CircleTransition: UIViewControllerAnimatedTransitioning {
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return duration
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView()
if transitionMode == .present {
if let presentedView = transitionContext.viewForKey(UITransitionContextToViewKey) {
let viewCenter = presentedView.center
let viewSize = presentedView.frame.size
circle = UIView()
circle.frame = frameForCircle(withViewCenter: viewCenter, size: viewSize, startPoint: startingPoint)
circle.layer.cornerRadius = circle.frame.size.height / 2
circle.center = startingPoint
circle.backgroundColor = circleColor
circle.transform = CGAffineTransformMakeScale(0.001, 0.001)
containerView!.addSubview(circle)
presentedView.center = startingPoint
presentedView.transform = CGAffineTransformMakeScale(0.001, 0.001)
presentedView.alpha = 0
containerView!.addSubview(presentedView)
UIView.animateWithDuration(duration, animations: {
self.circle.transform = CGAffineTransformIdentity
presentedView.transform = CGAffineTransformIdentity
presentedView.alpha = 1
presentedView.center = viewCenter
}, completion: { (success: Bool) in
transitionContext.completeTransition(success)
})
}
}
else{
let transitionModeKey = (transitionMode == .pop) ? UITransitionContextToViewKey : UITransitionContextFromViewKey
if let returningView = transitionContext.viewForKey(transitionModeKey) {
let viewCenter = returningView.center
let viewSize = returningView.frame.size
circle.frame = frameForCircle(withViewCenter: viewCenter, size: viewSize, startPoint: startingPoint)
circle.layer.cornerRadius = circle.frame.size.height / 2
circle.center = startingPoint
UIView.animateWithDuration(duration, animations: {
self.circle.transform = CGAffineTransformMakeScale(0.001, 0.001)
returningView.transform = CGAffineTransformMakeScale(0.001, 0.001)
returningView.center = self.startingPoint
returningView.alpha = 0
if self.transitionMode == .pop {
containerView!.insertSubview(returningView, belowSubview: returningView)
containerView!.insertSubview(self.circle, belowSubview: returningView)
}
}, completion: { (success: Bool) in
returningView.center = viewCenter
returningView.removeFromSuperview()
self.circle.removeFromSuperview()
transitionContext.completeTransition(success)
})
}
}
}
func frameForCircle (withViewCenter viewCenter: CGPoint, size viewSize: CGSize, startPoint: CGPoint) -> CGRect {
let xLength = fmax(startPoint.x, viewSize.width - startPoint.x)
let yLength = fmax(startPoint.y, viewSize.height - startPoint.y)
let offsetVector = sqrt(xLength * xLength + yLength * yLength) * 2
let size = CGSize(width: offsetVector, height: offsetVector)
return CGRect(origin: CGPoint.zero, size: size)
}
}
| mit |
presence-insights/pi-clientsdk-ios | IBMPIGeofence/PIGeofenceData.swift | 1 | 991 | /**
* IBMPIGeofence
* PIGeofenceData.swift
*
* Performs all communication to the PI Rest API.
*
* © Copyright 2016 IBM Corp.
*
* Licensed under the Presence Insights Client iOS Framework License (the "License");
* you may not use this file except in compliance with the License. You may find
* a copy of the license in the license.txt file in this package.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
@objc(IBMPIGeofenceData)
public class PIGeofenceData:NSObject {
static public let dataController = PIDataController(fileName:"PIGeofence")
static public let userDefaults = NSUserDefaults(suiteName: dataController.groupIdentifier)!
} | epl-1.0 |
made2k/QuickLauncher | Example/QuickLauncher/AppDelegate.swift | 2 | 2043 | /*
The MIT License (MIT)
Copyright (c) 2015 Zach McGaughey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Extract any shortcut that may have launched the app.
// We don't need to take any action here, but will
// let our view controller take action on the shortcut.
QuickLauncher.sharedInsatance.setupShortcutFromLaunchOptions(launchOptions)
return true
}
// This function is provided by UIKit. Add the @available annotation to
// allow it to work with non iOS 9 devices.
@available(iOS 9.0, *)
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
QuickLauncher.sharedInsatance.setShortcut(shortcutItem)
}
}
| mit |
GenericDataSource/GenericDataSource | GenericDataSourceTests/DelegatedGeneralCollectionViewMultiSectionTestCases.swift | 1 | 21736 | //
// DelegatedGeneralCollectionViewMultiSectionTestCases.swift
// GenericDataSource
//
// Created by Mohamed Afifi on 3/27/16.
// Copyright © 2016 mohamede1945. All rights reserved.
//
import XCTest
import GenericDataSource
private class ClosureDataSource: ReportBasicDataSource<TextReportTableViewCell> {
var configure: (([GeneralCollectionView]) -> Void)?
fileprivate override func ds_collectionView(_ collectionView: GeneralCollectionView, didSelectItemAt indexPath: IndexPath) {
configure?([collectionView, ds_reusableViewDelegate!])
}
}
class DelegatedGeneralCollectionViewMultiSectionTestCases: XCTestCase {
var tableView: TableView!
var dataSource: CompositeDataSource!
fileprivate var textReportsDataSource: ClosureDataSource!
override func setUp() {
super.setUp()
dataSource = CompositeDataSource(sectionType: .multi)
let pdfReportsDataSource = ReportBasicDataSource<PDFReportTableViewCell>()
pdfReportsDataSource.items = Report.generate(numberOfReports: 50)
dataSource.add(pdfReportsDataSource)
textReportsDataSource = ClosureDataSource()
textReportsDataSource.items = Report.generate(numberOfReports: 200)
dataSource.add(textReportsDataSource)
tableView = TableView()
tableView.reset()
tableView.ds_useDataSource(dataSource)
}
func testScrollView() {
textReportsDataSource.configure = { collectionViews in
class TestClass: UITableViewCell {
}
for collectionView in collectionViews {
XCTAssertEqual(self.tableView, collectionView.ds_scrollView)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testRegisterClass() {
textReportsDataSource.configure = { collectionViews in
class TestClass: UITableViewCell {
}
for collectionView in collectionViews {
collectionView.ds_register(TestClass.self, forCellWithReuseIdentifier: "testClass")
XCTAssertEqual(NSStringFromClass(TestClass.self), NSStringFromClass(self.tableView.cellClass!))
XCTAssertEqual("testClass", self.tableView.identifier)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testRegisterNib() {
textReportsDataSource.configure = { collectionViews in
let nib = UINib(nibName: "testNib", bundle: nil)
for collectionView in collectionViews {
collectionView.ds_register(nib, forCellWithReuseIdentifier: "testNib")
XCTAssertEqual(nib, self.tableView.nib)
XCTAssertEqual("testNib", self.tableView.identifier)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testDequeueCell() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
_ = collectionView.ds_dequeueReusableCell(withIdentifier: "testCell", for: IndexPath(row: 0, section: 0))
XCTAssertEqual(IndexPath(row: 0, section: 1), self.tableView.indexPath)
XCTAssertEqual("testCell", self.tableView.identifier)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testNumberOfSections() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
self.tableView.sections = 45
let sections = collectionView.ds_numberOfSections()
XCTAssertEqual(sections, self.tableView.sections)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testNumberOfItems() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
self.tableView.items = 45
let items = collectionView.ds_numberOfItems(inSection: 0)
XCTAssertEqual(items, self.tableView.items)
XCTAssertEqual(1, self.tableView.section)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testReloadData() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
collectionView.ds_reloadData()
XCTAssertTrue(self.tableView.called)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testPerformBatchUpdates() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
collectionView.ds_performBatchUpdates(nil, completion: nil)
XCTAssertTrue(self.tableView.called)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testInsertSections() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
let indexSet = IndexSet(integer: 0)
let animation = UITableView.RowAnimation.bottom
collectionView.ds_insertSections(indexSet, with: animation)
XCTAssertEqual(IndexSet(integer: 1), self.tableView.sectionsSet)
XCTAssertEqual(animation, self.tableView.animation)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testDeleteSections() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
let indexSet = IndexSet(integer: 0)
let animation = UITableView.RowAnimation.bottom
collectionView.ds_deleteSections(indexSet, with: animation)
XCTAssertEqual(IndexSet(integer: 1), self.tableView.sectionsSet)
XCTAssertEqual(animation, self.tableView.animation)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testReloadSections() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
let indexSet = IndexSet(integer: 0)
let animation = UITableView.RowAnimation.bottom
collectionView.ds_reloadSections(indexSet, with: animation)
XCTAssertEqual(IndexSet(integer: 1), self.tableView.sectionsSet)
XCTAssertEqual(animation, self.tableView.animation)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testMoveSection() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
collectionView.ds_moveSection(0, toSection: 0)
XCTAssertEqual(1, self.tableView.section)
XCTAssertEqual(1, self.tableView.toSection)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testInsertItems() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
let indexPaths = [IndexPath(row: 0, section: 0), IndexPath(row: 10, section: 0)]
let animation = UITableView.RowAnimation.bottom
collectionView.ds_insertItems(at: indexPaths, with: animation)
XCTAssertEqual([IndexPath(row: 0, section: 1), IndexPath(row: 10, section: 1)],
self.tableView.indexPaths!)
XCTAssertEqual(animation, self.tableView.animation)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testDeleteItems() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
let indexPaths = [IndexPath(row: 0, section: 0), IndexPath(row: 10, section: 0)]
let animation = UITableView.RowAnimation.bottom
collectionView.ds_deleteItems(at: indexPaths, with: animation)
XCTAssertEqual([IndexPath(row: 0, section: 1), IndexPath(row: 10, section: 1)],
self.tableView.indexPaths!)
XCTAssertEqual(animation, self.tableView.animation)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testReloadItems() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
let indexPaths = [IndexPath(row: 0, section: 0), IndexPath(row: 10, section: 0)]
let animation = UITableView.RowAnimation.bottom
collectionView.ds_reloadItems(at: indexPaths, with: animation)
XCTAssertEqual([IndexPath(row: 0, section: 1), IndexPath(row: 10, section: 1)],
self.tableView.indexPaths!)
XCTAssertEqual(animation, self.tableView.animation)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testMoveItem() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
collectionView.ds_moveItem(at: IndexPath(row: 15, section: 0), to: IndexPath(row: 50, section: 0))
XCTAssertEqual(IndexPath(row: 15, section: 1), self.tableView.indexPath)
XCTAssertEqual(IndexPath(row: 50, section: 1), self.tableView.toIndexPath)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testScrollToItem() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
let indexPath = IndexPath(row: 145, section: 0)
let scroll = UICollectionView.ScrollPosition.bottom
let animated = true
collectionView.ds_scrollToItem(at: indexPath, at: scroll, animated: animated)
XCTAssertEqual(IndexPath(row: 145, section: 1), self.tableView.indexPath)
XCTAssertEqual(UITableView.ScrollPosition.bottom, self.tableView.scrollPosition)
XCTAssertEqual(animated, self.tableView.animated)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testSelectItem() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
let indexPath = IndexPath(row: 145, section: 0)
let scroll = UICollectionView.ScrollPosition.top
let animated = true
collectionView.ds_selectItem(at: indexPath, animated: animated, scrollPosition: scroll)
XCTAssertEqual(IndexPath(row: 145, section: 1), self.tableView.indexPath)
XCTAssertEqual(UITableView.ScrollPosition.top, self.tableView.scrollPosition)
XCTAssertEqual(animated, self.tableView.animated)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testSelectItemWithNil() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
let indexPath: IndexPath? = nil
let scroll = UICollectionView.ScrollPosition.top
let animated = true
collectionView.ds_selectItem(at: indexPath, animated: animated, scrollPosition: scroll)
XCTAssertEqual(indexPath, self.tableView.indexPath)
XCTAssertEqual(UITableView.ScrollPosition.top, self.tableView.scrollPosition)
XCTAssertEqual(animated, self.tableView.animated)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testDeselectItem() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
let indexPath = IndexPath(row: 145, section: 0)
let animated = false
collectionView.ds_deselectItem(at: indexPath, animated: animated)
XCTAssertEqual(IndexPath(row: 145, section: 1), self.tableView.indexPath)
XCTAssertEqual(animated, self.tableView.animated)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testIndexPathForCell() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
let cell = UITableViewCell()
self.tableView.indexPath = IndexPath(row: 50, section: 1)
let indexPath = collectionView.ds_indexPath(for: cell)
XCTAssertEqual(IndexPath(row: 50, section: 0), indexPath)
XCTAssertEqual(cell, self.tableView.cell)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testIndexPathForCellNil() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
let cell = UITableViewCell()
self.tableView.indexPath = nil
let indexPath = collectionView.ds_indexPath(for: cell)
XCTAssertEqual(self.tableView.indexPath, indexPath)
XCTAssertEqual(cell, self.tableView.cell)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testIndexPathForItemAtPoint() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
let point = CGPoint(x: 11, y: 22)
self.tableView.indexPath = IndexPath(row: 50, section: 1)
let indexPath = collectionView.ds_indexPathForItem(at: point)
XCTAssertEqual(IndexPath(row: 50, section: 0), indexPath)
XCTAssertEqual(point, self.tableView.point)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testIndexPathForItemAtPointNil() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
let point = CGPoint(x: 11, y: 22)
self.tableView.indexPath = nil
let indexPath = collectionView.ds_indexPathForItem(at: point)
XCTAssertEqual(self.tableView.indexPath, indexPath)
XCTAssertEqual(point, self.tableView.point)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testIndexPathsForVisibleItems() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
self.tableView.indexPaths = [IndexPath(row: 50, section: 1), IndexPath(row: 100, section: 1)]
let indexPaths = collectionView.ds_indexPathsForVisibleItems()
XCTAssertEqual([IndexPath(row: 50, section: 0), IndexPath(row: 100, section: 0)], indexPaths)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testIndexPathsForSelectedItems() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
self.tableView.indexPaths = [IndexPath(row: 50, section: 1), IndexPath(row: 100, section: 1)]
let indexPaths = collectionView.ds_indexPathsForSelectedItems()
XCTAssertEqual([IndexPath(row: 50, section: 0), IndexPath(row: 100, section: 0)], indexPaths)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testVisibleCells() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
self.tableView.cells = [UITableViewCell(), TextReportTableViewCell()]
let cells = collectionView.ds_visibleCells()
XCTAssertEqual(self.tableView.cells.count, cells.count)
for i in 0..<cells.count {
if let cell = cells[i] as? UITableViewCell {
XCTAssertEqual(cell, self.tableView.cells[i])
} else {
XCTFail()
}
}
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testCellForItemAtIndexPath() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
self.tableView.cell = UITableViewCell()
let cell = collectionView.ds_cellForItem(at: IndexPath(row: 0, section: 0))
XCTAssertEqual(IndexPath(row: 0, section: 1), self.tableView.indexPath)
XCTAssertEqual(cell as? UITableViewCell, self.tableView.cell)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testLocalIndexPathForGlobalIndexPath() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
let indexPath = collectionView.ds_localIndexPathForGlobalIndexPath(IndexPath(row: 51, section: 1))
XCTAssertEqual(IndexPath(row: 51, section: 0), indexPath)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testGlobalIndexPathForLocalIndexPath() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
let indexPath = collectionView.ds_globalIndexPathForLocalIndexPath(IndexPath(row: 2, section: 0))
XCTAssertEqual(IndexPath(row: 2, section: 1), indexPath)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
func testGlobalSectionForLocalSection() {
textReportsDataSource.configure = { collectionViews in
for collectionView in collectionViews {
let section = collectionView.ds_globalSectionForLocalSection(0)
XCTAssertEqual(1, section)
self.tableView.reset()
}
}
// call configure
dataSource.ds_collectionView(tableView, didSelectItemAt: IndexPath(row: 50, section: 1))
}
}
| mit |
GenericDataSource/GenericDataSource | Example/Example/ContactTableViewCell.swift | 1 | 514 | //
// ContactTableViewCell.swift
// Example
//
// Created by Mohamed Ebrahim Mohamed Afifi on 4/3/17.
// Copyright © 2017 Mohamed Afifi. All rights reserved.
//
import UIKit
class ContactTableViewCell: UITableViewCell, ContactCell {
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.