repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
HabitRPG/habitrpg-ios
|
Habitica API Client/Habitica API Client/Models/User/APIFlags.swift
|
1
|
2515
|
//
// APIFlags.swift
// Habitica API Client
//
// Created by Phillip Thelen on 09.03.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
class APIFlags: FlagsProtocol, Decodable {
var armoireEmpty: Bool = false
var cronCount: Int = 0
var rebirthEnabled: Bool = false
var communityGuidelinesAccepted: Bool = false
var hasNewStuff: Bool = false
var armoireOpened: Bool = false
var chatRevoked: Bool = false
var classSelected: Bool = false
var itemsEnabled: Bool = false
var verifiedUsername: Bool = false
var tutorials: [TutorialStepProtocol]
var welcomed: Bool = false
enum CodingKeys: String, CodingKey {
case armoireEmpty
case cronCount
case rebirthEnabled
case communityGuidelinesAccepted
case hasNewStuff = "newStuff"
case armoireOpened
case chatRevoked
case classSelected
case itemsEnabled
case verifiedUsername
case tutorials = "tutorial"
case welcomed
}
public required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
armoireEmpty = (try? values.decode(Bool.self, forKey: .armoireEmpty)) ?? false
cronCount = (try? values.decode(Int.self, forKey: .cronCount)) ?? 0
rebirthEnabled = (try? values.decode(Bool.self, forKey: .rebirthEnabled)) ?? false
communityGuidelinesAccepted = (try? values.decode(Bool.self, forKey: .communityGuidelinesAccepted)) ?? false
hasNewStuff = (try? values.decode(Bool.self, forKey: .hasNewStuff)) ?? false
armoireOpened = (try? values.decode(Bool.self, forKey: .armoireOpened)) ?? false
chatRevoked = (try? values.decode(Bool.self, forKey: .chatRevoked)) ?? false
classSelected = (try? values.decode(Bool.self, forKey: .classSelected)) ?? false
itemsEnabled = (try? values.decode(Bool.self, forKey: .itemsEnabled)) ?? false
verifiedUsername = (try? values.decode(Bool.self, forKey: .verifiedUsername)) ?? false
welcomed = (try? values.decode(Bool.self, forKey: .welcomed)) ?? false
tutorials = []
try? values.decode([String: [String: Bool]].self, forKey: .tutorials).forEach({ tutorialTypes in
tutorialTypes.value.forEach({ (key, wasSeen) in
tutorials.append(APITutorialStep(type: tutorialTypes.key, key: key, wasSeen: wasSeen))
})
})
}
}
|
gpl-3.0
|
46d923de5629ee8df1661d2282c9382d
| 40.213115 | 116 | 0.662291 | 3.971564 | false | false | false | false |
bridger/NumberPad
|
NumberPad/NumberSlideView.swift
|
1
|
13455
|
//
// NumberSlideView.swift
// NumberPad
//
// Created by Bridger Maxwell on 1/17/15.
// Copyright (c) 2015 Bridger Maxwell. All rights reserved.
//
import UIKit
public protocol NumberSlideViewDelegate: NSObjectProtocol {
func numberSlideView(numberSlideView: NumberSlideView, didSelectNewValue newValue: NSDecimalNumber, scale: Int16)
func numberSlideView(numberSlideView: NumberSlideView, didSelectNewScale scale: Int16)
}
class ScaleButton: UIButton {
var scale: Int16 = 0
override var isSelected: Bool {
didSet {
if self.isSelected {
self.backgroundColor = UIColor.textColor()
} else {
self.backgroundColor = UIColor.selectedBackgroundColor()
}
}
}
}
public class NumberSlideView: UIView, UIScrollViewDelegate {
let scrollView: UIScrollView = UIScrollView()
var valueAnchor: (Value: NSDecimalNumber, Offset: CGFloat)?
var scaleButtons: [ScaleButton] = []
public weak var delegate: NumberSlideViewDelegate?
var scale: Int16 = 0
public func resetToValue(value: NSDecimalNumber, scale: Int16) {
for label in visibleLabels {
label.removeFromSuperview()
}
visibleLabels.removeAll(keepingCapacity: true)
// Stop the scrolling
scrollView.setContentOffset(scrollView.contentOffset, animated: false)
self.scale = scale
let center = self.convert(scrollView.center, to: scrollingContentContainer)
valueAnchor = (Value: value, Offset: center.x)
fixScrollableContent()
updateScaleButtons()
}
public func selectedValue() -> NSDecimalNumber? {
if let valueAnchor = valueAnchor {
let offsetFromAnchor = self.scrollView.contentOffset.x + self.bounds.midX - valueAnchor.Offset
let spacePerTick = spacingBetweenLabels / 10.0
let ticks = Int(round(offsetFromAnchor / spacePerTick))
let valuePerTick = NSDecimalNumber(mantissa: 1, exponent: self.scale, isNegative: false)
return valueAnchor.Value.adding( NSDecimalNumber(value: ticks).multiplying(by: valuePerTick) )
}
return nil
}
public func roundedSelectedValue() -> NSDecimalNumber? {
if let value = self.selectedValue() {
let roundBehavior = NSDecimalNumberHandler(roundingMode: .down, scale: -scale, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
return value.rounding(accordingToBehavior: roundBehavior)
}
return nil
}
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
var visibleLabels: [NumberLabel] = []
let scrollingContentContainer = UIView()
let centerMarker = UIView()
func setup() {
self.backgroundColor = UIColor.selectedBackgroundColor()
centerMarker.translatesAutoresizingMaskIntoConstraints = false
centerMarker.backgroundColor = UIColor.textColor()
self.addSubview(centerMarker)
self.addAutoLayoutSubview(subview: scrollView)
self.addHorizontalConstraints( |-0-[scrollView]-0-| )
scrollView.delegate = self
self.scrollView.showsHorizontalScrollIndicator = false
self.scrollView.addSubview(scrollingContentContainer)
scrollingContentContainer.isUserInteractionEnabled = false
self.layoutIfNeeded()
resetToValue(value: NSDecimalNumber.zero, scale: 0)
let scales = [(-4, ".1%"), (-3, ".01"), (-2, ".1"), (-1, "1"), (0, "10"), (1, "10²")]
for (scale, label) in scales {
let button = ScaleButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.scale = Int16(scale)
button.setTitle(label, for: [])
self.addSubview(button)
// The following broke in swift 2.0, so they are expressed more explicity directly below
self.addVerticalConstraints( [button]-0-| )
self.addConstraint(button.al_bottom == self.al_bottom)
if let previousButton = self.scaleButtons.last {
self.addHorizontalConstraints( [previousButton]-0-[button == previousButton] )
self.addConstraint( previousButton.al_height == button.al_height )
} else {
// The first button!
self.addConstraints(horizontalConstraints( |-0-[button] ))
}
button.addTarget(self, action: #selector(NumberSlideView.scaleButtonTapped(button:)), for: .touchUpInside)
self.scaleButtons.append(button)
}
let lastScaleButton = self.scaleButtons.last!
self.addHorizontalConstraints( [lastScaleButton]-0-| )
self.addVerticalConstraints( |-0-[scrollView]-0-[lastScaleButton]-0-| )
self.addConstraint(centerMarker.al_height == scrollView.al_height)
self.addConstraint(centerMarker.al_bottom == scrollView.al_bottom)
self.addConstraint(centerMarker.al_centerX == scrollView.al_centerX)
self.addConstraint(centerMarker.al_width == 2.0)
updateScaleButtons()
}
public override func layoutSubviews() {
super.layoutSubviews()
scrollView.contentSize = CGSize(width: 5000, height: scrollView.frame.size.height)
scrollingContentContainer.frame = CGRect(x: 0, y: 0, width: self.scrollView.contentSize.width, height: self.scrollView.contentSize.height)
let yPosition = scrollingContentContainer.bounds.size.height / 2.0
for label in visibleLabels {
label.center.y = yPosition
}
fixScrollableContent()
}
func scaleButtonTapped(button: ScaleButton) {
if let selectedValue = selectedValue() {
self.resetToValue(value: selectedValue, scale: button.scale)
if let delegate = delegate {
delegate.numberSlideView(numberSlideView: self, didSelectNewScale: button.scale)
}
}
}
func updateScaleButtons() {
for button in self.scaleButtons {
button.isSelected = button.scale == self.scale
}
}
var centerValue: CGFloat = 0.0
func recenterIfNecessary() {
let currentOffset = scrollView.contentOffset
let contentWidth = scrollView.contentSize.width
let centerOffsetX = (contentWidth - scrollView.bounds.size.width) / 2.0
let distanceFromCenter = abs(currentOffset.x - centerOffsetX)
if distanceFromCenter > contentWidth / 4.0 {
let moveAmount = centerOffsetX - currentOffset.x
scrollView.contentOffset = CGPoint(x: centerOffsetX, y: currentOffset.y)
for label in self.visibleLabels {
var center = scrollingContentContainer.convert(label.center, to: scrollView)
center.x += moveAmount
label.center = scrollView.convert(center, to: scrollingContentContainer)
}
if let valueAnchor = self.valueAnchor {
self.valueAnchor = (Value: valueAnchor.Value, Offset: valueAnchor.Offset + moveAmount)
}
}
}
var lastSelectedValue: NSDecimalNumber?
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
fixScrollableContent()
// Figure out which new value is selected. If it is new, pass it on to the delegate
if let delegate = delegate {
if let selectedValue = roundedSelectedValue() {
if selectedValue != lastSelectedValue {
delegate.numberSlideView(numberSlideView: self, didSelectNewValue: selectedValue, scale: self.scale)
lastSelectedValue = selectedValue
}
}
}
}
let spacingBetweenLabels: CGFloat = 70.0
func fixScrollableContent() {
recenterIfNecessary()
let visibleBounds = scrollView.convert(scrollView.bounds, to: scrollingContentContainer)
let minVisibleX = visibleBounds.minX
let maxVisibileX = visibleBounds.maxX
self.tileLabelsFromMinX(minX: minVisibleX - spacingBetweenLabels * 2, maxX: maxVisibileX + spacingBetweenLabels * 2)
}
func addLabelCenteredAt(value: NSDecimalNumber, centerX: CGFloat) -> NumberLabel {
let newLabel = NumberLabel(number: value)
newLabel.font = UIFont.systemFont(ofSize: 22)
newLabel.sizeToFit()
newLabel.center = CGPoint(x: centerX, y: scrollingContentContainer.bounds.midY)
newLabel.textColor = UIColor.selectedTextColor()
scrollingContentContainer.addSubview(newLabel)
return newLabel
}
func tileLabelsFromMinX(minX: CGFloat, maxX: CGFloat) {
if var valueAnchor = valueAnchor {
let valueBetweenLabels = NSDecimalNumber(mantissa: 1, exponent: self.scale + 1, isNegative: false)
// Move the anchor closer to the center, if it isn't in the visible region
if valueAnchor.Offset < minX || valueAnchor.Offset > maxX {
let distanceFromCenter = (minX + maxX) / 2.0 - valueAnchor.Offset
let placesToMove = Int(distanceFromCenter / spacingBetweenLabels)
let newValue = valueAnchor.Value.adding( NSDecimalNumber(value: placesToMove).multiplying(by: valueBetweenLabels) )
let newOffset = valueAnchor.Offset + CGFloat(placesToMove) * spacingBetweenLabels
valueAnchor = (Value: newValue, Offset: newOffset)
self.valueAnchor = valueAnchor
}
// the upcoming tiling logic depends on there already being at least one label in the visibleLabels array, so
// to kick off the tiling we need to make sure there's at least one label
if visibleLabels.count == 0 {
// We need to add the first label! If we have a valueAnchor at 60.6 and a scale of 0, then we would place a label of 60 at (60% * spacing) to the left of the anchor.
let labelRoundBehavior = NSDecimalNumberHandler(roundingMode: .down, scale: -(scale + 1), raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
let closestLabelValue = valueAnchor.Value.rounding(accordingToBehavior: labelRoundBehavior)
let valueDifference = (closestLabelValue.doubleValue - valueAnchor.Value.doubleValue)
let offset = CGFloat(valueDifference / valueBetweenLabels.doubleValue) * spacingBetweenLabels
let label = addLabelCenteredAt(value: closestLabelValue, centerX: valueAnchor.Offset + offset)
visibleLabels.append(label)
}
// Add labels missing on the left side
var firstLabel = visibleLabels.first!
while firstLabel.center.x - spacingBetweenLabels > minX {
let newCenter = firstLabel.center.x - spacingBetweenLabels
let newValue = firstLabel.number.subtracting(valueBetweenLabels)
let label = addLabelCenteredAt(value: newValue, centerX: newCenter)
visibleLabels.insert(label, at: 0)
firstLabel = label
}
// Add labels missing on the right side
var lastLabel = visibleLabels.last!
while lastLabel.center.x + spacingBetweenLabels < maxX {
let newCenter = lastLabel.center.x + spacingBetweenLabels
let newValue = lastLabel.number.adding(valueBetweenLabels)
let label = addLabelCenteredAt(value: newValue, centerX: newCenter)
visibleLabels.append(label)
lastLabel = label
}
// Remove labels that have fallen off the left edge
while true {
if let firstLabel = visibleLabels.first {
if firstLabel.frame.midX < minX {
visibleLabels.remove(at: 0)
firstLabel.removeFromSuperview()
continue
}
}
break
}
// Remove labels that have fallen off the right edge
while true {
if let lastLabel = visibleLabels.last {
if lastLabel.frame.midX > maxX {
visibleLabels.removeLast()
lastLabel.removeFromSuperview()
continue
}
}
break
}
}
}
}
class NumberLabel: UILabel {
let number: NSDecimalNumber
init(number: NSDecimalNumber) {
self.number = number
super.init(frame: CGRect.zero)
self.text = number.description
self.textColor = UIColor.selectedTextColor()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
apache-2.0
|
fa0e9558c37e55a7e36d578fbf1b9798
| 41.175549 | 207 | 0.617809 | 5.257522 | false | false | false | false |
CocoaHeadsCR/CETAV_Mapa
|
CETAV/ViewController.swift
|
1
|
1857
|
//
// ViewController.swift
// CETAV
//
// Created by Esteban Torres on 12/2/16.
// Copyright © 2016 Esteban Torres. All rights reserved.
//
//// Native Frameworks
import UIKit
import MapKit
class ViewController: UIViewController {
// MARK: Propiedades de UI
@IBOutlet weak var mapa: MKMapView!
@IBOutlet weak var agregarBtn: UIButton!
// MARK: Propiedades
let manager = CLLocationManager()
let cargador = CargadorDatos()
// MARK: Ciclo de vida del VC
override func viewDidLoad() {
super.viewDidLoad()
// Tenemos que solicitar al usuario permiso para acceder a su ubicación
manager.requestWhenInUseAuthorization()
self.mapa.showsUserLocation = true
self.mapa.delegate = self
}
// MARK: Eventos
@IBAction func agregarPuntos_tapped(sender: UIButton) {
self.cargador.cargarDatos { (puntos) -> () in
print(puntos)
let anotaciones = puntos.map { punto -> MKPointAnnotation in
let anotacion = MKPointAnnotation()
anotacion.coordinate = punto.coordenadas
anotacion.title = punto.titulo
anotacion.subtitle = punto.subtitulo
return anotacion
}
self.mapa.addAnnotations(anotaciones)
}
}
}
// MARK: - MKMapViewDelegate
extension ViewController: MKMapViewDelegate {
func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) {
// Centramos el mapa en el usuario actual
// mapView.setCenterCoordinate(userLocation.coordinate, animated: true)
// Centramos el mapa en una región cuyo centro es la ubicación del usuario
// Y cuya distancia longitudinal y latitudinal es de 2Kms
let region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 2000, 2000)
mapView.setRegion(region, animated: true)
self.agregarBtn.enabled = true
}
}
|
mit
|
5faae23bf2d33e7a6f1e58ee785dd0d0
| 26.264706 | 88 | 0.698867 | 4.081498 | false | false | false | false |
tjw/swift
|
test/SILGen/external-keypath.swift
|
1
|
3173
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o %t/ExternalKeyPaths.swiftmodule -module-name ExternalKeyPaths %S/Inputs/ExternalKeyPaths.swift
// RUN: %target-swift-frontend -enable-key-path-resilience -emit-silgen -I %t %s | %FileCheck %s
import ExternalKeyPaths
struct Local {
var x: Int
var y: String
}
// CHECK-LABEL: sil hidden @{{.*}}16externalKeyPaths
func externalKeyPaths<T: Hashable, U>(_ x: T, _ y: U, _ z: Int) {
// CHECK: keypath $WritableKeyPath<External<Int>, Int>, (root $External<Int>; external #External.property<Int> : $Int)
_ = \External<Int>.property
// CHECK: keypath $WritableKeyPath<External<Int>, Int>, (root $External<Int>; external #External.intProperty<Int> : $Int)
_ = \External<Int>.intProperty
// CHECK: keypath $WritableKeyPath<External<T>, T>, <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (root $External<τ_0_0>; external #External.property<T> : $τ_0_0) <T, U>
_ = \External<T>.property
// CHECK: keypath $WritableKeyPath<External<T>, Int>, <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (root $External<τ_0_0>; external #External.intProperty<T> : $Int) <T, U>
_ = \External<T>.intProperty
// CHECK: keypath $WritableKeyPath<External<U>, U>, <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (root $External<τ_0_1>; external #External.property<U> : $τ_0_1) <T, U>
_ = \External<U>.property
// CHECK: keypath $WritableKeyPath<External<U>, Int>, <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (root $External<τ_0_1>; external #External.intProperty<U> : $Int) <T, U>
_ = \External<U>.intProperty
// CHECK: keypath $KeyPath<External<Int>, Int>, (root $External<Int>; external #External.subscript<Int, Int>[%$0 : $Int : $Int] : $Int, indices_equals @{{.*}}) (%2)
_ = \External<Int>.[z]
// CHECK: keypath $KeyPath<External<T>, T>, <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (root $External<τ_0_0>; external #External.subscript<T, T>[%$0 : $τ_0_0 : $*τ_0_0] : $τ_0_0, indices_equals @{{.*}}) <T, U> ({{.*}})
_ = \External<T>.[x]
// CHECK: keypath $KeyPath<External<U>, U>, <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (root $External<τ_0_1>; external #External.subscript<U, T>[%$0 : $τ_0_0 : $*τ_0_0] : $τ_0_1, indices_equals @{{.*}}) <T, U> ({{.*}})
_ = \External<U>.[x]
// CHECK: keypath $KeyPath<External<Local>, Int>, <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (
// CHECK-SAME: root $External<Local>;
// CHECK-SAME: external #External.subscript<Local, T>[%$0 : $τ_0_0 : $*τ_0_0] : $Local, indices_equals @{{.*}};
// CHECK-SAME: stored_property #Local.x : $Int) <T, U> ({{.*}})
_ = \External<Local>.[x].x
// CHECK: keypath $KeyPath<External<Local>, String>, <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (
// CHECK-SAME: root $External<Local>;
// CHECK-SAME: external #External.subscript<Local, T>[%$0 : $τ_0_0 : $*τ_0_0] : $Local, indices_equals @{{.*}};
// CHECK-SAME: stored_property #Local.y : $String) <T, U> ({{.*}})
_ = \External<Local>.[x].y
// CHECK: keypath $KeyPath<ExternalEmptySubscript, Int>, (
// CHECK-SAME: root $ExternalEmptySubscript;
// CHECK-SAME: external #ExternalEmptySubscript.subscript : $Int)
_ = \ExternalEmptySubscript.[]
}
|
apache-2.0
|
9414d9c5ba3a46250e3457eb85c076d4
| 53.929825 | 216 | 0.627595 | 2.846364 | false | false | false | false |
ArthurKK/Kingfisher
|
Kingfisher/UIButton+Kingfisher.swift
|
2
|
31149
|
//
// UIButton+Kingfisher.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/13.
//
// Copyright (c) 2015 Wei Wang <onevcat@gmail.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
/**
* Set image to use from web for a specified state.
*/
public extension UIButton {
/**
Set an image to use for a specified state with a resource.
It will ask for Kingfisher's manager to get the image for the `cacheKey` property in `resource` and then set it for a button state.
The memory and disk will be searched first. If the manager does not find it, it will try to download the image at the `resource.downloadURL` and store it with `resource.cacheKey` for next use.
:param: resource Resource object contains information such as `cacheKey` and `downloadURL`.
:param: state The state that uses the specified image.
:returns: A task represents the retrieving process.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState) -> RetrieveImageTask
{
return kf_setImageWithResource(resource, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a URL.
It will ask for Kingfisher's manager to get the image for the URL and then set it for a button state.
The memory and disk will be searched first with `URL.absoluteString` as the cache key. If the manager does not find it, it will try to download the image at this URL and store the image with `URL.absoluteString` as cache key for next use.
If you need to specify the key other than `URL.absoluteString`, please use resource version of these APIs with `resource.cacheKey` set to what you want.
:param: URL The URL of image for specified state.
:param: state The state that uses the specified image.
:returns: A task represents the retrieving process.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a resource and a placeholder image.
:param: resource Resource object contains information such as `cacheKey` and `downloadURL`.
:param: state The state that uses the specified image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:returns: A task represents the retrieving process.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a URL and a placeholder image.
:param: URL The URL of image for specified state.
:param: state The state that uses the specified image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:returns: A task represents the retrieving process.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a resource, a placeholder image and options.
:param: resource Resource object contains information such as `cacheKey` and `downloadURL`.
:param: state The state that uses the specified image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
:returns: A task represents the retrieving process.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a URL, a placeholder image and options.
:param: URL The URL of image for specified state.
:param: state The state that uses the specified image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
:returns: A task represents the retrieving process.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a resource, a placeholder image, options and completion handler.
:param: resource Resource object contains information such as `cacheKey` and `downloadURL`.
:param: state The state that uses the specified image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
:param: completionHandler Called when the image retrieved and set.
:returns: A task represents the retrieving process.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set an image to use for a specified state with a URL, a placeholder image, options and completion handler.
:param: URL The URL of image for specified state.
:param: state The state that uses the specified image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
:param: completionHandler Called when the image retrieved and set.
:returns: A task represents the retrieving process.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set an image to use for a specified state with a resource, a placeholder image, options, progress handler and completion handler.
:param: resource Resource object contains information such as `cacheKey` and `downloadURL`.
:param: state The state that uses the specified image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
:param: progressBlock Called when the image downloading progress gets updated.
:param: completionHandler Called when the image retrieved and set.
:returns: A task represents the retrieving process.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
setImage(placeholderImage, forState: state)
kf_setWebURL(resource.downloadURL, forState: state)
let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo, progressBlock: { (receivedSize, totalSize) -> () in
if let progressBlock = progressBlock {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
progressBlock(receivedSize: receivedSize, totalSize: totalSize)
})
}
}) { (image, error, cacheType, imageURL) -> () in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if (imageURL == self.kf_webURLForState(state) && image != nil) {
self.setImage(image, forState: state)
}
completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
})
}
return task
}
/**
Set an image to use for a specified state with a URL, a placeholder image, options, progress handler and completion handler.
:param: URL The URL of image for specified state.
:param: state The state that uses the specified image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
:param: progressBlock Called when the image downloading progress gets updated.
:param: completionHandler Called when the image retrieved and set.
:returns: A task represents the retrieving process.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithResource(Resource(downloadURL: URL),
forState: state,
placeholderImage: placeholderImage,
optionsInfo: optionsInfo,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
}
private var lastURLKey: Void?
public extension UIButton {
/**
Get the image URL binded to this button for a specified state.
:param: state The state that uses the specified image.
:returns: Current URL for image.
*/
public func kf_webURLForState(state: UIControlState) -> NSURL? {
return kf_webURLs[NSNumber(unsignedLong:state.rawValue)] as? NSURL
}
private func kf_setWebURL(URL: NSURL, forState state: UIControlState) {
kf_webURLs[NSNumber(unsignedLong:state.rawValue)] = URL
}
private var kf_webURLs: NSMutableDictionary {
get {
var dictionary = objc_getAssociatedObject(self, &lastURLKey) as? NSMutableDictionary
if dictionary == nil {
dictionary = NSMutableDictionary()
kf_setWebURLs(dictionary!)
}
return dictionary!
}
}
private func kf_setWebURLs(URLs: NSMutableDictionary) {
objc_setAssociatedObject(self, &lastURLKey, URLs, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
}
}
/**
* Set background image to use from web for a specified state.
*/
public extension UIButton {
/**
Set the background image to use for a specified state with a resource.
It will ask for Kingfisher's manager to get the image for the `cacheKey` property in `resource` and then set it for a button state.
The memory and disk will be searched first. If the manager does not find it, it will try to download the image at the `resource.downloadURL` and store it with `resource.cacheKey` for next use.
:param: resource Resource object contains information such as `cacheKey` and `downloadURL`.
:param: state The state that uses the specified image.
:returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a URL.
It will ask for Kingfisher's manager to get the image for the URL and then set it for a button state.
The memory and disk will be searched first with `URL.absoluteString` as the cache key. If the manager does not find it, it will try to download the image at this URL and store the image with `URL.absoluteString` as cache key for next use.
If you need to specify the key other than `URL.absoluteString`, please use resource version of these APIs with `resource.cacheKey` set to what you want.
:param: URL The URL of image for specified state.
:param: state The state that uses the specified image.
:returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a resource and a placeholder image.
:param: resource Resource object contains information such as `cacheKey` and `downloadURL`.
:param: state The state that uses the specified image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a URL and a placeholder image.
:param: URL The URL of image for specified state.
:param: state The state that uses the specified image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a resource, a placeholder image and options.
:param: resource Resource object contains information such as `cacheKey` and `downloadURL`.
:param: state The state that uses the specified image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
:returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a URL, a placeholder image and options.
:param: URL The URL of image for specified state.
:param: state The state that uses the specified image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
:returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a resource, a placeholder image, options and completion handler.
:param: resource Resource object contains information such as `cacheKey` and `downloadURL`.
:param: state The state that uses the specified image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
:param: completionHandler Called when the image retrieved and set.
:returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set the background image to use for a specified state with a URL, a placeholder image, options and completion handler.
:param: URL The URL of image for specified state.
:param: state The state that uses the specified image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
:param: completionHandler Called when the image retrieved and set.
:returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set the background image to use for a specified state with a resource,
a placeholder image, options progress handler and completion handler.
:param: resource Resource object contains information such as `cacheKey` and `downloadURL`.
:param: state The state that uses the specified image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
:param: progressBlock Called when the image downloading progress gets updated.
:param: completionHandler Called when the image retrieved and set.
:returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
setBackgroundImage(placeholderImage, forState: state)
kf_setBackgroundWebURL(resource.downloadURL, forState: state)
let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo, progressBlock: { (receivedSize, totalSize) -> () in
if let progressBlock = progressBlock {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
progressBlock(receivedSize: receivedSize, totalSize: totalSize)
})
}
}) { (image, error, cacheType, imageURL) -> () in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if (imageURL == self.kf_backgroundWebURLForState(state) && image != nil) {
self.setBackgroundImage(image, forState: state)
}
completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
})
}
return task
}
/**
Set the background image to use for a specified state with a URL,
a placeholder image, options progress handler and completion handler.
:param: URL The URL of image for specified state.
:param: state The state that uses the specified image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
:param: progressBlock Called when the image downloading progress gets updated.
:param: completionHandler Called when the image retrieved and set.
:returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(Resource(downloadURL: URL),
forState: state,
placeholderImage: placeholderImage,
optionsInfo: optionsInfo,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
}
private var lastBackgroundURLKey: Void?
public extension UIButton {
/**
Get the background image URL binded to this button for a specified state.
:param: state The state that uses the specified background image.
:returns: Current URL for background image.
*/
public func kf_backgroundWebURLForState(state: UIControlState) -> NSURL? {
return kf_backgroundWebURLs[NSNumber(unsignedLong:state.rawValue)] as? NSURL
}
private func kf_setBackgroundWebURL(URL: NSURL, forState state: UIControlState) {
kf_backgroundWebURLs[NSNumber(unsignedLong:state.rawValue)] = URL
}
private var kf_backgroundWebURLs: NSMutableDictionary {
get {
var dictionary = objc_getAssociatedObject(self, &lastBackgroundURLKey) as? NSMutableDictionary
if dictionary == nil {
dictionary = NSMutableDictionary()
kf_setBackgroundWebURLs(dictionary!)
}
return dictionary!
}
}
private func kf_setBackgroundWebURLs(URLs: NSMutableDictionary) {
objc_setAssociatedObject(self, &lastBackgroundURLKey, URLs, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
}
}
// MARK: - Deprecated
public extension UIButton {
@availability(*, deprecated=1.2, message="Use -kf_setImageWithURL:forState:placeholderImage:optionsInfo: instead.")
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: nil)
}
@availability(*, deprecated=1.2, message="Use -kf_setImageWithURL:forState:placeholderImage:optionsInfo:completionHandler: instead.")
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: completionHandler)
}
@availability(*, deprecated=1.2, message="Use -kf_setImageWithURL:forState:placeholderImage:optionsInfo:progressBlock:completionHandler: instead.")
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: progressBlock, completionHandler: completionHandler)
}
@availability(*, deprecated=1.2, message="Use -kf_setBackgroundImageWithURL:forState:placeholderImage:optionsInfo: instead.")
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: nil)
}
@availability(*, deprecated=1.2, message="Use -kf_setBackgroundImageWithURL:forState:placeholderImage:optionsInfo:completionHandler: instead.")
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: completionHandler)
}
@availability(*, deprecated=1.2, message="Use -kf_setBackgroundImageWithURL:forState:placeholderImage:optionsInfo:progressBlock:completionHandler: instead.")
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: progressBlock, completionHandler: completionHandler)
}
}
|
mit
|
3692a87a809745609162ff5e666a1c41
| 51.97449 | 242 | 0.649941 | 5.909505 | false | false | false | false |
tectijuana/patrones
|
Bloque1SwiftArchivado/PracticasSwift/CarlosGastelum/encontrarLadosDelTriangulo.swift
|
1
|
2078
|
/*
Nombre del programa: ...................Problema:
12. Un triángulo rectángulo tiene un ángulo de 42° 25" y el lado opuesto a este ángulo mide 25.4 cm. Encontrar los otros lados del triángulo.
Creado por: .......... Gastelum Nieves Carlos
No Control: .................................................14210456
Fecha ......................................................17-02-2017
*/
//Librería
import Foundation
//Declaramos los datos del Triangulo
var anguA : Float = 42 + (25/60) //comvertimos de minutos a grados
var anguC : Float = 90 //Al ser triángulo rectángulo al menos uno de los ángulos será de 90°
var ladA : Float = 25.4
var anguB = 180 - (anguA+anguC) //Se restan los otros ángulos a 180 para obtener el ángulo faltante
var ladB = ladA / sin(anguA * Float.pi / 180) //Se divide el Lado A por el seno del ángulo A para obtener la hipotenusa
var ladC = sqrt((pow(ladB,2)) - (pow(ladA,2 ))) //Se despeja el teorema de Pitágoras para calcular el último lado
//Se guarda en una variable el texto con el problema a resolver
let problema = " Problema: " + "\n" +
"12. Un triángulo rectángulo tiene un ángulo de 42° 25\" y el lado opuesto a este ángulo mide 25.4 cm. Encontrar los otros lados del triángulo." + "\n \n"
//En otra variable diferente se guardan los datos para desplegarse
let datos = "Datos: " + "\n" + "Lado A: \(ladA)" + "\n" + "Ángulo A: \(anguA)°" + "\n" + "\n" + "Ángulo C = 90°" + "\n \n"
//gardamos la variable el procedimiento
let procedimiento = "Procedimiento: " + "\n" +
"Ángulo B = 180 - (\(anguA)° + \(anguC)°)" +
"\n" + "Lado B = \(ladA)/sen(\(sin(anguA * Float.pi / 180)))" + "\n" +
"Lado C = v((\(ladB))^2-(\(ladA))^2)" + "\n \n"
//se van guardando los resultados en una variable distinta
let resultado = "Resultado: " + "\n" +
"Lado A: \(ladA) cm" + "\n" +
"Lado B: \(ladB) cm" + "\n" +
"Lado C: \(ladC) cm"
// desplegamos las variables donde guardamos el texto
print(problema,datos,procedimiento,resultado)
|
gpl-3.0
|
7b76abdd77b5420bdbf7dda43f568d38
| 46.761905 | 154 | 0.599121 | 2.868347 | false | false | false | false |
DenHeadless/DTCollectionViewManager
|
Example/Examples/FeedViewController.swift
|
1
|
3939
|
//
// FeedViewController.swift
// Example
//
// Created by Denys Telezhkin on 19.08.2020.
// Copyright © 2020 Denys Telezhkin. All rights reserved.
//
import UIKit
import DTCollectionViewManager
class FeedViewController: UIViewController, DTCollectionViewManageable {
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
manager.register(PostCell.self) { [weak self] mapping in
mapping.sizeForCell { _, _ in
self?.itemSize(for: self?.view.frame.size.width ?? .zero) ?? .zero
}
mapping.willDisplay { _, _, indexPath in
if indexPath.item > (self?.numberOfItems ?? 0) - 5 {
// Showing last 5 posts, time to start loading new ones
self?.loadNextPage()
}
}
}
manager.register(ActivityIndicatorCell.self, for: ActivityIndicatorCell.Model.self) { [weak self] mapping in
mapping.sizeForCell { _, _ in
CGSize(width: self?.view.frame.size.width ?? 0, height: 50)
}
} handler: { _, _, _ in }
manager.targetContentOffsetForProposedContentOffset { [weak self] point in
// Restoring content offset to value, which was before rotation started and we updated layout
self?.expectedTargetContentOffset ?? point
}
let refreshControl = UIRefreshControl()
refreshControl.addAction(UIAction(handler: { [weak self] _ in
// Emulate refreshing feed
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self?.expectedTargetContentOffset = .zero
self?.setInitialPage()
self?.collectionView.refreshControl?.endRefreshing()
}
}), for: .valueChanged)
collectionView.refreshControl = refreshControl
setInitialPage()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animate { [weak self] context in
self?.expectedTargetContentOffset = self?.collectionView.contentOffset ?? .zero
self?.updateLayout(size: size, animated: true)
} completion: { _ in }
}
private func setInitialPage() {
manager.memoryStorage.setItems((0...25).map { _ in Post() })
manager.memoryStorage.addItem(ActivityIndicatorCell.Model())
}
private func loadNextPage() {
guard !isLoadingNextPage else { return }
isLoadingNextPage = true
// Emulate loading next page
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in
self?.expectedTargetContentOffset = self?.collectionView.contentOffset ?? .zero
try? self?.manager.memoryStorage.insertItems((0...25).map { _ in Post() }, at: IndexPath(item: (self?.numberOfItems ?? 0) - 1, section: 0))
self?.isLoadingNextPage = false
}
}
private var isLoadingNextPage: Bool = false
private var numberOfItems : Int {
manager.memoryStorage.numberOfItems(inSection: 0)
}
private var expectedTargetContentOffset: CGPoint = .zero
private func itemSize(for width: CGFloat) -> CGSize {
if width > 500 {
// Looks like wide-enough size for 2 columns
return CGSize(width: (width - 30) / 2.0, height: 200)
} else {
// Only single column would fit
return CGSize(width: width - 20, height: 200)
}
}
private func updateLayout(size: CGSize, animated: Bool) {
let layout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = 10
layout.minimumLineSpacing = 10
layout.itemSize = itemSize(for: size.width)
collectionView.setCollectionViewLayout(layout, animated: animated)
}
}
|
mit
|
dee43dfc4f89f261a5623bcc65720a65
| 38.777778 | 152 | 0.616811 | 5.08129 | false | false | false | false |
jshultz/download_images_from_web
|
Downloading_Web_Content/ViewController.swift
|
1
|
2839
|
//
// ViewController.swift
// Downloading_Web_Content
//
// Created by Jason Shultz on 11/8/15.
// Copyright © 2015 HashRocket. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var image: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// create a url
let url = NSURL(string: "https://upload.wikimedia.org/wikipedia/commons/6/6a/Johann_Sebastian_Bach.jpg")
// make a url request. use ! because we know that the url is a url
let urlRequest = NSURLRequest(URL: url!)
// typically, you will use asynchronous requests.
NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
if error != nil {
print(error)
} else {
if let bach = UIImage(data: data!) {
// we comment this out because we are testing the code below where we are getting the image from the file system instead.
// self.image.image = bach
// create variable we will store path into.
var documentsDirectory:String?
// create a variable, then search for the user's documents directory.
var paths:[AnyObject] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
// did we find a directory? of course we did.
if paths.count > 0 {
// take the path, set it as a string and store it in the variable.
documentsDirectory = paths[0] as? String
// now we can create a save path.
let savePath = documentsDirectory! + "/bach.jpg"
// now we actually save the file.
NSFileManager.defaultManager().createFileAtPath(savePath, contents: data, attributes: nil)
// now we are going to pull it from the file system.
self.image.image = UIImage(named: savePath)
}
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
bf6dc0edbffca9103c5ac48e7f765ed5
| 35.384615 | 165 | 0.511628 | 6.012712 | false | false | false | false |
ngageoint/mage-ios
|
Mage/BaseFieldView.swift
|
1
|
5799
|
//
// BaseFieldView.swift
// MAGE
//
// Created by Daniel Barela on 5/13/20.
// Copyright © 2020 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
import MaterialComponents.MDCTextField;
class BaseFieldView : UIView {
var didSetupConstraints = false;
internal var field: [String: Any]!;
internal weak var delegate: (ObservationFormFieldListener & FieldSelectionDelegate)?;
internal var fieldValueValid: Bool! = false;
internal var value: Any?;
internal var editMode: Bool = true;
internal var scheme: MDCContainerScheming?;
private lazy var fieldSelectionCoordinator: FieldSelectionCoordinator? = {
var fieldSelectionCoordinator: FieldSelectionCoordinator? = nil;
if let delegate: FieldSelectionDelegate = delegate {
fieldSelectionCoordinator = FieldSelectionCoordinator(field: field, formField: self, delegate: delegate, scheme: self.scheme);
}
return fieldSelectionCoordinator;
}();
lazy var fieldNameSpacerView: UIView = {
let fieldNameSpacerView = UIView(forAutoLayout: ());
fieldNameSpacerView.addSubview(fieldNameLabel);
fieldNameLabel.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16));
return fieldNameSpacerView;
}()
lazy var fieldNameLabel: UILabel = {
let label = UILabel(forAutoLayout: ());
label.text = "\(field[FieldKey.title.key] as? String ?? "")\((editMode && (field[FieldKey.required.key] as? Bool ?? false)) ? " *" : "")";
label.accessibilityLabel = "\((field[FieldKey.name.key] as? String ?? "")) Label";
return label;
}()
lazy var fieldValue: UILabel = {
let label = UILabel(forAutoLayout: ());
label.accessibilityLabel = "\((field[FieldKey.name.key] as? String ?? "")) Value"
label.numberOfLines = 0;
return label;
}()
lazy var viewStack: UIStackView = {
let stackView = UIStackView(forAutoLayout: ());
stackView.axis = .vertical
stackView.alignment = .fill
stackView.spacing = 8
stackView.distribution = .fill
stackView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 8, leading: 8, bottom: 0, trailing: 8)
stackView.isLayoutMarginsRelativeArrangement = false;
return stackView;
}()
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
init(field: [String: Any], delegate: (ObservationFormFieldListener & FieldSelectionDelegate)?, value: Any?, editMode: Bool = true) {
super.init(frame: CGRect.zero);
self.configureForAutoLayout();
self.editMode = editMode;
self.field = field;
self.delegate = delegate;
self.value = value;
self.accessibilityLabel = "Field View \((field[FieldKey.name.key] as? String ?? ""))"
self.addSubview(viewStack);
if (!editMode) {
viewStack.spacing = 0;
}
}
func applyTheme(withScheme scheme: MDCContainerScheming?) {
self.scheme = scheme;
fieldSelectionCoordinator?.applyTheme(withScheme: scheme)
fieldValue.textColor = scheme?.colorScheme.onSurfaceColor;
fieldValue.font = scheme?.typographyScheme.body1;
fieldNameLabel.textColor = scheme?.colorScheme.onSurfaceColor.withAlphaComponent(0.6);
if let font = scheme?.typographyScheme.body1 {
let smallFont = font.withSize(font.pointSize * 0.8);
fieldNameLabel.font = smallFont;
}
}
override func updateConstraints() {
if (!didSetupConstraints) {
viewStack.autoPinEdgesToSuperviewEdges();
if (!editMode) {
fieldNameLabel.autoSetDimension(.height, toSize: 16);
}
didSetupConstraints = true;
}
super.updateConstraints();
}
func setPlaceholder(textField: MDCFilledTextField) {
textField.placeholder = field[FieldKey.title.key] as? String
if ((field[FieldKey.required.key] as? Bool) == true) {
textField.placeholder = (textField.placeholder ?? "") + " *"
}
textField.label.text = textField.placeholder;
}
func setPlaceholder(textArea: MDCFilledTextArea) {
textArea.placeholder = field[FieldKey.title.key] as? String
if ((field[FieldKey.required.key] as? Bool) == true) {
textArea.placeholder = (textArea.placeholder ?? "") + " *"
}
textArea.label.text = textArea.placeholder;
}
func setValue(_ value: Any?) {
preconditionFailure("This method must be overridden");
}
func getErrorMessage() -> String {
preconditionFailure("This method must be overridden");
}
func getValue() -> Any? {
return value;
}
func isEmpty() -> Bool {
return false;
}
func setValid(_ valid: Bool) {
fieldValueValid = valid;
}
func isValid() -> Bool {
return isValid(enforceRequired: true);
}
func isValid(enforceRequired: Bool = false) -> Bool {
if ((field[FieldKey.required.key] as? Bool) == true && enforceRequired && isEmpty()) {
return false;
}
return true;
}
func addTapRecognizer() -> UIView {
let tapView = UIView(forAutoLayout: ());
self.addSubview(tapView);
tapView.autoPinEdgesToSuperviewEdges();
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
tapView.addGestureRecognizer(tapGesture)
return tapView;
}
@objc func handleTap() {
fieldSelectionCoordinator?.fieldSelected();
}
}
|
apache-2.0
|
5111738d8b7a0d07402870f632777f09
| 34.790123 | 146 | 0.629527 | 4.892827 | false | false | false | false |
edragoev1/pdfjet
|
Sources/PDFjet/BarCode2D.swift
|
1
|
10584
|
/**
* BarCode2D.swift
*
Copyright 2020 Innovatics Inc.
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
/**
* Used to create PDF417 2D barcodes.
*
* Please see Example_12.
*/
public class BarCode2D : Drawable {
private static let ALPHA = 0x08
private static let LOWER = 0x04
private static let MIXED = 0x02
private static let PUNCT = 0x01
private static let LATCH_TO_LOWER = 27
private static let SHIFT_TO_ALPHA = 27
private static let LATCH_TO_MIXED = 28
private static let LATCH_TO_ALPHA = 28
private static let SHIFT_TO_PUNCT = 29
private var x1: Float = 0.0
private var y1: Float = 0.0
// Critical defaults!
private var w1: Float = 0.75
private var h1: Float = 0.0
private var rows = 50
private var cols = 18
private var codewords = [Int]()
private var str: String = ""
/**
* Constructor for 2D barcodes.
*
* @param str the specified string.
*/
public init(_ str: String) {
self.str = str
self.h1 = 3 * w1
self.codewords = [Int](repeating: 0, count: rows * (cols + 2))
var lfBuffer = [Int](repeating: 0, count: rows)
var lrBuffer = [Int](repeating: 0, count: rows)
var buffer = [Int](repeating: 0, count: (rows * cols))
// Left and right row indicators - see page 34 of the ISO specification
let compression = 5 // Compression Level
var k = 1
for i in 0..<rows {
var lf = 0
var lr = 0
let cf = 30 * (i / 3)
if k == 1 {
lf = cf + ((rows - 1) / 3)
lr = cf + (cols - 1)
}
else if k == 2 {
lf = cf + 3*compression + ((rows - 1) % 3)
lr = cf + ((rows - 1) / 3)
}
else if k == 3 {
lf = cf + (cols - 1)
lr = cf + 3*compression + ((rows - 1) % 3)
}
lfBuffer[i] = lf
lrBuffer[i] = lr
k += 1
if k == 4 {
k = 1
}
}
let dataLen = (rows * cols) - ECC_L5.table.count
for i in 0..<dataLen {
buffer[i] = 900 // The default pad codeword
}
buffer[0] = dataLen
addData(&buffer, dataLen)
addECC(&buffer)
for i in 0..<rows {
let index = (cols + 2) * i
codewords[index] = lfBuffer[i]
for j in 0..<cols {
codewords[index + j + 1] = buffer[cols*i + j]
}
codewords[index + cols + 1] = lrBuffer[i]
}
}
public func setPosition(_ x: Float, _ y: Float) {
setLocation(x, y)
}
/**
* Sets the location of this barcode on the page.
*
* @param x the x coordinate of the top left corner of the barcode.
* @param y the y coordinate of the top left corner of the barcode.
*/
public func setLocation(_ x: Float, _ y: Float) {
self.x1 = x
self.y1 = y
}
/**
* Sets the module width for this barcode.
* This changes the barcode size while preserving the aspect.
* Use value between 0.5f and 0.75f.
* If the value is too small some scanners may have difficulty reading the barcode.
*
* @param width the module width of the barcode.
*/
public func setModuleWidth(_ width: Float) {
self.w1 = width
self.h1 = 3 * w1
}
/**
* Draws this barcode on the specified page.
*
* @param page the page to draw this barcode on.
* @return x and y coordinates of the bottom right corner of this component.
* @throws Exception
*/
@discardableResult
public func drawOn(_ page: Page?) -> [Float] {
return drawPdf417(page!)
}
private func textToArrayOfIntegers() -> [Int] {
var list = [Int]()
var currentMode = BarCode2D.ALPHA
for scalar in str.unicodeScalars {
if scalar == Unicode.Scalar(0x20) {
list.append(26)
continue
}
let value = TextCompact.TABLE[Int(scalar.value)][1]
let mode = TextCompact.TABLE[Int(scalar.value)][2]
if mode == currentMode {
list.append(value)
}
else {
if mode == BarCode2D.ALPHA && currentMode == BarCode2D.LOWER {
list.append(BarCode2D.SHIFT_TO_ALPHA)
list.append(value)
}
else if mode == BarCode2D.ALPHA && currentMode == BarCode2D.MIXED {
list.append(BarCode2D.LATCH_TO_ALPHA)
list.append(value)
currentMode = mode
}
else if mode == BarCode2D.LOWER && currentMode == BarCode2D.ALPHA {
list.append(BarCode2D.LATCH_TO_LOWER)
list.append(value)
currentMode = mode
}
else if mode == BarCode2D.LOWER && currentMode == BarCode2D.MIXED {
list.append(BarCode2D.LATCH_TO_LOWER)
list.append(value)
currentMode = mode
}
else if mode == BarCode2D.MIXED && currentMode == BarCode2D.ALPHA {
list.append(BarCode2D.LATCH_TO_MIXED)
list.append(value)
currentMode = mode
}
else if mode == BarCode2D.MIXED && currentMode == BarCode2D.LOWER {
list.append(BarCode2D.LATCH_TO_MIXED)
list.append(value)
currentMode = mode
}
else if mode == BarCode2D.PUNCT && currentMode == BarCode2D.ALPHA {
list.append(BarCode2D.SHIFT_TO_PUNCT)
list.append(value)
}
else if mode == BarCode2D.PUNCT && currentMode == BarCode2D.LOWER {
list.append(BarCode2D.SHIFT_TO_PUNCT)
list.append(value)
}
else if mode == BarCode2D.PUNCT && currentMode == BarCode2D.MIXED {
list.append(BarCode2D.SHIFT_TO_PUNCT)
list.append(value)
}
}
}
return list
}
private func addData(_ buffer: inout [Int], _ dataLen: Int) {
let list = textToArrayOfIntegers()
// buffer index = 1 to skip the Symbol Length Descriptor
var bi = 1
var hi = 0
var lo = 0
var i = 0
while i < list.count {
hi = list[i]
if i + 1 == list.count {
lo = BarCode2D.SHIFT_TO_PUNCT // Pad
} else {
lo = list[i + 1]
}
bi += 1
if bi == dataLen {
break
}
buffer[bi] = 30*hi + lo
i += 2
}
}
private func addECC(_ buf: inout [Int]) {
var ecc = [Int](repeating: 0, count: ECC_L5.table.count)
var t1 = 0
var t2 = 0
var t3 = 0
let dataLen = buf.count - ecc.count
for i in 0..<dataLen {
t1 = (buf[i] + ecc[ecc.count - 1]) % 929
var j = ecc.count - 1
while j > 0 {
t2 = (t1 * ECC_L5.table[j]) % 929
t3 = 929 - t2
ecc[j] = (ecc[j - 1] + t3) % 929
j -= 1
}
t2 = (t1 * ECC_L5.table[0]) % 929
t3 = 929 - t2
ecc[0] = t3 % 929
}
for i in 0..<ecc.count {
if ecc[i] != 0 {
buf[(buf.count - 1) - i] = 929 - ecc[i]
}
}
}
private func drawPdf417(_ page: Page) -> [Float] {
var x: Float = x1
var y: Float = y1
let startSymbol = [8, 1, 1, 1, 1, 1, 1, 3]
for i in 0..<startSymbol.count {
let n = startSymbol[i]
if i%2 == 0 {
drawBar(page, x, y, Float(n) * w1, Float(rows) * h1)
}
x += Float(n) * w1
}
x1 = x
var k = 1 // Cluster index
for i in 0..<codewords.count {
let row = codewords[i]
let symbol = String(PDF417.TABLE[row][k])
for j in 0..<8 {
let n = Array(symbol.unicodeScalars)[j].value - 0x30
if j%2 == 0 {
drawBar(page, x, y, Float(n) * w1, h1)
}
x += Float(n) * w1
}
if i == codewords.count - 1 {
break
}
if (i + 1) % (cols + 2) == 0 {
x = x1
y += h1
k += 1
if k == 4 {
k = 1
}
}
}
y = y1
let endSymbol = [7, 1, 1, 3, 1, 1, 1, 2, 1]
for i in 0..<endSymbol.count {
let n = endSymbol[i]
if i%2 == 0 {
drawBar(page, x, y, Float(n) * w1, Float(rows) * h1)
}
x += Float(n) * w1
}
return [x, y + h1*Float(rows)]
}
private func drawBar(
_ page: Page,
_ x: Float,
_ y: Float,
_ w: Float, // Bar width
_ h: Float) {
page.setPenWidth(w)
page.moveTo(x + w/2, y)
page.lineTo(x + w/2, y + h)
page.strokePath()
}
} // End of BarCode2D.swift
|
mit
|
ac18873a4a56d21498f65b0d17b156da
| 29.413793 | 88 | 0.487434 | 3.884037 | false | false | false | false |
HTWDD/HTWDresden-iOS
|
HTWDD/Main Categories/General/AppCoordinator.swift
|
1
|
6952
|
//
// AppCoordinator.swift
// HTWDD
//
// Created by Fabian Ehlert on 13.10.17.
// Copyright © 2017 HTW Dresden. All rights reserved.
//
import UIKit
import RxSwift
import SideMenu
class AppCoordinator: Coordinator {
private var window: UIWindow
private let tabBarController = TabBarController()
var rootViewController: UIViewController {
return self.tabBarController
// return self.rootNavigationController
}
lazy var childCoordinators: [Coordinator] = [
self.schedule,
self.exams,
self.grades,
self.canteen,
self.settings,
self.management,
self.campusPlan
]
private let navigationController: UINavigationController = UIStoryboard(name: "SideMenu", bundle: nil).instantiateViewController(withIdentifier: "MainNavigation") as! SideMenuContainerNavigationController
var rootNavigationController: SideMenuContainerNavigationController {
return self.navigationController as! SideMenuContainerNavigationController
}
let appContext = AppContext()
private let persistenceService = PersistenceService()
private lazy var dashboard = DashboardCoordinator(context: appContext)
private lazy var timetable = TimetableCoordinator(context: appContext)
private lazy var schedule = ScheduleCoordinator(context: appContext)
private lazy var roomOccupancy = RoomOccupancyCoordinator(context: appContext)
private lazy var exams = ExamsCoordinator(context: appContext)
private lazy var grades = GradeCoordinator(context: appContext)
private lazy var canteen = CanteenCoordinator(context: appContext)
private lazy var settings = SettingsCoordinator(context: appContext, delegate: self)
private lazy var management = ManagementCoordinator(context: appContext)
private lazy var campusPlan = CampusPlanCoordinator(context: appContext)
private let disposeBag = DisposeBag()
// MARK: - Lifecycle
init(window: UIWindow) {
self.window = window
self.rootNavigationController.coordinator = self
self.window.rootViewController = self.rootNavigationController
self.window.tintColor = UIColor.htw.blue
self.window.makeKeyAndVisible()
if #available(iOS 13.0, *) {
let app = UINavigationBarAppearance()
app.backgroundColor = .blue
self.rootNavigationController.navigationController?.navigationBar.scrollEdgeAppearance = app
}
goTo(controller: .dashboard)
if UserDefaults.standard.needsOnboarding {
self.showOnboarding(animated: false)
}
}
private func injectAuthentication(schedule: ScheduleService.Auth?, grade: GradeService.Auth?) {
self.schedule.auth = schedule
}
private func showOnboarding(animated: Bool) {
rootNavigationController.present(OnboardingCoordinator(context: appContext).start(), animated: animated, completion: nil)
}
private func loadPersistedAuth(completion: @escaping (ScheduleService.Auth?, GradeService.Auth?) -> Void) {
self.persistenceService.load()
.take(1)
.subscribe(onNext: { res in
completion(res.schedule, res.grades)
}, onError: { _ in
completion(nil, nil)
})
.disposed(by: self.disposeBag)
}
}
// MARK: - Routing
extension AppCoordinator {
func selectChild(`for` url: URL) {
guard let route = url.host?.removingPercentEncoding else { return }
self.selectChild(coordinator: CoordinatorRoute(rawValue: route))
}
func selectChild(coordinator: CoordinatorRoute?) {
guard let coordinator = coordinator else { return }
switch coordinator {
case .schedule:
// Dismiss any ViewController presented on tabBarController
if let presented = self.tabBarController.presentedViewController {
presented.dismiss(animated: false)
}
self.tabBarController.selectedIndex = 0
case .scheduleToday:
// Dismiss any ViewController presented on tabBarController
if let presented = self.tabBarController.presentedViewController {
presented.dismiss(animated: false)
}
self.schedule.jumpToToday(animated: false)
self.tabBarController.selectedIndex = 0
default:
break
}
}
}
// MARK: - Data handling
extension AppCoordinator: SettingsCoordinatorDelegate {
func deleteAllData() {
ExamRealm.clear()
RoomRealm.clear()
UserDefaults.standard.apply {
$0.needsOnboarding = true
$0.analytics = false
$0.crashlytics = false
}
self.persistenceService.clear()
self.schedule.auth = nil
KeychainService.shared.removeAllKeys()
goTo(controller: .dashboard)
self.showOnboarding(animated: true)
}
}
// MARK: - Controller routing
extension AppCoordinator {
/// # Routing to UIViewController
func goTo(controller: CoordinatorRoute, animated: Bool = false) {
let viewController: UIViewController
switch controller {
case .dashboard:
viewController = (dashboard.rootViewController as! DashboardViewController).also {
$0.appCoordinator = self
}
case .schedule,
.scheduleToday:
viewController = timetable.start()
case .roomOccupancy:
viewController = (roomOccupancy.rootViewController as! RoomOccupancyViewController).also {
$0.appCoordinator = self
}
case .roomOccupancyDetail(let room):
viewController = roomOccupancy.getDetailRoomOccupancyViewController(with: room)
case .exams:
viewController = exams.start()
case .grades:
viewController = grades.rootViewController
case .canteen:
viewController = (canteen.rootViewController as! CanteenViewController).also {
$0.appCoordinator = self
}
case .meal(let canteenDetail):
viewController = canteen.getMealsTabViewController(for: canteenDetail)
case .settings:
viewController = settings.start()
case .management:
viewController = management.rootViewController
case .campusPlan:
viewController = campusPlan.rootViewController
}
if rootNavigationController.viewControllers.contains(viewController) {
rootNavigationController.popToViewController(viewController, animated: animated)
} else {
rootNavigationController.pushViewController(viewController, animated: animated)
}
}
}
|
gpl-2.0
|
f8ab530ac24ccd36389b277f112cfbcd
| 35.39267 | 208 | 0.651705 | 5.413551 | false | false | false | false |
alexoliveira/SwiftBreakout
|
SwiftBreakout/SwiftBreakout/GameViewController.swift
|
1
|
2207
|
//
// GameViewController.swift
// SwiftBreakout
//
// Created by Steven Veshkini on 9/27/14.
// Copyright (c) 2014 swiftbreakout. All rights reserved.
//
import UIKit
import SpriteKit
extension SKNode {
class func unarchiveFromFile(file : NSString) -> SKNode? {
if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
var sceneData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe, error: nil)
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene
archiver.finishDecoding()
return scene
} else {
return nil
}
}
}
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
// Configure the view.
let skView = self.view as SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
scene.size = self.view.frame.size
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.toRaw())
} else {
return Int(UIInterfaceOrientationMask.All.toRaw())
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
|
mit
|
c661ccb06479dabd2c0bd393eb9b1a9f
| 30.528571 | 110 | 0.625283 | 5.503741 | false | false | false | false |
delbert06/DYZB
|
DYZB/DYZB/Common.swift
|
1
|
323
|
//
// Common.swift
// DYZB
//
// Created by 胡迪 on 2016/10/18.
// Copyright © 2016年 D.Huhu. All rights reserved.
//
import UIKit
let kStautusBarH : CGFloat = 20
let kNavigationBarH : CGFloat = 44
let kTabbarH : CGFloat = 44
let kScreenW = UIScreen.main.bounds.width
let kScreenH = UIScreen.main.bounds.height
|
mit
|
17d1d00912a679c50efbafd80036b5d3
| 17.588235 | 50 | 0.705696 | 3.128713 | false | false | false | false |
russbishop/swift
|
stdlib/public/SDK/Foundation/UUID.swift
|
1
|
4839
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
import Darwin.uuid
/// Represents UUID strings, which can be used to uniquely identify types, interfaces, and other items.
@available(OSX 10.8, iOS 6.0, *)
public struct UUID : ReferenceConvertible, Hashable, Equatable, CustomStringConvertible {
public typealias ReferenceType = NSUUID
public private(set) var uuid: uuid_t = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
/* Create a new UUID with RFC 4122 version 4 random bytes */
public init() {
withUnsafeMutablePointer(&uuid) {
uuid_generate_random(unsafeBitCast($0, to: UnsafeMutablePointer<UInt8>.self))
}
}
private init(reference: NSUUID) {
var bytes: uuid_t = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
withUnsafeMutablePointer(&bytes) {
reference.getBytes(unsafeBitCast($0, to: UnsafeMutablePointer<UInt8>.self))
}
uuid = bytes
}
/// Create a UUID from a string such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F".
///
/// Returns nil for invalid strings.
public init?(uuidString string: String) {
let res = withUnsafeMutablePointer(&uuid) {
return uuid_parse(string, unsafeBitCast($0, to: UnsafeMutablePointer<UInt8>.self))
}
if res != 0 {
return nil
}
}
/// Create a UUID from a `uuid_t`.
public init(uuid: uuid_t) {
self.uuid = uuid
}
/// Returns a string created from the UUID, such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
public var uuidString: String {
var bytes: uuid_string_t = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
var localValue = uuid
return withUnsafeMutablePointers(&localValue, &bytes) { val, str -> String in
uuid_unparse(unsafeBitCast(val, to: UnsafePointer<UInt8>.self), unsafeBitCast(str, to: UnsafeMutablePointer<Int8>.self))
return String(cString: unsafeBitCast(str, to: UnsafePointer<CChar>.self), encoding: .utf8)!
}
}
public var hashValue: Int {
var localValue = uuid
return withUnsafeMutablePointer(&localValue) {
return Int(bitPattern: CFHashBytes(unsafeBitCast($0, to: UnsafeMutablePointer<UInt8>.self), CFIndex(sizeof(uuid_t.self))))
}
}
public var description: String {
return uuidString
}
public var debugDescription: String {
return description
}
// MARK: - Bridging Support
private var reference: NSUUID {
var bytes = uuid
return withUnsafePointer(&bytes) {
return NSUUID(uuidBytes: unsafeBitCast($0, to: UnsafePointer<UInt8>.self))
}
}
}
public func ==(lhs: UUID, rhs: UUID) -> Bool {
return lhs.uuid.0 == rhs.uuid.0 &&
lhs.uuid.1 == rhs.uuid.1 &&
lhs.uuid.2 == rhs.uuid.2 &&
lhs.uuid.3 == rhs.uuid.3 &&
lhs.uuid.4 == rhs.uuid.4 &&
lhs.uuid.5 == rhs.uuid.5 &&
lhs.uuid.6 == rhs.uuid.6 &&
lhs.uuid.7 == rhs.uuid.7 &&
lhs.uuid.8 == rhs.uuid.8 &&
lhs.uuid.9 == rhs.uuid.9 &&
lhs.uuid.10 == rhs.uuid.10 &&
lhs.uuid.11 == rhs.uuid.11 &&
lhs.uuid.12 == rhs.uuid.12 &&
lhs.uuid.13 == rhs.uuid.13 &&
lhs.uuid.14 == rhs.uuid.14 &&
lhs.uuid.15 == rhs.uuid.15
}
extension UUID : _ObjectiveCBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSUUID {
return reference
}
public static func _forceBridgeFromObjectiveC(_ x: NSUUID, result: inout UUID?) {
if !_conditionallyBridgeFromObjectiveC(x, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSUUID, result: inout UUID?) -> Bool {
result = UUID(reference: input)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSUUID?) -> UUID {
var result: UUID? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
|
apache-2.0
|
840383c535084679ef048d6c454358b8
| 34.844444 | 146 | 0.585452 | 3.982716 | false | false | false | false |
mownier/photostream
|
Photostream/Services/Models/Activity.swift
|
1
|
2761
|
//
// Activity.swift
// Photostream
//
// Created by Mounir Ybanez on 22/12/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
import Firebase
enum ActivityType {
case unknown
case like(String, String) // user id, post id
case comment(String, String, String) // user id, comment id, post id
case post(String, String) // user id, post id
case follow(String) // user id
}
struct Activity {
var id: String = ""
var timestamp: Double = 0
var type: ActivityType = .unknown
}
struct ActivityList {
var activities = [Activity]()
var posts = [String: Post]()
var users = [String: User]()
var comments = [String: Comment]()
var following = [String]()
var count: Int {
return activities.count
}
}
extension Activity: SnapshotParser {
init(with snapshot: DataSnapshot, exception: String...) {
self.init()
var userId = ""
var postId = ""
var commentId = ""
if snapshot.hasChild("id") && !exception.contains("id") {
id = snapshot.childSnapshot(forPath: "id").value as! String
}
if snapshot.hasChild("timestamp") && !exception.contains("timestamp") {
timestamp = snapshot.childSnapshot(forPath: "timestamp").value as! Double
timestamp = timestamp / 1000
}
if snapshot.hasChild("trigger_by") && !exception.contains("trigger_by") {
userId = snapshot.childSnapshot(forPath: "trigger_by").value as! String
}
if snapshot.hasChild("post_id") && !exception.contains("post_id") {
postId = snapshot.childSnapshot(forPath: "post_id").value as! String
}
if snapshot.hasChild("comment_id") && !exception.contains("comment_id") {
commentId = snapshot.childSnapshot(forPath: "comment_id").value as! String
}
if snapshot.hasChild("type") && !exception.contains("type") {
let typeString = snapshot.childSnapshot(forPath: "type").value as! String
switch typeString.lowercased() {
case "like" where !userId.isEmpty && !postId.isEmpty:
type = .like(userId, postId)
case "comment" where !userId.isEmpty && !commentId.isEmpty && !postId.isEmpty:
type = .comment(userId, commentId, postId)
case "post" where !userId.isEmpty && !postId.isEmpty:
type = .post(userId, postId)
case "follow" where !userId.isEmpty:
type = .follow(userId)
default:
break
}
}
}
}
|
mit
|
7572f56171d69f3cf1ce79f97ac39253
| 29.32967 | 90 | 0.556159 | 4.539474 | false | false | false | false |
peferron/algo
|
EPI/Linked Lists/Merge two sorted lists/swift/main.swift
|
1
|
1096
|
public class Node {
public let value: Int
public var next: Node?
public init(value: Int) {
self.value = value
}
public func merge(_ other: Node) -> Node {
let tempHead = Node(value: 0)
var tail = tempHead
var remainingSelf: Node? = self
var remainingOther: Node? = other
while let rs = remainingSelf, let ro = remainingOther {
if rs.value < ro.value {
tail.next = rs
remainingSelf = rs.next
} else {
tail.next = ro
remainingOther = ro.next
}
tail = tail.next!
}
// Append the remaining nodes from either A or B (one of them must be nil).
tail.next = remainingSelf ?? remainingOther
return tempHead.next!
}
// Recursive implementation.
// public func merge(_ other: Node) -> Node {
// let (first, second) = self.value < other.value ? (self, other) : (other, self)
// first.next = first.next?.merge(second) ?? second
// return first
// }
}
|
mit
|
15064c60a7e4ab13fbc8524c328086ec
| 27.842105 | 89 | 0.532847 | 4.23166 | false | false | false | false |
loiwu/SCoreData
|
Dog Walk/Dog Walk/CoreDataStack.swift
|
1
|
2397
|
//
// CoreDataStack.swift
// Dog Walk
//
// Created by loi on 1/26/15.
// Copyright (c) 2015 GWrabbit. All rights reserved.
//
import CoreData
class CoreDataStack {
let context:NSManagedObjectContext
let psc:NSPersistentStoreCoordinator
let model:NSManagedObjectModel
let store:NSPersistentStore?
init() {
// 1 - load the managed object model from disk into a NSManagedObjectModel object.
// getting a URL to the momd directory that contains the compiled version of the .xcdatamodeld file.
let bundle = NSBundle.mainBundle()
let modelURL = bundle.URLForResource("Dog Walk", withExtension: "momd")
model = NSManagedObjectModel(contentsOfURL: modelURL!)!
// 2 - the persistent store coordinator mediates between the persistent store and NSManagedObjectModel
psc = NSPersistentStoreCoordinator(managedObjectModel: model)
// 3 - The NSManagedObjectContext takes no arguments to initialize.
context = NSManagedObjectContext()
context.persistentStoreCoordinator = psc
// 4 - the persistent store coordinator hands you an NSPersistentStore object as a side effect of attaching a persistent store type.
// simply have to specify the store type (NSSQLiteStoreType in this case), the URL location of the store file and some configuration options.
let documentURL = applicationDocumentsDirectory()
let storeURL = documentURL.URLByAppendingPathComponent("Dog Walk")
let options = [NSMigratePersistentStoresAutomaticallyOption: true]
var error: NSError? = nil
store = psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: options, error: &error)
if store == nil {
println("Error adding persistent store: \(error)")
abort()
}
}
func saveContext() {
var error: NSError? = nil
if context.hasChanges && !context.save(&error) {
println("Could not save: \(error), \(error?.userInfo)")
}
}
func applicationDocumentsDirectory() -> NSURL {
let fileManager = NSFileManager.defaultManager()
let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) as [NSURL]
return urls[0]
}
}
|
mit
|
2c6533438a1a246cd04bbca3e45a6abb
| 38.295082 | 149 | 0.665832 | 5.613583 | false | false | false | false |
codeliling/DesignResearch
|
DesignBase/DesignBase/Controllers/RelationCaseViewController.swift
|
1
|
6305
|
//
// RelationCaseViewController.swift
// DesignBase
//
// Created by lotusprize on 15/5/15.
// Copyright (c) 2015年 geekTeam. All rights reserved.
//
import UIKit
import Alamofire
class RelationCaseViewController: ViewController,UICollectionViewDataSource,UICollectionViewDelegate {
@IBOutlet weak var backImage: UIImageView!
@IBOutlet weak var collectionView: UICollectionView!
var methodId:String?
var dataList:NSMutableArray!
var caseList:NSMutableArray?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var backTap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "doHandlerBack:")
backImage.addGestureRecognizer(backTap)
dataList = NSMutableArray()
self.doHandlerCaseList()
collectionView.delegate = self
collectionView.dataSource = self
var plistpath:String = NSBundle.mainBundle().pathForResource("caseList", ofType: "plist")!
caseList = NSMutableArray(contentsOfFile: plistpath)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataList.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var methodModel:MethodModel = dataList[indexPath.row] as! MethodModel
var imageCell:CaseListCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CaseListCell
imageCell.image.image = UIImage(named: methodModel.iconName)
return imageCell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
var methodModel:MethodModel = dataList.objectAtIndex(indexPath.row) as! MethodModel
var detailViewController = self.storyboard?.instantiateViewControllerWithIdentifier("caseDetail") as! CaseViewController
println(methodModel.cnName)
detailViewController.chineseTitle = methodModel.cnName
detailViewController.enTitle = methodModel.enName
detailViewController.url = RequestURL.ServerCaseURL + methodModel.flag!
self.presentViewController(detailViewController, animated: true, completion: { () -> Void in
})
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 1
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 1
}
func doHandlerCaseList(){
self.view.makeToastActivity()
println(methodId)
if methodId != nil{
var url:String = RequestURL.ServerMethodURL + methodId!
println(url)
Alamofire.request(.GET, url)
.responseJSON { (_, _, JSON, error) in
println(error)
if (error == nil){
var dict:NSDictionary = JSON as! NSDictionary
var studyCases:[Int] = dict.objectForKey("study_cases") as! Array
if studyCases.count == 0{
self.view.hideToastActivity()
self.view.makeToast("", duration: 2.0, position: CSToastPositionCenter, image: UIImage(named: "nothing"))
}
else{
self.view.hideToastActivity()
var methodModel:MethodModel?
for i in studyCases{
methodModel = MethodModel()
if (i > 9){
methodModel?.iconName = "S1408W0" + String(i)
}
else{
methodModel?.iconName = "S1408W00" + String(i)
}
methodModel?.flag = String(i)
if (self.caseList?.count > 0){
for (var m = 0; m < self.caseList?.count; m++){
var dict = self.caseList?.objectAtIndex(m) as! NSDictionary
var flag:AnyObject? = dict.objectForKey("flag")
if (flag != nil){
if (flag!.integerValue == i){
methodModel?.cnName = dict.objectForKey("cnName") as? String
methodModel?.enName = dict.objectForKey("enName") as? String
break
}
}
}
}
self.dataList.addObject(methodModel!)
}
self.collectionView.reloadData()
}
}
}
}
}
func doHandlerBack(gesture:UITapGestureRecognizer){
self.dismissViewControllerAnimated(true, completion: { () -> Void in
self.dismissViewControllerAnimated(true, completion: { () -> Void in
})
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
apache-2.0
|
4caa52d4411503d1e0a1923061bf88a5
| 40.196078 | 178 | 0.537839 | 6.328313 | false | false | false | false |
haawa799/WaniKani-iOS
|
WaniTimie Extension/ComplicationController.swift
|
1
|
7081
|
//
// ComplicationController.swift
// WaniTimie Extension
//
// Created by Andriy K. on 2/18/16.
// Copyright © 2016 Andriy K. All rights reserved.
//
import ClockKit
import DataKitWatch
class ComplicationController: NSObject, CLKComplicationDataSource {
var myDelegate: ExtensionDelegate {
return WKExtension.sharedExtension().delegate as! ExtensionDelegate
}
let tempKanji: KanjiMainData = {
var q = KanjiMainData()
q.character = "京"
q.meaning = "capital"
return q
}()
var basicList: [KanjiMainData] {
return dataManager.currentLevel?.kanji ?? [KanjiMainData]()
}
//
func futureItems(date: NSDate, numberOfItems: Int, limit: Int, endDate: NSDate) -> [(KanjiMainData, NSDate)] {
let numberOfItemsInBasicList = basicList.count
var array = [(KanjiMainData, NSDate)]()
guard numberOfItemsInBasicList > 0 else { return array }
let periodInSeconds = endDate.timeIntervalSinceDate(date)
let step = UInt(periodInSeconds / NSTimeInterval(numberOfItems))
var previousDate = date
for i in 0..<numberOfItems {
if array.count < limit {
let basicIndex = i % numberOfItemsInBasicList
let kanji = basicList[basicIndex]
let itemDate = previousDate.plusSeconds(step)
previousDate = itemDate
let item = (kanji, itemDate)
array.append(item)
} else {
break
}
}
return array
}
func pastItemsItems(date: NSDate, numberOfItems: Int, limit: Int, beginDate: NSDate) -> [(KanjiMainData, NSDate)] {
let numberOfItemsInBasicList = basicList.count
var array = [(KanjiMainData, NSDate)]()
guard numberOfItemsInBasicList > 0 else { return array }
let periodInSeconds = date.timeIntervalSinceDate(beginDate)
let step = UInt(periodInSeconds / NSTimeInterval(numberOfItems))
var previousDate = date
for i in 0..<numberOfItems {
if array.count < limit {
let basicIndex = i % numberOfItemsInBasicList
let kanji = basicList[basicIndex]
let itemDate = previousDate.minusSeconds(step)
previousDate = itemDate
let item = (kanji, itemDate)
array.append(item)
} else {
break
}
}
return array
}
//
func getSupportedTimeTravelDirectionsForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimeTravelDirections) -> Void) {
handler([.Backward,.Forward])
}
func getTimelineStartDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
let c = NSDate()
handler(c.minusMinutes(c.minute).minusHours(36))
}
func getTimelineEndDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
let c = NSDate()
handler(c.minusMinutes(c.minute).plusHours(36))
}
func getPrivacyBehaviorForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationPrivacyBehavior) -> Void) {
handler(.ShowOnLockScreen)
}
// MARK: - Timeline Population
func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: ((CLKComplicationTimelineEntry?) -> Void)) {
// Call the handler with the current timeline entry
if basicList.count == 0 {
myDelegate.setupWatchConnectivity()
}
guard let kanji = basicList.first else { handler(nil); return }
let template = complicationTemplate(complication.family, kanji: kanji)
let entry = CLKComplicationTimelineEntry(date: NSDate(), complicationTemplate: template)
handler(entry)
}
func getTimelineEntriesForComplication(complication: CLKComplication, beforeDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
// Call the handler with the timeline entries prior to the given date
let items = pastItemsItems(date, numberOfItems: 36, limit: limit, beginDate: date.minusMinutes(date.minute).minusHours(36)).reverse()
let entries = items.map { (item) -> CLKComplicationTimelineEntry in
let template = complicationTemplate(complication.family, kanji: item.0)
let entrie = CLKComplicationTimelineEntry(date: item.1, complicationTemplate: template)
return entrie
}
handler(entries)
}
func getTimelineEntriesForComplication(complication: CLKComplication, afterDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
// Call the handler with the timeline entries after to the given date
let items = futureItems(date, numberOfItems: 36, limit: limit, endDate: date.minusMinutes(date.minute).plusHours(36))
let entries = items.map { (item) -> CLKComplicationTimelineEntry in
let template = complicationTemplate(complication.family, kanji: item.0)
let entrie = CLKComplicationTimelineEntry(date: item.1, complicationTemplate: template)
return entrie
}
handler(entries)
}
// MARK: - Update Scheduling
func getNextRequestedUpdateDateWithHandler(handler: (NSDate?) -> Void) {
// Call the handler with the date when you would next like to be given the opportunity to update your complication content
let c = NSDate()
handler(c.plusHours(36))
}
// MARK: - Placeholder Templates
func getPlaceholderTemplateForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTemplate?) -> Void) {
// This method will be called once per supported complication, and the results will be cached
handler(complicationTemplate(complication.family, kanji: tempKanji))
}
}
extension ComplicationController {
func complicationTemplate(family: CLKComplicationFamily, kanji: KanjiMainData) -> CLKComplicationTemplate {
let color = UIColor(red:0.99, green:0, blue:0.66, alpha:1)
switch family {
case .CircularSmall:
let t = CLKComplicationTemplateCircularSmallSimpleText()
t.tintColor = color
t.textProvider = CLKSimpleTextProvider(text: kanji.character)
return t
case .ModularLarge:
let t = CLKComplicationTemplateModularLargeTallBody()
t.tintColor = color
t.bodyTextProvider = CLKSimpleTextProvider(text: "==[ \(kanji.character) ]==")
t.headerTextProvider = CLKSimpleTextProvider(text: kanji.meaning)
return t
case .ModularSmall:
let t = CLKComplicationTemplateModularSmallSimpleText()
t.tintColor = color
t.textProvider = CLKSimpleTextProvider(text: kanji.character)
return t
case .UtilitarianSmall:
let t = CLKComplicationTemplateUtilitarianSmallRingText()
t.tintColor = color
t.textProvider = CLKSimpleTextProvider(text: kanji.character)
t.fillFraction = 0
return t
case .UtilitarianLarge:
let t = CLKComplicationTemplateUtilitarianLargeFlat()
t.tintColor = color
t.textProvider = CLKSimpleTextProvider(text: "\(kanji.character) \(kanji.meaning)")
return t
}
}
}
|
gpl-3.0
|
5937cba827f41712e20e9fa4654615d5
| 33.866995 | 176 | 0.70048 | 4.911867 | false | false | false | false |
Sage-Bionetworks/BridgeAppSDK
|
BridgeAppSDK/SBAStepNavigationView.swift
|
1
|
7158
|
//
// SBAStepNavigationView.swift
// ResearchUXFactory
//
// Created by Josh Bruhin on 5/23/17.
// Copyright © 2017 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import UIKit
/**
A custom UIView to be included in an SBAGenericStepViewController. It contains a Next button,
Previous button, and shadowView. The ViewController is responsible for assigning targets and
actions to the buttons.
To customize the view elements, subclasses should override the initializeViews() method. This will allow
the use of any custom element (of the appropriate type) to be used instead of the default instances.
*/
open class SBAStepNavigationView: UIView {
private let kTopMargin: CGFloat = 16.0
private let kBottomMargin: CGFloat = 20.0
private let kSideMargin: CGFloat = CGFloat(25.0).proportionalToScreenWidth()
private let kButtonWidth: CGFloat = CGFloat(120.0).proportionalToScreenWidth()
private let kShadowHeight: CGFloat = 5.0
private let showPreviousButton = SBAGenericStepUIConfig.backButtonPosition() == .navigationView
open var previousButton: UIButton!
open var nextButton: UIButton!
open var shadowView: UIView!
open var buttonCornerRadius = SBARoundedButtonDefaultCornerRadius
/**
Causes the drop shadow at the top of the view to be shown or hidden.
If the value in app configuration is false, that overrides any attempt to set to true
*/
private var _shouldShowShadow = false
open var shouldShowShadow: Bool {
set {
let shadowEnabled = SBAGenericStepUIConfig.shouldShowNavigationViewShadow()
_shouldShowShadow = shadowEnabled && newValue
self.shadowView.isHidden = !_shouldShowShadow
self.clipsToBounds = !_shouldShowShadow
}
get {
return _shouldShowShadow
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
/**
Layout constants. Subclasses can override to customize; otherwise the default private
constants are used.
*/
open func constants() -> (
topMargin: CGFloat,
bottomMargin: CGFloat,
sideMargin: CGFloat,
buttonWidth: CGFloat,
shadowHeight: CGFloat)
{
return (kTopMargin,
kBottomMargin,
kSideMargin,
kButtonWidth,
kShadowHeight)
}
/**
Create all the view elements. Subclasses can override to provide custom instances.
*/
open func initializeViews() {
previousButton = SBARoundedButton()
// Use the default customContinueButtonClass if it is available
if let buttonClass = ORKStepViewController.customContinueButtonClass() as? UIButton.Type {
nextButton = buttonClass.init()
} else {
nextButton = SBARoundedButton()
}
shadowView = SBAShadowGradient()
}
fileprivate func commonInit() {
initializeViews()
if let nextRounded = nextButton as? SBARoundedButton {
nextRounded.corners = buttonCornerRadius
}
if let prevRounded = previousButton as? SBARoundedButton {
prevRounded.corners = buttonCornerRadius
}
previousButton.translatesAutoresizingMaskIntoConstraints = false
nextButton.translatesAutoresizingMaskIntoConstraints = false
shadowView.translatesAutoresizingMaskIntoConstraints = false
// add previous and next buttons
if showPreviousButton {
self.addSubview(previousButton)
}
self.addSubview(nextButton)
self.addSubview(shadowView)
shadowView.isHidden = !shouldShowShadow
setNeedsUpdateConstraints()
}
open override func updateConstraints() {
NSLayoutConstraint.deactivate(self.constraints)
if showPreviousButton {
previousButton.makeWidth(.equal, constants().buttonWidth)
previousButton.makeHeight(.equal, SBARoundedButtonDefaultHeight)
previousButton.alignToSuperview([.leading], padding: constants().sideMargin)
previousButton.alignToSuperview([.top], padding: constants().topMargin)
previousButton.alignToSuperview([.bottom], padding: constants().bottomMargin)
// if we have a previousButton, then define width or nextButton
nextButton.makeWidth(.equal, constants().buttonWidth)
} else {
// if we don't have previousButton, align left edge of nextButton to superview left
nextButton.alignToSuperview([.leading], padding: constants().sideMargin)
}
nextButton.makeHeight(.equal, SBARoundedButtonDefaultHeight)
nextButton.alignToSuperview([.trailing], padding: constants().sideMargin)
nextButton.alignToSuperview([.top], padding: constants().topMargin)
nextButton.alignToSuperview([.bottom], padding: constants().bottomMargin)
shadowView.alignToSuperview([.leading, .trailing], padding: 0.0)
shadowView.alignToSuperview([.top], padding: -1 * constants().shadowHeight)
shadowView.makeHeight(.equal, constants().shadowHeight)
super.updateConstraints()
}
}
|
bsd-3-clause
|
345e2bd8795f123a1b4797f4b8535171
| 38.10929 | 105 | 0.682549 | 5.341045 | false | false | false | false |
mkrd/Swift-Big-Integer
|
Tools/MG Storage.swift
|
1
|
3535
|
/*
* ————————————————————————————————————————————————————————————————————————————
* MG Storage.swift
* ————————————————————————————————————————————————————————————————————————————
* Created by Marcel Kröker on 09.10.16.
* Copyright © 2016 Marcel Kröker. All rights reserved.
*/
import Foundation
public struct Storage
{
static func readResource(_ key: String, inBundle: Bundle = Bundle.main) -> String
{
if let path = inBundle.path(forResource: "longNumbers", ofType: "json", inDirectory: "Resources")
{
let data = try! Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonResult = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
if let jsonResult = jsonResult as? Dictionary<String, String>
{
if let res = jsonResult[key]
{
return res
}
}
}
return ""
}
/// Write a datapoint to UserDefaults for the key "key".
static func write(_ value: Any, forKey key: String)
{
UserDefaults.standard.set(value, forKey: key)
UserDefaults.standard.synchronize()
}
/// Read a datapoint from UserDefaults with the key key.
static func read(forkey key: String) -> Any?
{
return UserDefaults.standard.object(forKey: key)
}
/// Remove a datapoint from UserDefaults for the key key.
static func remove(forKey key: String)
{
UserDefaults.standard.removeObject(forKey: key)
}
/// Print all data stored in the UserDefaults.
static func printData()
{
print(UserDefaults.standard.dictionaryRepresentation())
}
/// Load the contents of a txt file from a specified directory, like downloadsDirectory.
///
/// loadFileContent(from: .downloadsDirectory, name: "kittens.txt")
static func loadFileContent(from: FileManager.SearchPathDirectory, name: String) -> String
{
let dir = FileManager.default.urls(for: from, in: .userDomainMask).first!
let path = dir.appendingPathComponent(name)
let text = try? String(contentsOf: path, encoding: String.Encoding.utf8)
return text ?? ""
}
/// Save the contents of a String to a txt file in a specified directory, like
/// downloadsDirectory.
///
/// loadFileContent(from: .downloadsDirectory, name: "kittens.txt")
static func saveTxtFile(content: String, to: FileManager.SearchPathDirectory, name: String)
{
do
{
let dir = FileManager.default.urls(for: to, in: .userDomainMask).first!
try content.write(
to: dir.appendingPathComponent(name),
atomically: false,
encoding: String.Encoding.utf8
)
}
catch
{
print("Couldn't write to \(name) in \(to)")
}
}
/// Save the contents of a String to a txt file in a specified directory, like
/// downloadsDirectory.
///
/// loadFileContent(from: .downloadsDirectory, name: "kittens.txt")
static func appendToTxtFile(content: String, to: FileManager.SearchPathDirectory, name: String)
{
let dir = FileManager.default.urls(for: to, in: .userDomainMask).first!
let path = dir.appendingPathComponent(name)
if FileManager.default.fileExists(atPath: path.path) {
if let fileHandle = try? FileHandle(forUpdating: path) {
fileHandle.seekToEndOfFile()
fileHandle.write(content.data(using: .utf8, allowLossyConversion: false)!)
fileHandle.closeFile()
}
}
}
}
|
mit
|
55d8cffe1744343123efe193ae8397b5
| 29.742857 | 99 | 0.675031 | 3.668182 | false | false | false | false |
kdawgwilk/KarmaAPI
|
Sources/App/Models/User.swift
|
1
|
7002
|
import Vapor
import Fluent
import HTTP
import Auth
import Foundation
import Turnstile
import TurnstileWeb
import TurnstileCrypto
import Hash
final class User: BaseModel, Model {
// Required properties
// Example ID: 723205272156524544
var username: String
var password = ""
var digitsID = ""
var phoneNumber = ""
var accessToken = URandom().secureToken
var apiKeyID = URandom().secureToken
var apiKeySecret = URandom().secureToken
var firstName = ""
var lastName = ""
var email = ""
var imageURL = ""
init(credentials: UsernamePassword) {
self.username = credentials.username
self.password = BCrypt.hash(password: credentials.password)
super.init()
}
init(credentials: DigitsAccount) {
self.username = "digit" + credentials.uniqueID
self.digitsID = credentials.uniqueID
super.init()
}
/**
Initializer for Fluent
*/
override init(node: Node, in context: Context) throws {
username = try node.extract("username")
password = try node.extract("password")
accessToken = try node.extract("access_token")
apiKeyID = try node.extract("api_key_id")
apiKeySecret = try node.extract("api_key_secret")
digitsID = try node.extract("digits_id")
phoneNumber = try node.extract("phone_number")
firstName = try node.extract("first_name")
lastName = try node.extract("last_name")
email = try node.extract("email")
imageURL = try node.extract("image_url")
try super.init(node: node, in: context)
}
/**
Serializer for Fluent
*/
override func makeNode(context: Context) throws -> Node {
var node = [String: NodeRepresentable]()
node["id"] = id
node["created_on"] = createdOn
node["username"] = username
node["password"] = password
node["access_token"] = accessToken
node["api_key_id"] = apiKeyID
node["api_key_secret"] = apiKeySecret
node["digits_id"] = digitsID
node["phone_number"] = phoneNumber
node["first_name"] = firstName
node["last_name"] = lastName
node["email"] = email
node["image_url"] = imageURL
return try Node(node: node)
}
func groups() throws -> Siblings<Group> {
return try siblings()
}
}
extension User: Auth.User {
static func authenticate(credentials: Credentials) throws -> Auth.User {
var user: User?
switch credentials {
/**
Fetches a user, and checks that the password is present, and matches.
*/
case let credentials as UsernamePassword:
let fetchedUser = try User.query()
.filter("username", credentials.username)
.first()
if let password = fetchedUser?.password,
password != "",
(try? BCrypt.verify(password: credentials.password, matchesHash: password)) == true {
user = fetchedUser
}
/**
Fetches the user by session ID. Used by the Vapor session manager.
*/
case let credentials as Identifier:
user = try User.find(credentials.id)
/**
Authenticates via AccessToken
*/
case let credentials as AccessToken:
user = try User.query().filter("access_token", credentials.string).first()
/**
Fetches the user by Digits ID. If the user doesn't exist, autoregisters it.
*/
case let credentials as DigitsAccount:
if let existing = try User.query().filter("digits_id", credentials.uniqueID).first() {
user = existing
} else {
user = try User.register(credentials: credentials) as? User
}
/**
Authenticates via API Keys
*/
case let credentials as APIKey:
user = try User.query()
.filter("api_key_id", credentials.id)
.filter("api_key_secret", credentials.secret)
.first()
default:
throw UnsupportedCredentialsError()
}
guard let u = user else {
throw IncorrectCredentialsError()
}
return u
}
// This shouldn't be used because a user can be created with the above method instead
static func register(credentials: Credentials) throws -> Auth.User {
var newUser: User
switch credentials {
case let credentials as UsernamePassword:
newUser = User(credentials: credentials)
case let credentials as DigitsAccount:
newUser = User(credentials: credentials)
default:
throw Abort.custom(status: .badRequest, message: "Invalid credentials.")
}
if try User.query().filter("username", newUser.username).first() == nil {
try newUser.save()
return newUser
} else {
throw AccountTakenError()
}
}
}
extension Request {
func user() throws -> User {
guard let user = try auth.user() as? User else {
throw Abort.custom(status: .badRequest, message: "Invalid user type.")
}
return user
}
}
extension User: Preparation {
static func prepare(_ database: Database) throws {
try database.create("users") { user in
prepare(model: user)
user.string("username")
user.string("password")
user.string("access_token")
user.string("api_key_id")
user.string("api_key_secret")
user.string("digits_id")
user.string("phone_number")
user.string("first_name")
user.string("last_name")
user.string("email")
user.string("image_url")
}
}
static func revert(_ database: Database) throws {
try database.delete("users")
}
}
// MARK: Merge
extension User {
func merge(updates: User) {
super.merge(updates: updates)
username = updates.username
password = updates.password
accessToken = updates.accessToken
apiKeyID = updates.apiKeyID
apiKeySecret = updates.apiKeySecret
digitsID = updates.digitsID
phoneNumber = updates.phoneNumber
firstName = updates.firstName
lastName = updates.lastName
email = updates.email
imageURL = updates.imageURL
}
}
// MARK: Relationships
extension User {
func points() throws -> Children<Score> {
return children()
}
func userTasks() throws -> Children<UserTask> {
return children()
}
func userRewards() throws -> Children<UserReward> {
return children()
}
}
|
mit
|
77312afe69a4269fb939c02d58a0d61c
| 26.896414 | 101 | 0.569837 | 4.769755 | false | false | false | false |
Lifelong-Study/EliteFramework
|
EliteFramework/EliteDate.swift
|
1
|
3657
|
//
// EliteDate.swift
// EliteFramework
//
// Created by Lifelong-Study on 2016/3/2.
// Copyright © 2016年 Lifelong-Study. All rights reserved.
//
import UIKit
public extension Date {
var dateByZeroSecond: Date {
return self
}
func dateByZeroSecond(date: Date) -> Date {
var calendar = Calendar(identifier: Calendar.Identifier.gregorian)
calendar.timeZone = .current
let components = (calendar as NSCalendar).components([.year, .month, .day], from: date)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSS"
let dateString = String(format: "%04d-%02d-%02d 00:00:00.0000", components.year!, components.month!, components.day!)
return dateFormatter.date(from: dateString)!
}
func cleanNanosecond() -> Date {
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
if var components = (calendar as NSCalendar?)?.components([.year, .month, .day, .hour, .minute, .second], from: self) {
components.nanosecond = 0
return calendar.date(from: components) ?? self
}
return self
}
func string(format: String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
var firstDayByTheYear: Date? {
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
var components = (calendar as NSCalendar?)?.components([.year, .hour, .minute, .second], from: self)
components?.month = 1
components?.day = 1
components?.nanosecond = 0
return calendar.date(from: components!)
}
var firstDayByTheMonth: Date? {
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
var components = (calendar as NSCalendar?)?.components([.year, .month, .hour, .minute, .second], from: self)
components?.day = 1
return calendar.date(from: components!)
}
var lastDayByTheMonth: Date? {
return self.addingTimeInterval(Double(daysInTheMonth!) * 24 * 60 * 60)
}
var daysInTheMonth: Int? {
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
return (calendar as NSCalendar?)?.range(of: .day, in: .month, for: self).length
}
func calendar() -> Calendar? {
return Calendar(identifier: Calendar.Identifier.gregorian)
}
var year: Int? { return (calendar() as NSCalendar?)?.components([.year], from: self).day }
var month: Int? { return (calendar() as NSCalendar?)?.components([.month], from: self).month }
var day: Int? { return (calendar() as NSCalendar?)?.components([.day], from: self).day }
var hour: Int? { return (calendar() as NSCalendar?)?.components([.hour], from: self).hour }
var minute: Int? { return (calendar() as NSCalendar?)?.components([.minute], from: self).minute }
var second: Int? { return (calendar() as NSCalendar?)?.components([.second], from: self).second }
var shortweek: String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE"
return dateFormatter.string(from: self)
}
var longweek: String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
return dateFormatter.string(from: self)
}
}
|
mit
|
0c55d036ab0c9df0c49ba49fe21c2feb
| 32.522936 | 127 | 0.599343 | 4.550436 | false | false | false | false |
gaoleegin/SwiftLianxi
|
自定义控制器视图的转场动画_Swift/自定义控制器视图的转场动画_Swift/FirstCustomSegueUnwind.swift
|
1
|
774
|
//
// FirstCustomSegueUnwind.swift
// 自定义控制器视图的转场动画_Swift
//
// Created by 高李军 on 15/11/25.
// Copyright © 2015年 高李军. All rights reserved.
import UIKit
class FirstCustomSegueUnwind: UIStoryboardSegue {
override func perform() {
let screenWidth = UIScreen.mainScreen().bounds.size.width
let screenHeight = UIScreen.mainScreen().bounds.size.height
var secondVCView = self.sourceViewController.view as UIView!
var firstVCView = self.destinationViewController.view as UIView!
let window = UIApplication.sharedApplication().keyWindow
window?.insertSubview(firstVCView, aboveSubview: secondVCView)
}
}
|
apache-2.0
|
bb48331be30180cbb6754bb8cf19d184
| 23.433333 | 72 | 0.65075 | 4.854305 | false | false | false | false |
Resoulte/DYZB
|
DYZB/DYZB/Classes/Tools/Common.swift
|
1
|
329
|
//
// Common.swift
// DYZB
//
// Created by ma c on 16/10/20.
// Copyright © 2016年 shifei. All rights reserved.
//
import UIKit
let kScreenH = UIScreen.main.bounds.height
let kScreenW = UIScreen.main.bounds.width
let kTabBarH : CGFloat = 44.0
let kStatusBarH : CGFloat = 20.0
let kNavigationBarH : CGFloat = 44.0
|
mit
|
c57e45c56caeaafc03e10f5a5e41fd07
| 13.818182 | 50 | 0.690184 | 3.292929 | false | false | false | false |
gottesmm/swift
|
test/type/protocol_types.swift
|
10
|
3819
|
// RUN: %target-typecheck-verify-swift
protocol HasSelfRequirements {
func foo(_ x: Self)
func returnsOwnProtocol() -> HasSelfRequirements // expected-error{{protocol 'HasSelfRequirements' can only be used as a generic constraint because it has Self or associated type requirements}}
}
protocol Bar {
// init() methods should not prevent use as an existential.
init()
func bar() -> Bar
}
func useBarAsType(_ x: Bar) {}
protocol Pub : Bar { }
func refinementErasure(_ p: Pub) {
useBarAsType(p)
}
typealias Compo = HasSelfRequirements & Bar
struct CompoAssocType {
typealias Compo = HasSelfRequirements & Bar // expected-error{{protocol 'HasSelfRequirements' can only be used as a generic constraint}}
}
func useAsRequirement<T: HasSelfRequirements>(_ x: T) { }
func useCompoAsRequirement<T: HasSelfRequirements & Bar>(_ x: T) { }
func useCompoAliasAsRequirement<T: Compo>(_ x: T) { }
func useAsWhereRequirement<T>(_ x: T) where T: HasSelfRequirements {}
func useCompoAsWhereRequirement<T>(_ x: T) where T: HasSelfRequirements & Bar {}
func useCompoAliasAsWhereRequirement<T>(_ x: T) where T: Compo {}
func useAsType(_ x: HasSelfRequirements) { } // expected-error{{protocol 'HasSelfRequirements' can only be used as a generic constraint}}
func useCompoAsType(_ x: HasSelfRequirements & Bar) { } // expected-error{{protocol 'HasSelfRequirements' can only be used as a generic constraint}}
func useCompoAliasAsType(_ x: Compo) { } // expected-error{{protocol 'HasSelfRequirements' can only be used as a generic constraint}}
struct TypeRequirement<T: HasSelfRequirements> {}
struct CompoTypeRequirement<T: HasSelfRequirements & Bar> {}
struct CompoAliasTypeRequirement<T: Compo> {}
struct CompoTypeWhereRequirement<T> where T: HasSelfRequirements & Bar {}
struct CompoAliasTypeWhereRequirement<T> where T: Compo {}
struct Struct1<T> { }
struct Struct2<T : Pub & Bar> { }
struct Struct3<T : Pub & Bar & P3> { } // expected-error {{use of undeclared type 'P3'}}
struct Struct4<T> where T : Pub & Bar {}
struct Struct5<T : protocol<Pub, Bar>> { } // expected-warning {{'protocol<...>' composition syntax is deprecated; join the protocols using '&'}}
struct Struct6<T> where T : protocol<Pub, Bar> {} // expected-warning {{'protocol<...>' composition syntax is deprecated; join the protocols using '&'}}
typealias T1 = Pub & Bar
typealias T2 = protocol<Pub , Bar> // expected-warning {{'protocol<...>' composition syntax is deprecated; join the protocols using '&'}}
// rdar://problem/20593294
protocol HasAssoc {
associatedtype Assoc
func foo()
}
func testHasAssoc(_ x: Any) {
if let p = x as? HasAssoc { // expected-error {{protocol 'HasAssoc' can only be used as a generic constraint}}
p.foo() // don't crash here.
}
}
// rdar://problem/16803384
protocol InheritsAssoc : HasAssoc {
func silverSpoon()
}
func testInheritsAssoc(_ x: InheritsAssoc) { // expected-error {{protocol 'InheritsAssoc' can only be used as a generic constraint}}
x.silverSpoon()
}
// SR-38
var b: HasAssoc // expected-error {{protocol 'HasAssoc' can only be used as a generic constraint because it has Self or associated type requirements}}
// Further generic constraint error testing - typealias used inside statements
protocol P {}
typealias MoreHasAssoc = HasAssoc & P
func testHasMoreAssoc(_ x: Any) {
if let p = x as? MoreHasAssoc { // expected-error {{protocol 'HasAssoc' can only be used as a generic constraint}}
p.foo() // don't crash here.
}
}
struct Outer {
typealias Any = Int // expected-error {{keyword 'Any' cannot be used as an identifier here}} expected-note {{if this name is unavoidable, use backticks to escape it}} {{13-16=`Any`}}
typealias `Any` = Int
static func aa(a: `Any`) -> Int { return a }
}
typealias X = Struct1<Pub & Bar>
_ = Struct1<Pub & Bar>.self
|
apache-2.0
|
515ab2977c96c5c9946c1dd41bdc8051
| 37.19 | 195 | 0.720084 | 3.933059 | false | false | false | false |
ivanbruel/SwipeIt
|
SwipeIt/Models/AppLink.swift
|
1
|
683
|
//
// AppLink.swift
// Reddit
//
// Created by Ivan Bruel on 10/05/16.
// Copyright © 2016 Faber Ventures. All rights reserved.
//
import Foundation
struct AppLink {
let appName: String
let url: NSURL
let appStoreId: String
init?(html: String) {
guard let parser = HTMLParser(html: html) else { return nil }
guard let appName = parser.contentFromMetatag("al:ios:app_name"),
appStoreId = parser.contentFromMetatag("al:ios:app_store_id"),
urlString = parser.contentFromMetatag("al:ios:url"),
url = NSURL(string: urlString) else {
return nil
}
self.appName = appName
self.url = url
self.appStoreId = appStoreId
}
}
|
mit
|
af3f2b7e59de25c4bb6ef9cc2581b648
| 21 | 69 | 0.659824 | 3.666667 | false | false | false | false |
JGiola/swift
|
test/Interop/SwiftToCxx/methods/mutating-method-in-cxx.swift
|
1
|
4129
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %s -typecheck -module-name Methods -clang-header-expose-public-decls -emit-clang-header-path %t/methods.h
// RUN: %FileCheck %s < %t/methods.h
// RUN: %check-interop-cxx-header-in-clang(%t/methods.h)
public struct LargeStruct {
var x1, x2, x3, x4, x5, x6: Int
public func dump() {
print("\(x1), \(x2), \(x3), \(x4), \(x5), \(x6)")
}
public mutating func double() {
x1 *= 2
x2 *= 2
x3 *= 2
x4 *= 2
x5 *= 2
x6 *= 2
}
public mutating func scale(_ x: Int, _ y: Int) -> LargeStruct {
x1 *= x
x2 *= y
x3 *= x
x4 *= y
x5 *= x
x6 *= y
return self
}
}
public struct SmallStruct {
var x: Float
public func dump() {
print("small x = \(x);")
}
public mutating func scale(_ y: Float) -> SmallStruct {
x *= y
return SmallStruct(x: x / y)
}
public mutating func invert() {
x = -x
}
}
// CHECK: SWIFT_EXTERN void $s7Methods11LargeStructV4dumpyyF(SWIFT_CONTEXT const void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // dump()
// CHECK: SWIFT_EXTERN void $s7Methods11LargeStructV6doubleyyF(SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // double()
// CHECK: SWIFT_EXTERN void $s7Methods11LargeStructV5scaleyACSi_SitF(SWIFT_INDIRECT_RESULT void * _Nonnull, ptrdiff_t x, ptrdiff_t y, SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // scale(_:_:)
// CHECK: SWIFT_EXTERN void $s7Methods11SmallStructV4dumpyyF(struct swift_interop_stub_Methods_SmallStruct _self) SWIFT_NOEXCEPT SWIFT_CALL; // dump()
// CHECK: SWIFT_EXTERN struct swift_interop_stub_Methods_SmallStruct $s7Methods11SmallStructV5scaleyACSfF(float y, SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // scale(_:)
// CHECK: SWIFT_EXTERN void $s7Methods11SmallStructV6invertyyF(SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // invert()
// CHECK: class LargeStruct final {
// CHECK: inline LargeStruct(LargeStruct &&) = default;
// CHECK-NEXT: inline void dump() const;
// CHECK-NEXT: inline void double_();
// CHECK-NEXT: inline LargeStruct scale(swift::Int x, swift::Int y);
// CHECK-NEXT: private
// CHECK: inline void LargeStruct::dump() const {
// CHECK-NEXT: return _impl::$s7Methods11LargeStructV4dumpyyF(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline void LargeStruct::double_() {
// CHECK-NEXT: return _impl::$s7Methods11LargeStructV6doubleyyF(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline LargeStruct LargeStruct::scale(swift::Int x, swift::Int y) {
// CHECK-NEXT: return _impl::_impl_LargeStruct::returnNewValue([&](void * _Nonnull result) {
// CHECK-NEXT: _impl::$s7Methods11LargeStructV5scaleyACSi_SitF(result, x, y, _getOpaquePointer());
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK: class SmallStruct final {
// CHECK: inline SmallStruct(SmallStruct &&) = default;
// CHECK-NEXT: inline void dump() const;
// CHECK-NEXT: inline SmallStruct scale(float y);
// CHECK-NEXT: inline void invert();
// CHECK-NEXT: private:
// CHECK: inline void SmallStruct::dump() const {
// CHECK-NEXT: return _impl::$s7Methods11SmallStructV4dumpyyF(_impl::swift_interop_passDirect_Methods_SmallStruct(_getOpaquePointer()));
// CHECK-NEXT: }
// CHECK-NEXT: inline SmallStruct SmallStruct::scale(float y) {
// CHECK-NEXT: return _impl::_impl_SmallStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::swift_interop_returnDirect_Methods_SmallStruct(result, _impl::$s7Methods11SmallStructV5scaleyACSfF(y, _getOpaquePointer()));
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: inline void SmallStruct::invert() {
// CHECK-NEXT: return _impl::$s7Methods11SmallStructV6invertyyF(_getOpaquePointer());
// CHECK-NEXT: }
public func createLargeStruct() -> LargeStruct {
return LargeStruct(x1: 1, x2: -5, x3: 9, x4: 11, x5: 0xbeef, x6: -77)
}
public func createSmallStruct(x: Float) -> SmallStruct {
return SmallStruct(x: x)
}
|
apache-2.0
|
372d41bd22e5f6411cfac05977079a0d
| 38.701923 | 212 | 0.66045 | 3.443703 | false | false | false | false |
10Duke/DukeSwiftLibs
|
Example/DukeSwiftLibs/controllers/UserViewController.swift
|
1
|
4527
|
import Foundation
import UIKit
import DukeSwiftLibs
/**
* View controller class for user creation and editing.
*/
class UserViewController: AbstractViewController, UITextFieldDelegate {
var m_user: User?
var m_actionButton: UIBarButtonItem?
/**
* Generic delegate method called when view is loaded.
*/
override func viewDidLoad() {
//
if m_user == nil {
//
m_user = User()
}
//
super.viewDidLoad()
}
/**
* Dynamic layout handling and component creation.
*/
override func loadView() {
//
let scrollView = UIScrollView(frame: UIScreen.main.bounds)
self.view = scrollView
self.view.autoresizesSubviews = true
self.view.backgroundColor = UIColor.white
self.view.addSubview(createInputField(title: "FirstName".localized, value: m_user?.firstName, action: #selector(self.givenNameEdited(_:)), editable: true))
self.view.addSubview(createInputField(title: "LastName".localized, value: m_user?.lastName, action: #selector(self.familyNameEdited(_:)), editable: true))
self.view.addSubview(createInputField(title: "Email".localized, value: m_user?.email, action: #selector(self.emailEdited(_:)), editable: true))
self.view.addSubview(createInputField(title: "Description".localized, value: m_user?._description, action: #selector(self.descriptionEdited(_:)), editable: true))
//
if m_user?.id != nil {
//
self.view.addSubview(createInputField(title: "Id", value: m_user?.id, action: nil, editable: false))
}
//
m_actionButton = UIBarButtonItem(title: m_user?.id != nil ? "Save".localized: "Create".localized, style: .plain, target: self, action: #selector(UserViewController.actionButtonAction(_:)))
m_actionButton?.isEnabled = false
self.navigationItem.rightBarButtonItem = m_actionButton
//
setMaxHeight(scrollView: scrollView)
}
override func viewWillAppear(_ animated: Bool) {
//
if m_user?.id != nil {
//
navigationItem.title = "UserInformation".localized
} else {
//
navigationItem.title = "CreateUser".localized
}
//
navigationItem.backBarButtonItem?.title = "Back".localized
}
override func viewDidAppear(_ animated: Bool) {
//
}
func givenNameEdited(_ textField: UITextField) {
//
m_user?.firstName = textField.text
m_actionButton?.isEnabled = true
}
func familyNameEdited(_ textField: UITextField) {
//
m_user?.lastName = textField.text
m_actionButton?.isEnabled = true
}
func emailEdited(_ textField: UITextField) {
//
m_user?.email = textField.text
m_actionButton?.isEnabled = true
}
func descriptionEdited(_ textField: UITextField) {
//
m_user?._description = textField.text
m_actionButton?.isEnabled = true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
//
}
/**
* Update user action result callback function.
*
* - parameter success: Boolean that tells if the operation was successful.
*/
func updateUserCallback(_ success: Bool) {
//
if success {
//
m_actionButton?.isEnabled = false
} else {
//
showError(title: "UserUpdateFailed".localized, message: "PressOkToContinue".localized)
}
}
/**
* Create user action result callback function.
*
* - parameter success: Boolean that tells if the operation was successful.
*/
func createUserCallback(_ success: Bool) {
//
if success {
//
m_actionButton?.isEnabled = false
} else {
//
showError(title: "UserCreateFailed".localized, message: "PressOkToContinue".localized)
}
}
/**
* Callback function that is called when action button is pressed.
*/
func actionButtonAction(_ sender: Any) {
//
if let user = m_user {
//
if user.id != nil {
//
RestApiImpl.shared.updateUser(user, completion: updateUserCallback(_:))
} else {
//
RestApiImpl.shared.createUser(user, completion: createUserCallback(_:))
}
}
}
}
|
mit
|
c7364dd4a7bab0e09be7a2aa3899ca57
| 27.29375 | 196 | 0.585818 | 4.826226 | false | false | false | false |
watson-developer-cloud/ios-sdk
|
Sources/DiscoveryV2/Models/QueryLargePassages.swift
|
1
|
6970
|
/**
* (C) Copyright IBM Corp. 2019, 2021.
*
* 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
/**
Configuration for passage retrieval.
*/
public struct QueryLargePassages: Codable, Equatable {
/**
A passages query that returns the most relevant passages from the results.
*/
public var enabled: Bool?
/**
If `true`, ranks the documents by document quality, and then returns the highest-ranked passages per document in a
`document_passages` field for each document entry in the results list of the response.
If `false`, ranks the passages from all of the documents by passage quality regardless of the document quality and
returns them in a separate `passages` field in the response.
*/
public var perDocument: Bool?
/**
Maximum number of passages to return per document in the result. Ignored if `passages.per_document` is `false`.
*/
public var maxPerDocument: Int?
/**
A list of fields to extract passages from. If this parameter is an empty list, then all root-level fields are
included.
*/
public var fields: [String]?
/**
The maximum number of passages to return. Ignored if `passages.per_document` is `true`.
*/
public var count: Int?
/**
The approximate number of characters that any one passage will have.
*/
public var characters: Int?
/**
When true, `answer` objects are returned as part of each passage in the query results. The primary difference
between an `answer` and a `passage` is that the length of a passage is defined by the query, where the length of an
`answer` is calculated by Discovery based on how much text is needed to answer the question.
This parameter is ignored if passages are not enabled for the query, or no **natural_language_query** is specified.
If the **find_answers** parameter is set to `true` and **per_document** parameter is also set to `true`, then the
document search results and the passage search results within each document are reordered using the answer
confidences. The goal of this reordering is to place the best answer as the first answer of the first passage of
the first document. Similarly, if the **find_answers** parameter is set to `true` and **per_document** parameter is
set to `false`, then the passage search results are reordered in decreasing order of the highest confidence answer
for each document and passage.
The **find_answers** parameter is available only on managed instances of Discovery.
*/
public var findAnswers: Bool?
/**
The number of `answer` objects to return per passage if the **find_answers** parmeter is specified as `true`.
*/
public var maxAnswersPerPassage: Int?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case enabled = "enabled"
case perDocument = "per_document"
case maxPerDocument = "max_per_document"
case fields = "fields"
case count = "count"
case characters = "characters"
case findAnswers = "find_answers"
case maxAnswersPerPassage = "max_answers_per_passage"
}
/**
Initialize a `QueryLargePassages` with member variables.
- parameter enabled: A passages query that returns the most relevant passages from the results.
- parameter perDocument: If `true`, ranks the documents by document quality, and then returns the highest-ranked
passages per document in a `document_passages` field for each document entry in the results list of the response.
If `false`, ranks the passages from all of the documents by passage quality regardless of the document quality
and returns them in a separate `passages` field in the response.
- parameter maxPerDocument: Maximum number of passages to return per document in the result. Ignored if
`passages.per_document` is `false`.
- parameter fields: A list of fields to extract passages from. If this parameter is an empty list, then all
root-level fields are included.
- parameter count: The maximum number of passages to return. Ignored if `passages.per_document` is `true`.
- parameter characters: The approximate number of characters that any one passage will have.
- parameter findAnswers: When true, `answer` objects are returned as part of each passage in the query results.
The primary difference between an `answer` and a `passage` is that the length of a passage is defined by the
query, where the length of an `answer` is calculated by Discovery based on how much text is needed to answer the
question.
This parameter is ignored if passages are not enabled for the query, or no **natural_language_query** is
specified.
If the **find_answers** parameter is set to `true` and **per_document** parameter is also set to `true`, then the
document search results and the passage search results within each document are reordered using the answer
confidences. The goal of this reordering is to place the best answer as the first answer of the first passage of
the first document. Similarly, if the **find_answers** parameter is set to `true` and **per_document** parameter
is set to `false`, then the passage search results are reordered in decreasing order of the highest confidence
answer for each document and passage.
The **find_answers** parameter is available only on managed instances of Discovery.
- parameter maxAnswersPerPassage: The number of `answer` objects to return per passage if the **find_answers**
parmeter is specified as `true`.
- returns: An initialized `QueryLargePassages`.
*/
public init(
enabled: Bool? = nil,
perDocument: Bool? = nil,
maxPerDocument: Int? = nil,
fields: [String]? = nil,
count: Int? = nil,
characters: Int? = nil,
findAnswers: Bool? = nil,
maxAnswersPerPassage: Int? = nil
)
{
self.enabled = enabled
self.perDocument = perDocument
self.maxPerDocument = maxPerDocument
self.fields = fields
self.count = count
self.characters = characters
self.findAnswers = findAnswers
self.maxAnswersPerPassage = maxAnswersPerPassage
}
}
|
apache-2.0
|
f7abfdc1d4ab7685ed54227cf99d2b3c
| 47.741259 | 121 | 0.698996 | 4.428208 | false | false | false | false |
CrawlingSnail/CardStack
|
CardStackdemo/CardStacking/BaseViewController.swift
|
1
|
1268
|
//
// BaseViewController.swift
// CardStacking
//
// Created by Mr.Huang on 2017/7/4.
// Copyright © 2017年 Mr.Huang. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController {
public let fuzzyImgView = UIImageView.init(frame: .zero)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
fuzzyImgView.frame = view.bounds
fuzzyImgView.contentMode = .scaleAspectFill
view.addSubview(fuzzyImgView)
let effect = UIBlurEffect.init(style: .light)
let effectView = UIVisualEffectView.init(effect: effect)
effectView.frame = view.bounds
fuzzyImgView.addSubview(effectView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
f902f991c6b19308f40e4fa612a13219
| 28.418605 | 106 | 0.674308 | 4.846743 | false | false | false | false |
codeforgreenville/trolley-tracker-ios-client
|
TrolleyTracker/Controllers/Model/GetETAOperation.swift
|
1
|
1823
|
//
// GetETAOperation.swift
//
//
// Created by Austin Younts on 8/23/15.
//
//
import Foundation
import MapKit
class GetETAOperation: ConcurrentOperation {
private static let travelTimeDateFormatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .abbreviated
return formatter
}()
var expectedTravelTime: TimeInterval?
var formattedTravelTime: String?
private let source: MKMapItem
private let destination: MKMapItem
init(source: MKMapItem, destination: MKMapItem) {
self.source = source
self.destination = destination
}
override func execute() {
if isCancelled {
self.finish()
return
}
let request = MKDirectionsRequest()
request.source = source
request.destination = destination
request.transportType = MKDirectionsTransportType.walking
let directions = MKDirections(request: request)
directions.calculateETA { (response, error) -> Void in
guard let response = response else { self.finish(); return }
let time = response.expectedTravelTime
var travelTimeComponents = DateComponents()
travelTimeComponents.hour = Int(floor(time / 3600))
travelTimeComponents.minute = Int(ceil((time.truncatingRemainder(dividingBy: 3600)) / 60))
let componentsString = GetETAOperation.travelTimeDateFormatter.string(from: travelTimeComponents)
self.expectedTravelTime = response.expectedTravelTime
self.formattedTravelTime = componentsString
self.finish()
}
}
}
|
mit
|
754f3377ebc3c5b623946d2293b698d2
| 27.046154 | 109 | 0.61492 | 5.768987 | false | false | false | false |
blokadaorg/blokada
|
ios/App/Model/SKProduct+Extensions.swift
|
1
|
2491
|
//
// This file is part of Blokada.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
// Copyright © 2020 Blocka AB. All rights reserved.
//
// @author Karol Gusak
//
import Foundation
import StoreKit
extension SKProduct {
private func formatPrice(price: NSNumber) -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = self.priceLocale
return formatter.string(from: price)!
}
var localPrice: String {
formatPrice(price: self.price)
}
var durationMonths: Int {
switch self.subscriptionPeriod?.unit {
case .year:
return (self.subscriptionPeriod?.numberOfUnits ?? 1) * 12
default:
if (self.subscriptionPeriod?.numberOfUnits == 6) {
return 12
}
return self.subscriptionPeriod?.numberOfUnits ?? 1
}
}
var localTitle: String {
let length = self.durationMonths
if length == 1 {
return L10n.paymentSubscription1Month
} else {
return L10n.paymentSubscriptionManyMonths(String(length))
}
}
var localDescription: String {
let length = self.durationMonths
if length == 1 {
return "(\(L10n.paymentSubscriptionPerMonth(formatPrice(price: price))))"
} else if self.productIdentifier == "cloud_12month" {
let price = self.price.dividing(by: NSDecimalNumber(decimal: (length as NSNumber).decimalValue))
//return "then \(L10n.paymentSubscriptionPerMonth(formatPrice(price: price)))"
return "(\(L10n.paymentSubscriptionPerMonth(formatPrice(price: price))))"
} else {
let price = self.price.dividing(by: NSDecimalNumber(decimal: (length as NSNumber).decimalValue))
return "(\(L10n.paymentSubscriptionPerMonth(formatPrice(price: price))). \(localInfo))"
}
}
var isTrial: Bool {
return self.introductoryPrice?.paymentMode == SKProductDiscount.PaymentMode.freeTrial
}
private var localInfo: String {
switch (self.durationMonths) {
case 12:
return L10n.paymentSubscriptionOffer("20%")
case 6:
return L10n.paymentSubscriptionOffer("10%")
default:
return ""
}
}
}
|
mpl-2.0
|
3960e33046cbc337b9a4ffb19fbd2111
| 30.518987 | 107 | 0.623293 | 4.383803 | false | false | false | false |
CosmicMind/Material
|
Sources/iOS/Application/Application.swift
|
3
|
3516
|
/*
* The MIT License (MIT)
*
* Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
public struct Application {
/// A reference to UIApplication.shared application which doesn't trigger linker errors when Material is included in an extension
/// Note that this will crash if actually called from within an extension
public static var shared: UIApplication {
let sharedSelector = NSSelectorFromString("sharedApplication")
guard UIApplication.responds(to: sharedSelector) else {
fatalError("[Material: Extensions cannot access Application]")
}
let shared = UIApplication.perform(sharedSelector)
return shared?.takeUnretainedValue() as! UIApplication
}
/// An optional reference to the main UIWindow.
public static var keyWindow: UIWindow? {
return Application.shared.keyWindow
}
/// An optional reference to the top most view controller.
public static var rootViewController: UIViewController? {
return keyWindow?.rootViewController
}
/// A boolean indicating if the device is in Landscape mode.
public static var isLandscape: Bool {
return Application.shared.statusBarOrientation.isLandscape
}
/// A boolean indicating if the device is in Portrait mode.
public static var isPortrait: Bool {
return !isLandscape
}
/// The current UIInterfaceOrientation value.
public static var orientation: UIInterfaceOrientation {
return Application.shared.statusBarOrientation
}
/// Retrieves the device status bar style.
public static var statusBarStyle: UIStatusBarStyle {
get {
return Application.shared.statusBarStyle
}
set(value) {
Application.shared.statusBarStyle = value
}
}
/// Retrieves the device status bar hidden state.
public static var isStatusBarHidden: Bool {
get {
return Application.shared.isStatusBarHidden
}
set(value) {
Application.shared.isStatusBarHidden = value
}
}
/**
A boolean that indicates based on iPhone rules if the
status bar should be shown.
*/
public static var shouldStatusBarBeHidden: Bool {
return isLandscape && .phone == Device.userInterfaceIdiom
}
/// A reference to the user interface layout direction.
public static var userInterfaceLayoutDirection: UIUserInterfaceLayoutDirection {
return Application.shared.userInterfaceLayoutDirection
}
}
|
mit
|
1e484184bd05fbbbdf245cb3ee0e0d43
| 34.515152 | 131 | 0.738908 | 5.110465 | false | false | false | false |
marc-medley/004.45macOS_CotEditorSwiftScripting
|
templates/CotEditor.swift
|
1
|
16493
|
import Foundation
import AppKit
import ScriptingBridge
@objc
public protocol SBObjectProtocol: NSObjectProtocol {
func get() -> Any!
}
@objc
public protocol SBApplicationProtocol: SBObjectProtocol {
func activate()
var delegate: SBApplicationDelegate! { get set }
var running: Bool { @objc(isRunning) get }
}
/*
* CotEditor.h
*/
// MARK: CotEditorSaveOptions
@objc public enum CotEditorSaveOptions : AEKeyword {
case yes = 0x79657320 /* 'yes ' */ // Save the file.
case no = 0x6e6f2020 /* 'no ' */ // Do not save the file.
case ask = 0x61736b20 /* 'ask ' */ // Ask the user whether or not to save the file.
}
// MARK: CotEditorPrintingErrorHandling
@objc public enum CotEditorPrintingErrorHandling : AEKeyword {
case standard = 0x6c777374 /* 'lwst' */ // Standard PostScript error handling
case detailed = 0x6c776474 /* 'lwdt' */ // print a detailed report of PostScript errors
}
// MARK: CotEditorSaveableFileFormat
@objc public enum CotEditorSaveableFileFormat : AEKeyword {
case text = 0x54585420 /* 'TXT ' */ // The plain text.
}
// MARK: CotEditorLineEndingCharacter
@objc public enum CotEditorLineEndingCharacter : AEKeyword {
case lf = 0x6c654c46 /* 'leLF' */ // macOS / Unix (LF)
case cr = 0x6c654352 /* 'leCR' */ // Classic Mac OS (CR)
case crlf = 0x6c65434c /* 'leCL' */ // Windows (CR/LF)
}
// MARK: CotEditorCaseType
@objc public enum CotEditorCaseType : AEKeyword {
case capitalized = 0x63436370 /* 'cCcp' */
case lower = 0x63436c77 /* 'cClw' */
case upper = 0x63437570 /* 'cCup' */
}
// MARK: CotEditorKanaType
@objc public enum CotEditorKanaType : AEKeyword {
case hiragana = 0x6348676e /* 'cHgn' */
case katakana = 0x634b6b6e /* 'cKkn' */
}
// MARK: CotEditorUNFType
@objc public enum CotEditorUNFType : AEKeyword {
case nfc = 0x634e6663 /* 'cNfc' */
case nfd = 0x634e6664 /* 'cNfd' */
case nfkc = 0x634e6b63 /* 'cNkc' */
case nfkd = 0x634e6b64 /* 'cNkd' */
case nfkcCasefold = 0x634e6366 /* 'cNcf' */
case modifiedNFC = 0x634e6d63 /* 'cNmc' */
case modifiedNFD = 0x634e666d /* 'cNfm' */
}
// MARK: CotEditorCharacterWidthType
@objc public enum CotEditorCharacterWidthType : AEKeyword {
case full = 0x7257666c /* 'rWfl' */
case half = 0x72576866 /* 'rWhf' */
}
// MARK: @protocol CotEditorGenericMethods
@objc public protocol CotEditorGenericMethods {
@objc optional func closeSaving(_ saving: CotEditorSaveOptions, savingIn: URL) // Close a document.
@objc optional func saveIn(_ in_: URL, as: CotEditorSaveableFileFormat) // Save a document.
@objc optional func printWithProperties(_ withProperties: [AnyHashable: Any]!, printDialog: Bool) // Print a document.
@objc optional func delete() // Delete an object.
@objc optional func duplicateTo(_ to: SBObject!, withProperties: [AnyHashable: Any]!) // Copy an object.
@objc optional func moveTo(_ to: SBObject!) // Move an object to a new location.
}
/*
* Standard Suite
*/
// The application's top-level scripting object.
// MARK: @interface CotEditorApplication
@objc public protocol CotEditorApplication: SBApplicationProtocol {
@objc optional func documents() -> SBElementArray
@objc optional func windows() -> SBElementArray
@objc optional var name: String { get } // The name of the application.
@objc optional var frontmost: Bool { get } // Is this the active application?
@objc optional var version: String { get } // The version number of the application.
@objc optional func open(_ x: Any!) -> Any // Open a document.
@objc optional func print(_ x: Any!, withProperties: [AnyHashable: Any]!, printDialog: Bool) // Print a document.
@objc optional func quitSaving(_ saving: CotEditorSaveOptions) // Quit the application.
@objc optional func exists(_ x: Any!) -> Bool // Verify that an object exists.
}
extension SBApplication: CotEditorApplication {}
// A document.
// MARK: @interface CotEditorDocument
@objc public protocol CotEditorDocument: SBObjectProtocol, CotEditorGenericMethods {
@objc optional var name: String { get } // Its name.
@objc optional var modified: Bool { get } // Has it been modified since the last save?
@objc optional var file: URL? { get } // Its location on disk, if it has one.
@objc optional func convertLossy(_ lossy: Bool, to: String) -> Bool // Convert the document text to new encoding.
@objc optional func findFor(_ for_: String, backwards: Bool, ignoreCase: Bool, RE: Bool, wrap: Bool) -> Bool // Search text.
@objc optional func reinterpretAs(_ as: String) -> Bool // Reinterpret the document text as new encoding.
@objc optional func replaceFor(_ for_: String, to: String, all: Bool, backwards: Bool, ignoreCase: Bool, RE: Bool, wrap: Bool) -> Int // Replace text.
@objc optional func scrollToCaret() // Scroll document to caret or selected text.
@objc optional func stringIn(_ in_: [Any]!) -> String // Get text in desired range.
// CotEditorDocument CotEditorSuite
@objc optional var text: CotEditorAttributeRun { get } // The whole text of the document.
@objc optional func setText(_ text: CotEditorAttributeRun!) // The whole text of the document.
@objc optional var coloringStyle: String { get } // The current syntax style name.
@objc optional func setColoringStyle(_ coloringStyle: String!) // The current syntax style name.
/// The contents of the document.
@objc optional var contents: CotEditorAttributeRun { get } // The contents of the document.
@objc optional func setContents(_ contents: CotEditorAttributeRun!) // The contents of the document.
@objc optional var encoding: String { get } // The encoding name of the document.
@objc optional var IANACharset: String { get } // The IANA charset name of the document.
@objc optional var length: Int { get } // The number of characters in the document.
@objc optional var lineEnding: CotEditorLineEndingCharacter { get } // The line ending type of the document.
@objc optional func setLineEnding(_ lineEnding: CotEditorLineEndingCharacter) // The line ending type of the document.
@objc optional var tabWidth: Int { get } // The width of a tab character in space equivalents.
@objc optional func setTabWidth(_ tabWidth: Int) // The width of a tab character in space equivalents.
@objc optional var expandsTab: Bool { get } // Are tab characters expanded to space?
@objc optional func setExpandsTab(_ expandsTab: Bool) // Are tab characters expanded to space?
@objc optional var selection: CotEditorTextSelection { get } // The current selection.
@objc optional func setSelection(_ selection: CotEditorTextSelection!) // The current selection.
@objc optional var wrapLines: Bool { get } // Are lines wrapped?
@objc optional func setWrapLines(_ wrapLines: Bool) // Are lines wrapped?
}
extension SBObject: CotEditorDocument {}
// A window.
// MARK: @interface CotEditorWindow
@objc public protocol CotEditorWindow: SBObjectProtocol, CotEditorGenericMethods {
@objc optional var name: String { get } // The title of the window.
@objc optional func id() -> Int // The unique identifier of the window.
@objc optional var index: Int { get } // The index of the window, ordered front to back.
@objc optional func setIndex(_ index: Int) // The index of the window, ordered front to back.
@objc optional var bounds: NSRect { get } // The bounding rectangle of the window.
@objc optional func setBounds(_ bounds: NSRect) // The bounding rectangle of the window.
@objc optional var closeable: Bool { get } // Does the window have a close button?
@objc optional var miniaturizable: Bool { get } // Does the window have a minimize button?
@objc optional var miniaturized: Bool { get } // Is the window minimized right now?
@objc optional func setMiniaturized(_ miniaturized: Bool) // Is the window minimized right now?
@objc optional var resizable: Bool { get } // Can the window be resized?
@objc optional var visible: Bool { get } // Is the window visible right now?
@objc optional func setVisible(_ visible: Bool) // Is the window visible right now?
@objc optional var zoomable: Bool { get } // Does the window have a zoom button?
@objc optional var zoomed: Bool { get } // Is the window zoomed right now?
@objc optional func setZoomed(_ zoomed: Bool) // Is the window zoomed right now?
@objc optional var document: CotEditorDocument { get } // The document whose contents are displayed in the window.
// CotEditorWindow (CotEditorSuite)
@objc optional var viewOpacity: Double { get } // The opacity of the text view. (from ‘0.2’ to ‘1.0’)
@objc optional func setViewOpacity(_ viewOpacity: Double) // The opacity of the text view. (from ‘0.2’ to ‘1.0’)
}
extension SBObject: CotEditorWindow {}
// A way to refer to the state of the current selection.
// MARK: @interface CotEditorTextSelection
@objc public protocol CotEditorTextSelection: SBObjectProtocol, CotEditorGenericMethods {
@objc optional var contents: CotEditorAttributeRun { get } // The contents of the selection.
@objc optional func setContents(_ contents: CotEditorAttributeRun!) // The contents of the selection.
@objc optional var lineRange: [NSNumber] { get } // The range of lines of the selection. The format is “{location, length}”.
@objc optional func setLineRange(_ lineRange: [NSNumber]!) // The range of lines of the selection. The format is “{location, length}”.
@objc optional var range: [NSNumber] { get } // The range of characters in the selection. The format is “{location, length}”.
@objc optional func setRange(_ range: [NSNumber]!) // The range of characters in the selection. The format is “{location, length}”.
@objc optional func changeCaseTo(_ to: CotEditorCaseType) // Change the case of the selection.
@objc optional func changeKanaTo(_ to: CotEditorKanaType) // Change Japanese “Kana” mode of the selection.
@objc optional func changeRomanWidthTo(_ to: CotEditorCharacterWidthType) // Change width of Japanese roman characters in the selection.
@objc optional func shiftLeft() // Shift selected lines to left.
@objc optional func shiftRight() // Shift selected lines to right.
@objc optional func moveLineUp() // Swap selected lines with the line just above.
@objc optional func moveLineDown() // Swap selected lines with the line just below
@objc optional func sortLines() // Sort selected lines ascending
@objc optional func reverseLines() // Reverse selected lines
@objc optional func deleteDuplicateLine() // Delete duplicate lines in selection
@objc optional func commentOut() // Append comment delimiters to selected text if possible.
@objc optional func uncomment() // Remove comment delimiters from selected text if possible.
@objc optional func normalizeUnicodeTo(_ to: CotEditorUNFType) // Normalize Unicode.
}
extension SBObject: CotEditorTextSelection {}
/*
* Text Suite
*/
// Rich (styled) text.
// MARK: @interface CotEditorRichText
@objc public protocol CotEditorRichText: SBObjectProtocol, CotEditorGenericMethods {
@objc optional func characters() -> SBElementArray
@objc optional func paragraphs() -> SBElementArray
@objc optional func words() -> SBElementArray
@objc optional func attributeRuns() -> SBElementArray
@objc optional func attachments() -> SBElementArray
@objc optional var color: NSColor { get } // The color of the text’s first character.
@objc optional func setColor(_ color: NSColor!) // The color of the text’s first character.
@objc optional var font: String { get } // The name of the font of the text’s first character.
@objc optional func setFont(_ font: String!) // The name of the font of the text’s first character.
@objc optional var size: Int { get } // The size in points of the text’s first character.
@objc optional func setSize(_ size: Int) // The size in points of the text’s first character.
}
extension SBObject: CotEditorRichText {}
// One of some text’s characters.
// MARK: @interface CotEditorCharacter
@objc public protocol CotEditorCharacter: SBObjectProtocol, CotEditorGenericMethods {
@objc optional func characters() -> SBElementArray
@objc optional func paragraphs() -> SBElementArray
@objc optional func words() -> SBElementArray
@objc optional func attributeRuns() -> SBElementArray
@objc optional func attachments() -> SBElementArray
@objc optional var color: NSColor { get } // Its color.
@objc optional func setColor(_ color: NSColor!) // Its color.
@objc optional var font: String { get } // The name of its font.
@objc optional func setFont(_ font: String!) // The name of its font.
@objc optional var size: Int { get } // Its size, in points.
@objc optional func setSize(_ size: Int) // Its size, in points.
}
extension SBObject: CotEditorCharacter {}
// One of some text’s paragraphs.
// MARK: @interface CotEditorParagraph
@objc public protocol CotEditorParagraph: SBObjectProtocol, CotEditorGenericMethods {
@objc optional func characters() -> SBElementArray
@objc optional func paragraphs() -> SBElementArray
@objc optional func words() -> SBElementArray
@objc optional func attributeRuns() -> SBElementArray
@objc optional func attachments() -> SBElementArray
@objc optional var color: NSColor { get } // The color of the paragraph’s first character.
@objc optional func setColor(_ color: NSColor!) // The color of the paragraph’s first character.
@objc optional var font: String { get } // The name of the font of the paragraph’s first character.
@objc optional func setFont(_ font: String!) // The name of the font of the paragraph’s first character.
@objc optional var size: Int { get } // The size in points of the paragraph’s first character.
@objc optional func setSize(_ size: Int) // The size in points of the paragraph’s first character.
}
extension SBObject: CotEditorParagraph {}
// One of some text’s words.
// MARK: @interface CotEditorWord
@objc public protocol CotEditorWord: SBObjectProtocol, CotEditorGenericMethods {
@objc optional func characters() -> SBElementArray
@objc optional func paragraphs() -> SBElementArray
@objc optional func words() -> SBElementArray
@objc optional func attributeRuns() -> SBElementArray
@objc optional func attachments() -> SBElementArray
@objc optional var color: NSColor { get } // The color of the word’s first character.
@objc optional func setColor(_ color: NSColor!) // The color of the word’s first character.
@objc optional var font: String { get } // The name of the font of the word’s first character.
@objc optional func setFont(_ font: String!) // The name of the font of the word’s first character.
@objc optional var size: Int { get } // The size in points of the word’s first character.
@objc optional func setSize(_ size: Int) // The size in points of the word’s first character.
}
extension SBObject: CotEditorWord {}
// A chunk of text that all has the same attributes.
// MARK: @interface CotEditorAttributeRun
@objc public protocol CotEditorAttributeRun: SBObjectProtocol, CotEditorGenericMethods {
@objc optional func characters() -> SBElementArray
@objc optional func paragraphs() -> SBElementArray
@objc optional func words() -> SBElementArray
@objc optional func attributeRuns() -> SBElementArray
@objc optional func attachments() -> SBElementArray
@objc optional var color: NSColor { get } // Its color.
@objc optional func setColor(_ color: NSColor!) // Its color.
@objc optional var font: String { get } // The name of its font.
@objc optional func setFont(_ font: String!) // The name of its font.
@objc optional var size: Int { get } // Its size, in points.
@objc optional func setSize(_ size: Int) // Its size, in points.
}
extension SBObject: CotEditorAttributeRun {}
// A file embedded in text. This is just for use when embedding a file using the make command.
// MARK: @interface CotEditorAttachment
@objc public protocol CotEditorAttachment: CotEditorRichText {
@objc optional var fileName: String { get } // The path to the embedded file.
@objc optional func setFileName(_ fileName: String!) // The path to the embedded file.
}
extension SBObject: CotEditorAttachment {}
|
mit
|
54a59a8c9dfcdfba9814d1ec1dcc28d8
| 54.644068 | 154 | 0.715504 | 4.258106 | false | false | false | false |
justinmakaila/Moya
|
Tests/Error+MoyaSpec.swift
|
1
|
2389
|
import Nimble
import Moya
public func beOfSameErrorType(_ expectedValue: MoyaError) -> Predicate<MoyaError> {
return Predicate { expression -> PredicateResult in
let test: Bool
if let value = try expression.evaluate() {
switch value {
case .imageMapping:
switch expectedValue {
case .imageMapping:
test = true
default:
test = false
}
case .jsonMapping:
switch expectedValue {
case .jsonMapping:
test = true
default:
test = false
}
case .stringMapping:
switch expectedValue {
case .stringMapping:
test = true
default:
test = false
}
case .objectMapping:
switch expectedValue {
case .objectMapping:
test = true
default:
test = false
}
case .encodableMapping:
switch expectedValue {
case .objectMapping:
test = true
default:
test = false
}
case .statusCode:
switch expectedValue {
case .statusCode:
test = true
default:
test = false
}
case .underlying:
switch expectedValue {
case .underlying:
test = true
default:
test = false
}
case .requestMapping:
switch expectedValue {
case .requestMapping:
test = true
default:
test = false
}
case .parameterEncoding:
switch expectedValue {
case .parameterEncoding:
test = true
default:
test = false
}
}
} else {
test = false
}
return PredicateResult(bool: test, message: .expectedActualValueTo("<\(expectedValue)>"))
}
}
|
mit
|
52e75aba5ed36528919274ea07292cf4
| 29.240506 | 97 | 0.399749 | 7.195783 | false | true | false | false |
robconrad/fledger-common
|
FledgerCommon/services/models/aggregate/AggregateServiceImpl.swift
|
1
|
3776
|
//
// Aggregates.swift
// fledger-ios
//
// Created by Robert Conrad on 4/12/15.
// Copyright (c) 2015 TwoSpec Inc. All rights reserved.
//
import Foundation
import SQLite
class AggregateServiceImpl: AggregateService {
private let items: SchemaType
private let groups: SchemaType
private let types: SchemaType
private let accounts: SchemaType
private let accountId: Expression<Int64>
private let groupId: Expression<Int64>
private let typeId: Expression<Int64>
private let name: Expression<String>
private let priority: Expression<Int>
private let inactive: Expression<Bool>
private let accountName: Expression<String>
private let groupName: Expression<String>
private let typeName: Expression<String>
private let sumAmount = Expressions.sumAmount
private let allQuery: ScalarQuery<Double?>
private let accountsQuery: SchemaType
private let groupsQuery: SchemaType
private let typesQuery: SchemaType
required init() {
items = DatabaseSvc().items
groups = DatabaseSvc().groups
types = DatabaseSvc().types
accounts = DatabaseSvc().accounts
accountId = accounts[Fields.id]
groupId = groups[Fields.id]
typeId = types[Fields.id]
name = Fields.name
priority = Fields.priority
inactive = Fields.inactive
accountName = accounts[name]
groupName = groups[name]
typeName = types[name]
allQuery = items
.select(sumAmount)
accountsQuery = accounts
.select(accountId, accountName, sumAmount, inactive)
.join(.LeftOuter, items, on: Fields.accountId == accountId)
.group(accountId)
.order(inactive, priority, accountName.collate(.Nocase))
groupsQuery = groups
.select(groupId, groupName, sumAmount)
.join(.LeftOuter, types, on: Fields.groupId == groupId)
.join(.LeftOuter, items, on: Fields.typeId == typeId)
.group(groupId)
.order(groupName.collate(.Nocase))
typesQuery = types
.select(typeId, typeName, groupName, sumAmount)
.join(.LeftOuter, items, on: Fields.typeId == typeId)
.join(.LeftOuter, groups, on: Fields.groupId == groupId)
.group(typeId)
.order(groupName.collate(.Nocase), typeName.collate(.Nocase))
}
private func aggregate(model: ModelType, query: SchemaType, id: Expression<Int64>, name: Expression<String>, checkActive: Bool = false) -> [Aggregate] {
var result: [Aggregate] = []
for row in DatabaseSvc().db.prepare(query) {
var active = true
if checkActive {
active = !row.get(inactive)
}
var section: String?
if model == ModelType.Typ {
section = row.get(groupName)
}
result.append(Aggregate(model: model, id: row.get(id), name: row.get(name), value: row.get(sumAmount) ?? 0, active: active, section: section))
}
return result
}
func getAll() -> [Aggregate] {
return [Aggregate(model: nil, id: nil, name: "all", value: DatabaseSvc().db.scalar(allQuery) ?? 0)]
}
func getAccounts() -> [Aggregate] {
return aggregate(ModelType.Account, query: accountsQuery, id: accountId, name: name, checkActive: true)
}
func getGroups() -> [Aggregate] {
return aggregate(ModelType.Group, query: groupsQuery, id: groupId, name: name)
}
func getTypes() -> [Aggregate] {
return aggregate(ModelType.Typ, query: typesQuery, id: typeId, name: typeName)
}
}
|
mit
|
6c9e3903060fa21a467fcf4f0de8bbd1
| 33.027027 | 156 | 0.612288 | 4.484561 | false | false | false | false |
Raizlabs/ios-template
|
{{ cookiecutter.project_name | replace(' ', '') }}/app/Services/API/APISerialization.swift
|
1
|
2180
|
///
// APISerialization.swift
// {{ cookiecutter.project_name | replace(' ', '') }}
//
// Created by {{ cookiecutter.lead_dev }} on {% now 'utc', '%D' %}.
// Copyright © {% now 'utc', '%Y' %} {{ cookiecutter.company_name }}. All rights reserved.
//
import Alamofire
import Swiftilities
private func ResponseSerializer<T>(_ serializer: @escaping (Data) throws -> T) -> DataResponseSerializer<T> {
return DataResponseSerializer { _, _, data, error in
guard let data = data else {
return .failure(error ?? APIError.noData)
}
if let error = error {
do {
let knownError = try JSONDecoder.default.decode({{ cookiecutter.project_name | replace(' ', '') }}Error.self, from: data)
return .failure(knownError)
} catch let decodeError {
let string = String(data: data, encoding: .utf8)
Log.info("Could not decode error, falling back to generic error: \(decodeError) \(String(describing: string))")
}
if let errorDictionary = (try? JSONSerialization.jsonObject(with: data, options: [.allowFragments])) as? [String: Any] {
return .failure({{ cookiecutter.project_name | replace(' ', '') }}Error.unknown(errorDictionary))
}
return .failure(error)
}
do {
return .success(try serializer(data))
} catch let decodingError {
return .failure(decodingError)
}
}
}
func APIObjectResponseSerializer<Endpoint: APIEndpoint>(_ endpoint: Endpoint) -> DataResponseSerializer<Void> where Endpoint.ResponseType == Payload.Empty {
return ResponseSerializer { data in
endpoint.log(data)
}
}
/// Response serializer to import JSON Object using JSONDecoder and return an object
func APIObjectResponseSerializer<Endpoint: APIEndpoint>(_ endpoint: Endpoint) -> DataResponseSerializer<Endpoint.ResponseType> where Endpoint.ResponseType: Decodable {
return ResponseSerializer { data in
endpoint.log(data)
let decoder = JSONDecoder.default
return try decoder.decode(Endpoint.ResponseType.self, from: data)
}
}
|
mit
|
b3064b3ad9144b802f3428d364b4f2f0
| 41.72549 | 167 | 0.635154 | 4.696121 | false | false | false | false |
MadAppGang/SmartLog
|
iOS/Pods/CoreStore/Sources/OrderBy.swift
|
2
|
4993
|
//
// OrderBy.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
// MARK: - KeyPath
public typealias KeyPath = String
// MARK: - SortKey
/**
The `SortKey` is passed to the `OrderBy` clause to indicate the sort keys and their sort direction.
*/
public enum SortKey {
/**
Indicates that the `KeyPath` should be sorted in ascending order
*/
case ascending(KeyPath)
/**
Indicates that the `KeyPath` should be sorted in descending order
*/
case descending(KeyPath)
}
// MARK: - OrderBy
/**
The `OrderBy` clause specifies the sort order for results for a fetch or a query.
*/
public struct OrderBy: FetchClause, QueryClause, DeleteClause, Hashable {
/**
Combines two `OrderBy` sort descriptors together
*/
public static func + (left: OrderBy, right: OrderBy) -> OrderBy {
return OrderBy(left.sortDescriptors + right.sortDescriptors)
}
/**
Combines two `OrderBy` sort descriptors together and stores the result to the left operand
*/
public static func += (left: inout OrderBy, right: OrderBy) {
left = left + right
}
/**
The list of sort descriptors
*/
public let sortDescriptors: [NSSortDescriptor]
/**
Initializes a `OrderBy` clause with an empty list of sort descriptors
*/
public init() {
self.init([NSSortDescriptor]())
}
/**
Initializes a `OrderBy` clause with a single sort descriptor
- parameter sortDescriptor: a `NSSortDescriptor`
*/
public init(_ sortDescriptor: NSSortDescriptor) {
self.init([sortDescriptor])
}
/**
Initializes a `OrderBy` clause with a list of sort descriptors
- parameter sortDescriptors: a series of `NSSortDescriptor`s
*/
public init(_ sortDescriptors: [NSSortDescriptor]) {
self.sortDescriptors = sortDescriptors
}
/**
Initializes a `OrderBy` clause with a series of `SortKey`s
- parameter sortKey: a series of `SortKey`s
*/
public init(_ sortKey: [SortKey]) {
self.init(
sortKey.map { sortKey -> NSSortDescriptor in
switch sortKey {
case .ascending(let keyPath):
return NSSortDescriptor(key: keyPath, ascending: true)
case .descending(let keyPath):
return NSSortDescriptor(key: keyPath, ascending: false)
}
}
)
}
/**
Initializes a `OrderBy` clause with a series of `SortKey`s
- parameter sortKey: a single `SortKey`
- parameter sortKeys: a series of `SortKey`s
*/
public init(_ sortKey: SortKey, _ sortKeys: SortKey...) {
self.init([sortKey] + sortKeys)
}
// MARK: FetchClause, QueryClause, DeleteClause
public func applyToFetchRequest<ResultType: NSFetchRequestResult>(_ fetchRequest: NSFetchRequest<ResultType>) {
if let sortDescriptors = fetchRequest.sortDescriptors, sortDescriptors != self.sortDescriptors {
CoreStore.log(
.warning,
message: "Existing sortDescriptors for the \(cs_typeName(fetchRequest)) was overwritten by \(cs_typeName(self)) query clause."
)
}
fetchRequest.sortDescriptors = self.sortDescriptors
}
// MARK: Equatable
public static func == (lhs: OrderBy, rhs: OrderBy) -> Bool {
return lhs.sortDescriptors == rhs.sortDescriptors
}
// MARK: Hashable
public var hashValue: Int {
return (self.sortDescriptors as NSArray).hashValue
}
}
|
mit
|
7f25cad65422e7cf9bc406427fc8aeed
| 27.689655 | 142 | 0.622796 | 5.037336 | false | false | false | false |
shorlander/firefox-ios
|
Extensions/ShareTo/InitialViewController.swift
|
4
|
5870
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import Storage
private let LastUsedShareDestinationsKey = "LastUsedShareDestinations"
@objc(InitialViewController)
class InitialViewController: UIViewController, ShareControllerDelegate {
var shareDialogController: ShareDialogController!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(white: 0.0, alpha: 0.66) // TODO: Is the correct color documented somewhere?
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
ExtensionUtils.extractSharedItemFromExtensionContext(self.extensionContext, completionHandler: { (item, error) -> Void in
if let item = item, error == nil {
DispatchQueue.main.async {
guard item.isShareable else {
let alert = UIAlertController(title: Strings.SendToErrorTitle, message: Strings.SendToErrorMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Strings.SendToErrorOKButton, style: .default) { _ in self.finish() })
self.present(alert, animated: true, completion: nil)
return
}
self.presentShareDialog(item)
}
} else {
self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
}
})
}
//
func shareControllerDidCancel(_ shareController: ShareDialogController) {
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.shareDialogController.view.alpha = 0.0
}, completion: { (Bool) -> Void in
self.dismissShareDialog()
self.finish()
})
}
func finish() {
self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
}
func shareController(_ shareController: ShareDialogController, didShareItem item: ShareItem, toDestinations destinations: NSSet) {
setLastUsedShareDestinations(destinations)
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.shareDialogController.view.alpha = 0.0
}, completion: { (Bool) -> Void in
self.dismissShareDialog()
let profile = BrowserProfile(localName: "profile")
if destinations.contains(ShareDestinationReadingList) {
profile.readingList?.createRecordWithURL(item.url, title: item.title ?? "", addedBy: UIDevice.current.name)
}
if destinations.contains(ShareDestinationBookmarks) {
_ = profile.bookmarks.shareItem(item).value // Blocks until database has settled
}
profile.shutdown()
self.finish()
})
}
//
// TODO: use Set.
func getLastUsedShareDestinations() -> NSSet {
if let destinations = UserDefaults.standard.object(forKey: LastUsedShareDestinationsKey) as? NSArray {
return NSSet(array: destinations as [AnyObject])
}
return NSSet(object: ShareDestinationBookmarks)
}
func setLastUsedShareDestinations(_ destinations: NSSet) {
UserDefaults.standard.set(destinations.allObjects, forKey: LastUsedShareDestinationsKey)
UserDefaults.standard.synchronize()
}
func presentShareDialog(_ item: ShareItem) {
shareDialogController = ShareDialogController()
shareDialogController.delegate = self
shareDialogController.item = item
shareDialogController.initialShareDestinations = getLastUsedShareDestinations()
self.addChildViewController(shareDialogController)
shareDialogController.view.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(shareDialogController.view)
shareDialogController.didMove(toParentViewController: self)
// Setup constraints for the dialog. We keep the dialog centered with 16 points of padding on both
// sides. The dialog grows to max 380 points wide so that it does not look too big on landscape or
// iPad devices.
let views: NSDictionary = ["dialog": shareDialogController.view]
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(16@751)-[dialog(<=380@1000)]-(16@751)-|",
options: NSLayoutFormatOptions(), metrics: nil, views: (views as? [String : AnyObject])!))
let cx = NSLayoutConstraint(item: shareDialogController.view, attribute: NSLayoutAttribute.centerX,
relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: 0)
cx.priority = 1000 // TODO: Why does UILayoutPriorityRequired give a linker error? SDK Bug?
view.addConstraint(cx)
view.addConstraint(NSLayoutConstraint(item: shareDialogController.view, attribute: NSLayoutAttribute.centerY,
relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1.0, constant: 0))
// Fade the dialog in
shareDialogController.view.alpha = 0.0
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.shareDialogController.view.alpha = 1.0
}, completion: nil)
}
func dismissShareDialog() {
shareDialogController.willMove(toParentViewController: nil)
shareDialogController.view.removeFromSuperview()
shareDialogController.removeFromParentViewController()
}
}
|
mpl-2.0
|
3c2df8eb2a54f9b767be92c3f9ae1493
| 42.161765 | 147 | 0.657922 | 5.37054 | false | false | false | false |
algolia/algoliasearch-client-swift
|
Sources/AlgoliaSearchClient/Models/Internal/HTTP/HTTPError.swift
|
1
|
1091
|
//
// HTTPError.swift
//
//
// Created by Vladislav Fitc on 02/03/2020.
//
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
public struct HTTPError: Error, CustomStringConvertible {
public let statusCode: HTTPStatusСode
public let message: ErrorMessage?
public init?(response: HTTPURLResponse?, data: Data?) {
guard let response = response, !response.statusCode.belongs(to: .success) else {
return nil
}
let message = data.flatMap { try? JSONDecoder().decode(ErrorMessage.self, from: $0) }
self.init(statusCode: response.statusCode, message: message)
}
public init(statusCode: HTTPStatusСode, message: ErrorMessage?) {
self.statusCode = statusCode
self.message = message
}
public var description: String {
return "Status code: \(statusCode) Message: \(message.flatMap { $0.description } ?? "No message")"
}
}
public struct ErrorMessage: Codable, CustomStringConvertible {
enum CodingKeys: String, CodingKey {
case description = "message"
}
public let description: String
}
|
mit
|
f95401204a5e5b92efb4bd5f8823423c
| 22.673913 | 102 | 0.714417 | 4.22093 | false | false | false | false |
rdlester/simply-giphy
|
Pods/Moya-Gloss/Source/Response+Gloss.swift
|
1
|
2096
|
//
// Response+Gloss.swift
//
// Created by steven rogers on 4/5/16.
// Copyright (c) 2016 Steven Rogers
//
import Moya
import Gloss
/// Moya-Gloss extension for Moya.Response to allow Gloss bindings.
public extension Response {
/// Maps response data into a model object implementing the Decodable protocol.
/// Throws a JSONMapping error on failure.
public func mapObject<T: Gloss.Decodable>(_ type: T.Type) throws -> T {
guard
let json = try mapJSON() as? JSON,
let result = T(json: json)
else {
throw MoyaError.jsonMapping(self)
}
return result
}
/// Maps nested response data into a model object implementing the Decodable protocol.
/// Throws a JSONMapping error on failure.
public func mapObject<T: Gloss.Decodable>(_ type: T.Type, forKeyPath keyPath: String) throws -> T {
guard
let json = try mapJSON() as? NSDictionary,
let nested = json.value(forKeyPath: keyPath) as? JSON,
let result = T(json: nested)
else {
throw MoyaError.jsonMapping(self)
}
return result
}
/// Maps the response data into an array of model objects implementing the Decodable protocol.
/// Throws a JSONMapping error on failure.
public func mapArray<T: Gloss.Decodable>(_ type: T.Type) throws -> [T] {
guard
let json = try mapJSON() as? [JSON]
else {
throw MoyaError.jsonMapping(self)
}
if let models = [T].from(jsonArray: json) {
return models
} else {
throw MoyaError.jsonMapping(self)
}
}
/// Maps the nested response data into an array of model objects implementing the Decodable protocol.
/// Throws a JSONMapping error on failure.
public func mapArray<T: Gloss.Decodable>(_ type: T.Type, forKeyPath keyPath: String) throws -> [T] {
guard
let json = try mapJSON() as? NSDictionary,
let nested = json.value(forKeyPath: keyPath) as? [JSON]
else {
throw MoyaError.jsonMapping(self)
}
if let models = [T].from(jsonArray: nested) {
return models
} else {
throw MoyaError.jsonMapping(self)
}
}
}
|
apache-2.0
|
32d538537dec0da53ac36445823eae8e
| 28.521127 | 103 | 0.66126 | 4.125984 | false | false | false | false |
daltonclaybrook/swift-promises
|
Promises/PromiseManager.swift
|
1
|
2890
|
//
// PromiseManager.swift
// Promises
//
// Created by Dalton Claybrook on 7/1/15.
// Copyright © 2015 Claybrook Software, LLC. All rights reserved.
//
class PromiseManager {
static let sharedManager = PromiseManager()
private var blockChains = [Promise:Array<PromiseBlock>]()
private var errorBlocks = [Promise:CatchBlock]()
private var doneBlocks = [Promise:DoneBlock]()
func chainBlock(block: PromiseBlock, forPromise promise: Promise) {
var chain: [PromiseBlock]! = blockChains[promise]
if (chain == nil) {
chain = [PromiseBlock]()
}
chain.append(block)
blockChains[promise] = chain
}
func attachErrorBlock(block: CatchBlock, forPromise promise: Promise) {
errorBlocks[promise] = block
}
func executeChainForPromise(promise: Promise, withDoneBlock block: DoneBlock?) {
guard let chain = blockChains[promise] else {
assertionFailure("no blocks have been registered")
return
}
if let block = block {
doneBlocks[promise] = block
}
blockChains.removeValueForKey(promise)
executeChain(chain, forPromise: promise, blockParam: nil)
}
private func executeChain(var chain: [PromiseBlock], forPromise promise: Promise, blockParam: AnyObject?) {
var lastObj: AnyObject? = blockParam
var finished = true
while (chain.count > 0) {
let block = chain.removeAtIndex(0)
// execute synchronous blocks
do {
try lastObj = block(lastObj)
} catch let err {
self.executeError(err, forPromise: promise)
finished = false
break
}
// execute wait for deffered blocks if necessary
if let deferred = lastObj as? DeferredPromise {
deferred.waitAndExecute { obj in
self.executeChain(chain, forPromise: promise, blockParam: obj)
}
deferred.waitAndFail { err in
self.executeError(err, forPromise: promise)
}
finished = false
break
}
}
if finished {
executeDoneBlockIfNecessaryForPromise(promise)
}
}
private func executeError(error: ErrorType, forPromise promise: Promise) {
if let block = errorBlocks[promise] {
block(error)
}
executeDoneBlockIfNecessaryForPromise(promise)
}
private func executeDoneBlockIfNecessaryForPromise(promise: Promise) {
if let block = doneBlocks[promise] {
block()
}
}
}
|
mit
|
fa18b32f25d4f3599e200ec67d6713bb
| 28.783505 | 111 | 0.553825 | 5.059545 | false | false | false | false |
antonio081014/LeeCode-CodeBase
|
Swift/longest-common-subsequence.swift
|
2
|
942
|
/**
* https://leetcode.com/problems/longest-common-subsequence/
*
*
*/
// Date: Sun Apr 26 09:36:42 PDT 2020
class Solution {
func longestCommonSubsequence(_ text1: String, _ text2: String) -> Int {
var cost = Array(repeating: Array(repeating: 0, count: text2.count + 1), count: text1.count + 1)
let text1 = Array(text1)
let text2 = Array(text2)
for i in 0 ..< text1.count {
for j in 0 ..< text2.count {
cost[i + 1][j + 1] = max(cost[i + 1][j + 1], cost[i][j])
cost[i + 1][j + 1] = max(cost[i + 1][j + 1], cost[i + 1][j])
cost[i + 1][j + 1] = max(cost[i + 1][j + 1], cost[i][j + 1])
if text1[i] == text2[j] {
cost[i + 1][j + 1] = max(1 + cost[i][j], cost[i + 1][j + 1])
}
}
}
// print("\(cost)")
return cost[text1.count][text2.count]
}
}
|
mit
|
f7ad697586414c3f25e7631b0905a1cb
| 35.230769 | 104 | 0.45966 | 3.03871 | false | false | false | false |
samirahmed/iosRadialMenu
|
RadialMenu/RadialMenu.swift
|
1
|
12130
|
//
// RadialMenu.swift
// RadialMenu
//
// Created by Brad Jasper on 6/5/14.
// Copyright (c) 2014 Brad Jasper. All rights reserved.
//
// FIXME: Split out into smaller pieces
import UIKit
import QuartzCore
let defaultRadius:CGFloat = 115
@IBDesignable
class RadialMenu: UIView, RadialSubMenuDelegate {
// configurable properties
@IBInspectable var radius:CGFloat = defaultRadius
@IBInspectable var subMenuScale:CGFloat = 0.75
@IBInspectable var highlightScale:CGFloat = 1.15
var subMenuRadius: CGFloat {
get {
return radius * subMenuScale
}
}
var subMenuHighlightedRadius: CGFloat {
get {
return radius * (subMenuScale * highlightScale)
}
}
@IBInspectable var radiusStep = 0.0
@IBInspectable var openDelayStep = 0.05
@IBInspectable var closeDelayStep = 0.035
@IBInspectable var activatedDelay = 0.0
@IBInspectable var minAngle = 180
@IBInspectable var maxAngle = 540
@IBInspectable var allowMultipleHighlights = false
// get's set automatically on initialized to a percentage of radius
@IBInspectable var highlightDistance:CGFloat = 0
// FIXME: Needs better solution
// Fixes issue with highlighting too close to center (get set automatically..can be changed)
var minHighlightDistance:CGFloat = 0
// Callbacks
// FIXME: Easier way to handle optional callbacks?
typealias RadialMenuCallback = () -> ()
typealias RadialSubMenuCallback = (subMenu: RadialSubMenu) -> ()
var onOpening: RadialMenuCallback?
var onOpen: RadialMenuCallback?
var onClosing: RadialMenuCallback?
var onClose: RadialMenuCallback?
var onHighlight: RadialSubMenuCallback?
var onUnhighlight: RadialSubMenuCallback?
var onActivate: RadialSubMenuCallback?
// FIXME: Is it possible to scale a view without changing it's children? Couldn't get that
// working so put bg on it's own view
let backgroundView = UIView()
// FIXME: Make private when Swift adds access controls
var subMenus: [RadialSubMenu]
var numOpeningSubMenus = 0
var numOpenedSubMenus = 0
var numHighlightedSubMenus = 0
var addedConstraints = false
var position = CGPointZero
enum State {
case Closed, Opening, Opened, Highlighted, Unhighlighted, Activated, Closing
}
var state: State = .Closed {
didSet {
if oldValue == state { return }
// FIXME: open/close callbacks are called up here but (un)highlight/activate are called below
// we're abusing the fact that state changes are only called once here
// but can't pass submenu context without ugly global state
switch state {
case .Closed:
onClose?()
case .Opened:
onOpen?()
case .Opening:
onOpening?()
case .Closing:
onClosing?()
default:
break
}
}
}
// MARK: Init
required init(coder decoder: NSCoder) {
subMenus = []
super.init(coder: decoder)
}
override init(frame: CGRect) {
subMenus = []
super.init(frame: frame)
}
convenience init(menus: [RadialSubMenu]) {
self.init(menus: menus, radius: defaultRadius)
}
convenience init(menus: [RadialSubMenu], radius: CGFloat) {
self.init(frame: CGRect(x: 0, y: 0, width: radius*2, height: radius*2))
self.subMenus = menus
self.radius = radius
for (i, menu) in enumerate(subMenus) {
menu.delegate = self
menu.tag = i
self.addSubview(menu)
}
setup()
}
func setup() {
layer.zPosition = -2
// set a sane highlight distance by default..might need to be tweaked based on your needs
highlightDistance = radius * 0.75 // allow aggressive highlights near submenu
minHighlightDistance = radius * 0.25 // but not within 25% of center
backgroundView.backgroundColor = UIColor.grayColor().colorWithAlphaComponent(0.5)
backgroundView.layer.zPosition = -1
backgroundView.frame = CGRectMake(0, 0, radius*2, radius*2)
backgroundView.layer.cornerRadius = radius
backgroundView.center = center
// Initial transform size can't be 0 - https://github.com/facebook/pop/issues/24
backgroundView.transform = CGAffineTransformMakeScale(0.000001, 0.000001)
addSubview(backgroundView)
}
func resetDefaults() {
numOpenedSubMenus = 0
numOpeningSubMenus = 0
numHighlightedSubMenus = 0
for subMenu in subMenus {
subMenu.removeAllAnimations()
}
}
func openAtPosition(newPosition: CGPoint) {
let max = subMenus.count
if max == 0 {
return println("No submenus to open")
}
if state != .Closed {
return println("Can only open closed menus")
}
resetDefaults()
state = .Opening
position = newPosition
show()
let relPos = convertPoint(position, fromView:superview)
for (i, subMenu) in enumerate(subMenus) {
let subMenuPos = getPositionForSubMenu(subMenu)
let delay = openDelayStep * Double(i)
numOpeningSubMenus++
subMenu.openAt(subMenuPos, fromPosition: relPos, delay: delay)
}
}
func getAngleForSubMenu(subMenu: RadialSubMenu) -> Double {
let fullCircle = isFullCircle(minAngle, maxAngle)
let max = fullCircle ? subMenus.count : subMenus.count - 1
return getAngleForIndex(subMenu.tag, max, Double(minAngle), Double(maxAngle))
}
func getPositionForSubMenu(subMenu: RadialSubMenu) -> CGPoint {
return getPositionForSubMenu(subMenu, radius: Double(subMenuRadius))
}
func getExpandedPositionForSubMenu(subMenu: RadialSubMenu) -> CGPoint {
return getPositionForSubMenu(subMenu, radius: Double(subMenuHighlightedRadius))
}
func getPositionForSubMenu(subMenu: RadialSubMenu, radius: Double) -> CGPoint {
let angle = getAngleForSubMenu(subMenu)
let absRadius = radius + (radiusStep * Double(subMenu.tag))
let circlePos = getPointForAngle(angle, absRadius)
let relPos = CGPoint(x: position.x + circlePos.x, y: position.y + circlePos.y)
return self.convertPoint(relPos, fromView:self.superview)
}
func close() {
if (state == .Closed || state == .Closing) {
return println("Menu is already closed/closing")
}
state = .Closing
for (i, subMenu) in enumerate(subMenus) {
let delay = closeDelayStep * Double(i)
// FIXME: Why can't I use shortcut enum syntax .Highlighted here?
if subMenu.state == RadialSubMenu.State.Highlighted {
let closeDelay = (closeDelayStep * Double(subMenus.count)) + activatedDelay
subMenu.activate(closeDelay)
} else {
subMenu.close(delay)
}
}
}
// FIXME: Refactor entire method
func moveAtPosition(position:CGPoint) {
if state != .Opened && state != .Highlighted && state != .Unhighlighted {
return
}
let relPos = convertPoint(position, fromView:superview)
let distanceFromCenter = distanceBetweenPoints(position, center)
// Add all submenus within a certain distance to array
var distances:[(distance: Double, subMenu: RadialSubMenu)] = []
var highlightDistance = self.highlightDistance
if numHighlightedSubMenus > 0 {
highlightDistance = highlightDistance * highlightScale
}
for subMenu in subMenus {
let distance = distanceBetweenPoints(subMenu.center, relPos)
if distanceFromCenter >= Double(minHighlightDistance) && distance <= Double(highlightDistance) {
distances.append(distance: distance, subMenu: subMenu)
} else if subMenu.state == .Highlighted {
subMenu.unhighlight()
}
}
if distances.count == 0 { return }
distances.sort { $0.distance < $1.distance }
var shouldHighlight: [RadialSubMenu] = []
for (i, (_, subMenu)) in enumerate(distances) {
switch (i, allowMultipleHighlights) {
case (0, false), (_, true):
shouldHighlight.append(subMenu)
case (_, _) where subMenu.state == .Highlighted:
subMenu.unhighlight()
default:
break
}
}
// Make sure all submenus are unhighlighted before any should be highlighted
for subMenu in shouldHighlight {
subMenu.highlight()
}
}
// FIXME: Clean this up & make it more clear what's happening
func grow() {
scaleBackgroundView(highlightScale)
growSubMenus()
}
func shrink() {
scaleBackgroundView(1)
shrinkSubMenus()
}
func show() {
scaleBackgroundView(1)
}
func hide() {
scaleBackgroundView(0)
}
func scaleBackgroundView(size: CGFloat) {
var anim = backgroundView.pop_animationForKey("scale") as? POPSpringAnimation
let toValue = NSValue(CGPoint: CGPoint(x: size, y: size))
if ((anim) != nil) {
anim!.toValue = toValue
} else {
anim = POPSpringAnimation(propertyNamed: kPOPViewScaleXY)
anim!.toValue = toValue
backgroundView.pop_addAnimation(anim, forKey: "scale")
}
}
func growSubMenus() {
// FIXME: Refactor
for subMenu in subMenus {
let subMenuPos = getExpandedPositionForSubMenu(subMenu)
moveSubMenuToPosition(subMenu, pos: subMenuPos)
}
}
func shrinkSubMenus() {
// FIXME: Refactor
for subMenu in subMenus {
let subMenuPos = getPositionForSubMenu(subMenu)
moveSubMenuToPosition(subMenu, pos: subMenuPos)
}
}
func moveSubMenuToPosition(subMenu: RadialSubMenu, pos: CGPoint) {
var anim = subMenu.pop_animationForKey("expand") as? POPSpringAnimation
let toValue = NSValue(CGPoint: pos)
if ((anim) != nil) {
anim!.toValue = toValue
} else {
anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
anim!.toValue = toValue
subMenu.pop_addAnimation(anim, forKey: "expand")
}
}
// MARK: RadialSubMenuDelegate
func subMenuDidOpen(subMenu: RadialSubMenu) {
if ++numOpenedSubMenus == numOpeningSubMenus {
state = .Opened
}
}
func subMenuDidClose(subMenu: RadialSubMenu) {
if --numOpeningSubMenus == 0 || --numOpenedSubMenus == 0 {
hide()
state = .Closed
}
}
func subMenuDidHighlight(subMenu: RadialSubMenu) {
state = .Highlighted
onHighlight?(subMenu: subMenu)
if ++numHighlightedSubMenus >= 1 {
grow()
}
}
func subMenuDidUnhighlight(subMenu: RadialSubMenu) {
state = .Unhighlighted
onUnhighlight?(subMenu: subMenu)
if --numHighlightedSubMenus == 0 {
shrink()
}
}
func subMenuDidActivate(subMenu: RadialSubMenu) {
state = .Activated
onActivate?(subMenu: subMenu)
}
}
|
mit
|
0dae389c7cc761630906287b92cedb67
| 29.943878 | 108 | 0.583265 | 4.867576 | false | false | false | false |
jingyichushi/SwiftyOpenOauth
|
HeimdallTests/HeimdallSpec.swift
|
1
|
15972
|
import Heimdall
import LlamaKit
import Nimble
import OHHTTPStubs
import Quick
class OAuthAccessTokenMockStore: OAuthAccessTokenStore {
var storeAccessTokenCalled: Bool = false
var mockedAccessToken: OAuthAccessToken? = nil
var storedAccessToken: OAuthAccessToken? = nil
func storeAccessToken(accessToken: OAuthAccessToken?) {
storeAccessTokenCalled = true
storedAccessToken = accessToken
}
func retrieveAccessToken() -> OAuthAccessToken? {
return mockedAccessToken ?? storedAccessToken
}
}
class HeimdallResourceRequestMockAuthenticator: HeimdallResourceRequestAuthenticator {
func authenticateResourceRequest(request: NSURLRequest, accessToken: OAuthAccessToken) -> NSURLRequest {
var mutableRequest = request.mutableCopy() as NSMutableURLRequest
mutableRequest.addValue("totally", forHTTPHeaderField: "MockAuthorized")
return mutableRequest
}
}
class HeimdallSpec: QuickSpec {
let bundle = NSBundle(forClass: HeimdallSpec.self)
override func spec() {
var accessTokenStore: OAuthAccessTokenMockStore!
var heimdall: Heimdall!
beforeEach {
accessTokenStore = OAuthAccessTokenMockStore()
heimdall = Heimdall(tokenURL: NSURL(string: "http://rheinfabrik.de")!, accessTokenStore: accessTokenStore, resourceRequestAuthenticator: HeimdallResourceRequestMockAuthenticator())
}
describe("-init") {
context("when a token is saved in the store") {
it("loads the token from the token store") {
accessTokenStore.mockedAccessToken = OAuthAccessToken(accessToken: "foo", tokenType: "bar")
expect(heimdall.hasAccessToken).to(beTrue())
}
}
}
describe("-invalidateAccessToken") {
beforeEach {
accessTokenStore.storeAccessToken(OAuthAccessToken(accessToken: "foo", tokenType: "bar", expiresAt: NSDate(timeIntervalSinceNow: 3600)))
}
it("invalidates the currently stored access token") {
heimdall.invalidateAccessToken()
expect(accessTokenStore.retrieveAccessToken()?.expiresAt).to(equal(NSDate(timeIntervalSince1970: 0)))
}
}
describe("-clearAccessToken") {
beforeEach {
accessTokenStore.storeAccessToken(OAuthAccessToken(accessToken: "foo", tokenType: "bar", expiresAt: NSDate(timeIntervalSinceNow: 3600)))
}
it("clears the currently stored access token") {
heimdall.clearAccessToken()
expect(heimdall.hasAccessToken).to(beFalse())
}
}
describe("-requestAccessToken") {
var result: Result<Void, NSError>?
afterEach {
result = nil
}
context("with a valid response") {
beforeEach {
OHHTTPStubs.stubRequestsPassingTest({ request in
return (request.URL.absoluteString! == "http://rheinfabrik.de")
}, withStubResponse: { request in
return OHHTTPStubsResponse(data: NSData(contentsOfFile: self.bundle.pathForResource("authorize-valid", ofType: "json")!), statusCode: 200, headers: [ "Content-Type": "application/json" ])
})
waitUntil { done in
heimdall.requestAccessToken(username: "username", password: "password") { result = $0; done() }
}
}
afterEach {
OHHTTPStubs.removeAllStubs()
}
it("succeeds") {
expect(result?.isSuccess).to(beTrue())
}
it("sets the access token") {
expect(accessTokenStore.storeAccessTokenCalled).to(beTrue())
}
it("stores the access token in the token store") {
expect(accessTokenStore.storeAccessTokenCalled).to(beTrue())
}
}
context("with an error response") {
beforeEach {
OHHTTPStubs.stubRequestsPassingTest({ request in
return (request.URL.absoluteString! == "http://rheinfabrik.de")
}, withStubResponse: { request in
return OHHTTPStubsResponse(data: NSData(contentsOfFile: self.bundle.pathForResource("authorize-error", ofType: "json")!), statusCode: 400, headers: nil)
})
waitUntil { done in
heimdall.requestAccessToken(username: "username", password: "password") { result = $0; done() }
}
}
afterEach {
OHHTTPStubs.removeAllStubs()
}
it("fails") {
expect(result?.isSuccess).to(beFalse())
}
it("fails with the correct error domain") {
expect(result?.error?.domain).to(equal(OAuthErrorDomain))
}
it("fails with the correct error code") {
expect(result?.error?.code).to(equal(OAuthErrorInvalidClient))
}
it("does not set the access token") {
expect(heimdall.hasAccessToken).to(beFalse())
}
}
context("with an invalid response") {
beforeEach {
OHHTTPStubs.stubRequestsPassingTest({ request in
return (request.URL.absoluteString! == "http://rheinfabrik.de")
}, withStubResponse: { request in
return OHHTTPStubsResponse(data: NSData(contentsOfFile: self.bundle.pathForResource("authorize-invalid", ofType: "json")!), statusCode: 200, headers: [ "Content-Type": "application/json" ])
})
waitUntil { done in
heimdall.requestAccessToken(username: "username", password: "password") { result = $0; done() }
}
}
afterEach {
OHHTTPStubs.removeAllStubs()
}
it("fails") {
expect(result?.isSuccess).to(beFalse())
}
it("fails with the correct error domain") {
expect(result?.error?.domain).to(equal(HeimdallErrorDomain))
}
it("fails with the correct error code") {
expect(result?.error?.code).to(equal(HeimdallErrorInvalidData))
}
it("does not set the access token") {
expect(heimdall.hasAccessToken).to(beFalse())
}
}
context("with an invalid response missing a token") {
beforeEach {
OHHTTPStubs.stubRequestsPassingTest({ request in
return (request.URL.absoluteString! == "http://rheinfabrik.de")
}, withStubResponse: { request in
return OHHTTPStubsResponse(data: NSData(contentsOfFile: self.bundle.pathForResource("authorize-invalid-token", ofType: "json")!), statusCode: 200, headers: [ "Content-Type": "application/json" ])
})
waitUntil { done in
heimdall.requestAccessToken(username: "username", password: "password") { result = $0; done() }
}
}
afterEach {
OHHTTPStubs.removeAllStubs()
}
it("fails") {
expect(result?.isSuccess).to(beFalse())
}
it("fails with the correct error domain") {
expect(result?.error?.domain).to(equal(HeimdallErrorDomain))
}
it("fails with the correct error code") {
expect(result?.error?.code).to(equal(HeimdallErrorInvalidData))
}
it("does not set the access token") {
expect(heimdall.hasAccessToken).to(beFalse())
}
}
context("with an invalid response missing a type") {
beforeEach {
OHHTTPStubs.stubRequestsPassingTest({ request in
return (request.URL.absoluteString! == "http://rheinfabrik.de")
}, withStubResponse: { request in
return OHHTTPStubsResponse(data: NSData(contentsOfFile: self.bundle.pathForResource("authorize-invalid-type", ofType: "json")!), statusCode: 200, headers: [ "Content-Type": "application/json" ])
})
waitUntil { done in
heimdall.requestAccessToken(username: "username", password: "password") { result = $0; done() }
}
}
afterEach {
OHHTTPStubs.removeAllStubs()
}
it("fails") {
expect(result?.isSuccess).to(beFalse())
}
it("fails with the correct error domain") {
expect(result?.error?.domain).to(equal(HeimdallErrorDomain))
}
it("fails with the correct error code") {
expect(result?.error?.code).to(equal(HeimdallErrorInvalidData))
}
it("does not set the access token") {
expect(heimdall.hasAccessToken).to(beFalse())
}
}
}
describe("-authenticateRequest") {
var request = NSURLRequest(URL: NSURL(string: "http://rheinfabrik.de")!)
var result: Result<NSURLRequest, NSError>?
afterEach {
result = nil
}
context("when not authorized") {
beforeEach {
waitUntil { done in
heimdall.authenticateRequest(request) { result = $0; done() }
}
}
it("fails") {
expect(result?.isSuccess).to(beFalse())
}
it("fails with the correct error domain") {
expect(result?.error?.domain).to(equal(HeimdallErrorDomain))
}
it("fails with the correct error code") {
expect(result?.error?.code).to(equal(HeimdallErrorNotAuthorized))
}
}
context("when authorized with a still valid access token") {
beforeEach {
OHHTTPStubs.stubRequestsPassingTest({ request in
return (request.URL.absoluteString! == "http://rheinfabrik.de")
}, withStubResponse: { request in
return OHHTTPStubsResponse(data: NSData(contentsOfFile: self.bundle.pathForResource("request-valid", ofType: "json")!), statusCode: 200, headers: [ "Content-Type": "application/json" ])
})
waitUntil { done in
heimdall.requestAccessToken(username: "username", password: "password") { _ in done() }
}
waitUntil { done in
heimdall.authenticateRequest(request) { result = $0; done() }
}
}
afterEach {
OHHTTPStubs.removeAllStubs()
}
it("succeeds") {
expect(result?.isSuccess).to(beTrue())
}
it("authenticates the request using the resource request authenticator") {
expect(result?.value?.valueForHTTPHeaderField("MockAuthorized")).to(equal("totally"))
}
}
context("when authorized with an expired access token and no refresh token") {
beforeEach {
OHHTTPStubs.stubRequestsPassingTest({ request in
return (request.URL.absoluteString! == "http://rheinfabrik.de")
}, withStubResponse: { request in
return OHHTTPStubsResponse(data: NSData(contentsOfFile: self.bundle.pathForResource("request-invalid-norefresh", ofType: "json")!), statusCode: 200, headers: [ "Content-Type": "application/json" ])
})
waitUntil { done in
heimdall.requestAccessToken(username: "username", password: "password") { _ in done() }
}
waitUntil { done in
heimdall.authenticateRequest(request) { result = $0; done() }
}
}
afterEach {
OHHTTPStubs.removeAllStubs()
}
it("fails") {
expect(result?.isSuccess).to(beFalse())
}
it("fails with the correct error domain") {
expect(result?.error?.domain).to(equal(HeimdallErrorDomain))
}
it("fails with the correct error code") {
expect(result?.error?.code).to(equal(HeimdallErrorNotAuthorized))
}
}
context("when authorized with an expired access token and a valid refresh token") {
beforeEach {
OHHTTPStubs.stubRequestsPassingTest({ request in
return (
request.URL.absoluteString! == "http://rheinfabrik.de"
&& heimdall.hasAccessToken == false
)
}, withStubResponse: { request in
return OHHTTPStubsResponse(data: NSData(contentsOfFile: self.bundle.pathForResource("request-invalid", ofType: "json")!), statusCode: 200, headers: [ "Content-Type": "application/json" ])
})
waitUntil { done in
heimdall.requestAccessToken(username: "username", password: "password") { _ in done() }
}
OHHTTPStubs.stubRequestsPassingTest({ request in
return (request.URL.absoluteString! == "http://rheinfabrik.de")
}, withStubResponse: { request in
return OHHTTPStubsResponse(data: NSData(contentsOfFile: self.bundle.pathForResource("request-valid", ofType: "json")!), statusCode: 200, headers: [ "Content-Type": "application/json" ])
})
waitUntil { done in
heimdall.authenticateRequest(request) { result = $0; done() }
}
}
it("succeeds") {
expect(result?.isSuccess).to(beTrue())
}
it("authenticates the request using the resource request authenticator") {
expect(result?.value?.valueForHTTPHeaderField("MockAuthorized")).to(equal("totally"))
}
}
}
}
}
|
mit
|
82e269066204c16897295c03bd38952d
| 37.956098 | 225 | 0.496995 | 6.089211 | false | false | false | false |
poulpix/PXGoogleDirections
|
Samples/Shared/PXGoogleDirectionsSample/MainViewController.swift
|
1
|
10161
|
//
// ViewController.swift
// RLGoogleDirectionsSample
//
// Created by Romain on 07/03/2015.
// Copyright (c) 2015 RLT. All rights reserved.
//
import UIKit
import CoreLocation
import PXGoogleDirections
import GoogleMaps
protocol MainViewControllerDelegate {
func didAddWaypoint(_ waypoint: PXLocation)
}
class MainViewController: UIViewController {
@IBOutlet weak var originField: UITextField!
@IBOutlet weak var destinationField: UITextField!
@IBOutlet weak var modeField: UISegmentedControl!
@IBOutlet weak var advancedSwitch: UISwitch!
@IBOutlet weak var advancedView: UIView!
@IBOutlet weak var unitField: UISegmentedControl!
@IBOutlet weak var transitRoutingField: UISegmentedControl!
@IBOutlet weak var trafficModelField: UISegmentedControl!
@IBOutlet weak var alternativeSwitch: UISwitch!
@IBOutlet weak var busSwitch: UISwitch!
@IBOutlet weak var subwaySwitch: UISwitch!
@IBOutlet weak var trainSwitch: UISwitch!
@IBOutlet weak var tramSwitch: UISwitch!
@IBOutlet weak var railSwitch: UISwitch!
@IBOutlet weak var avoidTollsSwitch: UISwitch!
@IBOutlet weak var avoidHighwaysSwitch: UISwitch!
@IBOutlet weak var avoidFerriesSwitch: UISwitch!
@IBOutlet weak var startArriveField: UISegmentedControl!
@IBOutlet weak var startArriveDateField: UITextField!
@IBOutlet weak var waypointsLabel: UILabel!
@IBOutlet weak var optimizeWaypointsSwitch: UISwitch!
@IBOutlet weak var languageField: UISegmentedControl!
var startArriveDate: Date?
var waypoints: [PXLocation] = [PXLocation]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
updateStartArriveDateField(nil)
updateWaypointsField()
let datePicker = UIDatePicker()
datePicker.sizeToFit()
datePicker.autoresizingMask = [.flexibleWidth, .flexibleHeight]
datePicker.datePickerMode = .dateAndTime
datePicker.minuteInterval = 5
startArriveDateField.inputView = datePicker
let keyboardDoneButtonView = UIToolbar()
keyboardDoneButtonView.barStyle = .black
keyboardDoneButtonView.isTranslucent = true
keyboardDoneButtonView.tintColor = nil
keyboardDoneButtonView.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(MainViewController.doneButtonTouched(_:)))
let clearButton = UIBarButtonItem(title: "Clear", style: .plain, target: self, action: #selector(MainViewController.clearButtonTouched(_:)))
keyboardDoneButtonView.setItems([doneButton, clearButton], animated: false)
startArriveDateField.inputAccessoryView = keyboardDoneButtonView
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
fileprivate var directionsAPI: PXGoogleDirections {
return (UIApplication.shared.delegate as! AppDelegate).directionsAPI
}
fileprivate func modeFromField() -> PXGoogleDirectionsMode {
return PXGoogleDirectionsMode(rawValue: modeField.selectedSegmentIndex)!
}
fileprivate func unitFromField() -> PXGoogleDirectionsUnit {
return PXGoogleDirectionsUnit(rawValue: unitField.selectedSegmentIndex)!
}
fileprivate func transitRoutingPreferenceFromField() -> PXGoogleDirectionsTransitRoutingPreference? {
return PXGoogleDirectionsTransitRoutingPreference(rawValue: transitRoutingField.selectedSegmentIndex)
}
fileprivate func trafficModelFromField() -> PXGoogleDirectionsTrafficModel? {
return PXGoogleDirectionsTrafficModel(rawValue: trafficModelField.selectedSegmentIndex)
}
fileprivate func languageFromField() -> String {
return languageField.titleForSegment(at: languageField.selectedSegmentIndex)!
// There are quite a few other languages available, see here for more information: https://developers.google.com/maps/faq#languagesupport
}
fileprivate func updateStartArriveDateField(_ newDate: Date?) {
startArriveDate = newDate
if let saDate = startArriveDate {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .short
startArriveDateField.text = dateFormatter.string(from: saDate)
} else {
startArriveDateField.text = ""
}
}
fileprivate func updateWaypointsField() {
switch (waypoints).count {
case 0:
waypointsLabel.text = "No waypoints"
case 1:
waypointsLabel.text = "1 waypoint"
default:
waypointsLabel.text = "\((waypoints).count) waypoints"
}
}
@IBAction func advancedOptionsChanged(_ sender: UISwitch) {
UIView.animate(withDuration: 0.5, animations: {
self.advancedView.alpha = (self.advancedSwitch.isOn ? 1.0 : 0.0)
})
}
@IBAction func selectDateButtonTouched(_ sender: UIButton) {
startArriveDateField.isEnabled = true
startArriveDateField.becomeFirstResponder()
}
@objc func doneButtonTouched(_ sender: UIBarButtonItem) {
updateStartArriveDateField((startArriveDateField.inputView as! UIDatePicker).date)
startArriveDateField.resignFirstResponder()
startArriveDateField.isEnabled = false
}
@objc func clearButtonTouched(_ sender: UIBarButtonItem) {
updateStartArriveDateField(nil)
startArriveDateField.resignFirstResponder()
startArriveDateField.isEnabled = false
}
@IBAction func addWaypointButtonTouched(_ sender: UIButton) {
if let wpvc = self.storyboard?.instantiateViewController(withIdentifier: "Waypoint") as? WaypointViewController {
wpvc.delegate = self
self.present(wpvc, animated: true, completion: nil)
}
}
@IBAction func clearWaypointsButtonTouched(_ sender: UIButton) {
waypoints.removeAll(keepingCapacity: false)
updateWaypointsField()
}
@IBAction func goButtonTouched(_ sender: UIButton) {
directionsAPI.delegate = self
directionsAPI.from = PXLocation.namedLocation(originField.text!)
directionsAPI.to = PXLocation.namedLocation(destinationField.text!)
directionsAPI.mode = modeFromField()
if advancedSwitch.isOn {
directionsAPI.transitRoutingPreference = transitRoutingPreferenceFromField()
directionsAPI.trafficModel = trafficModelFromField()
directionsAPI.units = unitFromField()
directionsAPI.alternatives = alternativeSwitch.isOn
directionsAPI.transitModes = Set()
if busSwitch.isOn {
directionsAPI.transitModes.insert(.bus)
}
if subwaySwitch.isOn {
directionsAPI.transitModes.insert(.subway)
}
if trainSwitch.isOn {
directionsAPI.transitModes.insert(.train)
}
if tramSwitch.isOn {
directionsAPI.transitModes.insert(.tram)
}
if railSwitch.isOn {
directionsAPI.transitModes.insert(.rail)
}
directionsAPI.featuresToAvoid = Set()
if avoidTollsSwitch.isOn {
directionsAPI.featuresToAvoid.insert(.tolls)
}
if avoidHighwaysSwitch.isOn {
directionsAPI.featuresToAvoid.insert(.highways)
}
if avoidFerriesSwitch.isOn {
directionsAPI.featuresToAvoid.insert(.ferries)
}
switch startArriveField.selectedSegmentIndex {
case 0:
directionsAPI.departureTime = .now
directionsAPI.arrivalTime = nil
case 1:
if let saDate = startArriveDate {
directionsAPI.departureTime = PXTime.timeFromDate(saDate)
directionsAPI.arrivalTime = nil
} else {
return
}
case 2:
if let saDate = startArriveDate {
directionsAPI.departureTime = nil
directionsAPI.arrivalTime = PXTime.timeFromDate(saDate)
} else {
return
}
default:
break
}
directionsAPI.waypoints = waypoints
directionsAPI.optimizeWaypoints = optimizeWaypointsSwitch.isOn
directionsAPI.language = languageFromField()
} else {
directionsAPI.transitRoutingPreference = nil
directionsAPI.trafficModel = nil
directionsAPI.units = nil
directionsAPI.alternatives = nil
directionsAPI.transitModes = Set()
directionsAPI.featuresToAvoid = Set()
directionsAPI.departureTime = nil
directionsAPI.arrivalTime = nil
directionsAPI.waypoints = [PXLocation]()
directionsAPI.optimizeWaypoints = nil
directionsAPI.language = nil
}
// directionsAPI.region = "fr" // Feature not demonstrated in this sample app
directionsAPI.calculateDirections { (response) -> Void in
DispatchQueue.main.async(execute: { () -> Void in
switch response {
case let .error(_, error):
let alert = UIAlertController(title: "PXGoogleDirectionsSample", message: "Error: \(error.localizedDescription)", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
case let .success(request, routes):
if let rvc = self.storyboard?.instantiateViewController(withIdentifier: "Results") as? ResultsViewController {
rvc.request = request
rvc.results = routes
self.present(rvc, animated: true, completion: nil)
}
}
})
}
}
}
extension MainViewController: PXGoogleDirectionsDelegate {
func googleDirectionsWillSendRequestToAPI(_ googleDirections: PXGoogleDirections, withURL requestURL: URL) -> Bool {
NSLog("googleDirectionsWillSendRequestToAPI:withURL:")
return true
}
func googleDirectionsDidSendRequestToAPI(_ googleDirections: PXGoogleDirections, withURL requestURL: URL) {
NSLog("googleDirectionsDidSendRequestToAPI:withURL:")
NSLog("\(requestURL.absoluteString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!)")
}
func googleDirections(_ googleDirections: PXGoogleDirections, didReceiveRawDataFromAPI data: Data) {
NSLog("googleDirections:didReceiveRawDataFromAPI:")
NSLog(String(data: data, encoding: .utf8)!)
}
func googleDirectionsRequestDidFail(_ googleDirections: PXGoogleDirections, withError error: NSError) {
NSLog("googleDirectionsRequestDidFail:withError:")
NSLog("\(error)")
}
func googleDirections(_ googleDirections: PXGoogleDirections, didReceiveResponseFromAPI apiResponse: [PXGoogleDirectionsRoute]) {
NSLog("googleDirections:didReceiveResponseFromAPI:")
NSLog("Got \(apiResponse.count) routes")
for i in 0 ..< apiResponse.count {
NSLog("Route \(i) has \(apiResponse[i].legs.count) legs")
}
}
}
extension MainViewController: MainViewControllerDelegate {
func didAddWaypoint(_ waypoint: PXLocation) {
waypoints.append(waypoint)
updateWaypointsField()
}
}
|
bsd-3-clause
|
327a921e3bf54c56c3db4485d07725a2
| 35.160142 | 165 | 0.769708 | 4.056287 | false | false | false | false |
Stitch7/Instapod
|
Instapod/Player/SleepTimer/PlayerSleepTimerDuration.swift
|
1
|
1280
|
//
// PlayerSleepTimerDuration.swift
// Instapod
//
// Created by Christopher Reitz on 17.04.16.
// Copyright © 2016 Christopher Reitz. All rights reserved.
//
import UIKit
enum PlayerSleepTimerDuration: Int {
case off = 0
case fiveMinutes = 5
case tenMinutes = 10
case fifteenMinutes = 15
case thirtyMinutes = 30
case oneHour = 60
case twoHours = 120
var sorted: [PlayerSleepTimerDuration] {
return [
.off,
.fiveMinutes,
.tenMinutes,
.fifteenMinutes,
.thirtyMinutes,
.oneHour,
.twoHours
]
}
var seconds: Int {
return self.rawValue * 60
}
var image: UIImage {
let selfChars = String(describing: self).characters
let first = String(selfChars.prefix(1)).capitalized
let other = String(selfChars.dropFirst())
let suffix = first + other
return UIImage(named: "playerSleepTimerDuration\(suffix)")!
}
mutating func nextValue() {
let sorted = self.sorted
let currentIndex = sorted.index(of: self)!
var nextIndex = currentIndex + 1
if sorted.count <= nextIndex {
nextIndex = 0
}
self = sorted[nextIndex]
}
}
|
mit
|
8663548f23c2b24908f3adbc4eff2b18
| 22.685185 | 67 | 0.584832 | 4.395189 | false | false | false | false |
fe9lix/Protium
|
iOS/Protium/src/base/InteractableUI.swift
|
1
|
1608
|
import UIKit
// Base class for View Controllers. The init/creation methods accept a factory closure that returns an Interactor.
// The UI passes itself as parameter to the closure so that action streams can be retrieved from the UI and
// passed as dependency to the Interactor.
// See: https://github.com/ReactiveKit/ReactiveGitter/blob/master/Common/DirectedViewController.swift
class InteractableUI<Interactor>: UIViewController {
var interactor: Interactor!
private var interactorFactory: ((InteractableUI) -> Interactor)!
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?, interactorFactory: @escaping (InteractableUI) -> Interactor) {
self.interactorFactory = interactorFactory
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
class func create(storyboard: UIStoryboard, interactorFactory: @escaping (InteractableUI) -> Interactor) -> InteractableUI {
let viewController = storyboard.instantiateInitialViewController() as! InteractableUI
viewController.interactorFactory = interactorFactory
return viewController
}
override func viewDidLoad() {
super.viewDidLoad()
interactor = interactorFactory(self)
interactorFactory = nil
bindInteractor(interactor: interactor)
}
func bindInteractor(interactor: Interactor) {}
class func downcast<T, U, D>(_ closure: @escaping (T) -> D) -> ((U) -> D) {
return { a in closure(a as! T) }
}
}
|
mit
|
74424eeb84a1124bbfaf5b9a948ca72d
| 40.230769 | 134 | 0.705224 | 4.917431 | false | false | false | false |
ubi-naist/SenStick
|
ios/Pods/iOSDFULibrary/iOSDFULibrary/Classes/Utilities/Streams/DFUStreamZip.swift
|
4
|
12264
|
/*
* Copyright (c) 2016, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Errors
internal enum DFUStreamZipError : Error {
case noManifest
case invalidManifest
case fileNotFound
case typeNotFound
var description: String {
switch self {
case .noManifest: return NSLocalizedString("No manifest file found", comment: "")
case .invalidManifest: return NSLocalizedString("Invalid manifest.json file", comment: "")
case .fileNotFound: return NSLocalizedString("File specified in manifest.json not found in ZIP", comment: "")
case .typeNotFound: return NSLocalizedString("Specified type not found in manifest.json", comment: "")
}
}
}
internal class DFUStreamZip : DFUStream {
private static let MANIFEST_FILE = "manifest.json"
private(set) var currentPart = 1
private(set) var parts = 1
private(set) var currentPartType: UInt8 = 0
/// The parsed manifest file if such found, nil otherwise.
private var manifest: Manifest?
/// Binaries with softdevice and bootloader.
private var systemBinaries: Data?
/// Binaries with an app.
private var appBinaries: Data?
/// System init packet.
private var systemInitPacket: Data?
/// Application init packet.
private var appInitPacket: Data?
private var currentBinaries: Data?
private var currentInitPacket: Data?
private var softdeviceSize : UInt32 = 0
private var bootloaderSize : UInt32 = 0
private var applicationSize : UInt32 = 0
var size: DFUFirmwareSize {
return DFUFirmwareSize(softdevice: softdeviceSize, bootloader: bootloaderSize, application: applicationSize)
}
var currentPartSize: DFUFirmwareSize {
// If the ZIP file will be transferred in one part, return all sizes. Two of them will be 0.
if parts == 1 {
return DFUFirmwareSize(softdevice: softdeviceSize, bootloader: bootloaderSize, application: applicationSize)
}
// Else, return sizes based on the current part number. First the SD and/or BL are uploaded
if currentPart == 1 {
return DFUFirmwareSize(softdevice: softdeviceSize, bootloader: bootloaderSize, application: 0)
}
// and then the application.
return DFUFirmwareSize(softdevice: 0, bootloader: 0, application: applicationSize)
}
/**
Initializes the stream with URL to the ZIP file.
- parameter urlToZipFile: URL to the ZIP file with firmware files and manifest.json file containing metadata.
- throws: DFUStreamZipError when manifest file was not found or contained an error
- returns: the stream
*/
convenience init(urlToZipFile: URL) throws {
let allTypes = FIRMWARE_TYPE_SOFTDEVICE | FIRMWARE_TYPE_BOOTLOADER | FIRMWARE_TYPE_APPLICATION
try self.init(urlToZipFile: urlToZipFile, type: allTypes)
}
/**
Initializes the stream with URL to the ZIP file.
- parameter urlToZipFile: URL to the ZIP file with firmware files and manifest.json file containing metadata.
- parameter type: The type of the firmware to use
- throws: DFUStreamZipError when manifest file was not found or contained an error
- returns: the stream
*/
init(urlToZipFile: URL, type: UInt8) throws {
// Try to unzip the file. This may throw an exception
let contentUrls = try ZipArchive.unzip(urlToZipFile)
// Look for MANIFEST_FILE
let manifestUrl = ZipArchive.findFile(DFUStreamZip.MANIFEST_FILE, inside: contentUrls)
if let url = manifestUrl {
// Read manifest content
let json = try String(contentsOf: url)
// Deserialize json
manifest = Manifest(withJsonString: json)
if manifest!.valid {
// After validation we are sure that the manifest file contains at most one
// of: softdeviceBootloader, softdevice or bootloader
// Look for and assign files specified in the manifest
let softdeviceBootloaderType = FIRMWARE_TYPE_SOFTDEVICE | FIRMWARE_TYPE_BOOTLOADER
if type & softdeviceBootloaderType == softdeviceBootloaderType {
if let softdeviceBootloader = manifest!.softdeviceBootloader {
let (bin, dat) = try getContentOf(softdeviceBootloader, from: contentUrls)
systemBinaries = bin
systemInitPacket = dat
softdeviceSize = softdeviceBootloader.sdSize
bootloaderSize = softdeviceBootloader.blSize
currentPartType = softdeviceBootloaderType
}
}
let softdeviceType = FIRMWARE_TYPE_SOFTDEVICE
if type & softdeviceType == softdeviceType {
if let softdevice = manifest!.softdevice {
if systemBinaries != nil {
// It is not allowed to put both softdevice and softdeviceBootloader in the manifest
throw DFUStreamZipError.invalidManifest
}
let (bin, dat) = try getContentOf(softdevice, from: contentUrls)
systemBinaries = bin
systemInitPacket = dat
softdeviceSize = UInt32(bin.count)
currentPartType = softdeviceType
}
}
let bootloaderType = FIRMWARE_TYPE_BOOTLOADER
if type & bootloaderType == bootloaderType {
if let bootloader = manifest!.bootloader {
if systemBinaries != nil {
// It is not allowed to put both bootloader and softdeviceBootloader in the manifest
throw DFUStreamZipError.invalidManifest
}
let (bin, dat) = try getContentOf(bootloader, from: contentUrls)
systemBinaries = bin
systemInitPacket = dat
bootloaderSize = UInt32(bin.count)
currentPartType = bootloaderType
}
}
let applicationType = FIRMWARE_TYPE_APPLICATION
if type & applicationType == applicationType {
if let application = manifest!.application {
let (bin, dat) = try getContentOf(application, from: contentUrls)
appBinaries = bin
appInitPacket = dat
applicationSize = UInt32(bin.count)
if currentPartType == 0 {
currentPartType = applicationType
} else {
// Otherwise the app will be sent as part 2
// It is not possible to send SD+BL+App in a single connection, due to a fact that
// the softdevice_bootloade_application section is not defined for the manifest.json file.
// It would be possible to send both bin (systemBinaries and appBinaries), but there are
// two dat files with two Init Packets and non of them matches two combined binaries.
}
}
}
if systemBinaries == nil && appBinaries == nil {
// The specified type is not included in the manifest.
throw DFUStreamZipError.typeNotFound
}
else if systemBinaries != nil {
currentBinaries = systemBinaries
currentInitPacket = systemInitPacket
} else {
currentBinaries = appBinaries
currentInitPacket = appInitPacket
}
// If the ZIP file contains an app and a softdevice or bootloader,
// the content will be sent in 2 parts.
if systemBinaries != nil && appBinaries != nil {
parts = 2
}
} else {
throw DFUStreamZipError.invalidManifest
}
} else { // no manifest file
// This library does not support the old, deprecated name-based ZIP files
// Please, use the nrf-util app to create a new Distribution packet
throw DFUStreamZipError.noManifest
}
}
/**
This method checks if the FirmwareInfo object is valid (has both bin and dat files specified),
adds those files to binUrls and datUrls arrays and returns the length of the bin file in bytes.
- parameter info: the metadata obtained from the manifest file
- parameter contentUrls: the list of URLs to the unzipped files
- throws: DFUStreamZipError when file specified in the metadata was not found in the ZIP
- returns: content bin and dat files
*/
fileprivate func getContentOf(_ info: ManifestFirmwareInfo, from contentUrls: [URL]) throws -> (Data, Data?) {
if !info.valid {
throw DFUStreamZipError.invalidManifest
}
// Get the URLs to the bin and dat files specified in the FirmwareInfo
let bin = ZipArchive.findFile(info.binFile!, inside: contentUrls)
var dat: URL? = nil
if let datFile = info.datFile {
dat = ZipArchive.findFile(datFile, inside: contentUrls)
}
// Check if the files were found in the ZIP
if bin == nil || (info.datFile != nil && dat == nil) {
throw DFUStreamZipError.fileNotFound
}
// Read content of those files
let binData = try! Data(contentsOf: bin!)
var datData: Data? = nil
if let dat = dat {
datData = try! Data(contentsOf: dat)
}
return (binData, datData)
}
var data: Data {
return currentBinaries!
}
var initPacket: Data? {
return currentInitPacket
}
func hasNextPart() -> Bool {
return currentPart < parts
}
func switchToNextPart() {
if currentPart == 1 && parts == 2 {
currentPart = 2
currentPartType = FIRMWARE_TYPE_APPLICATION
currentBinaries = appBinaries
currentInitPacket = appInitPacket
}
}
}
|
mit
|
075b3f10c2bad7655e4eb38b02591f54
| 43.923077 | 144 | 0.600294 | 5.516869 | false | false | false | false |
Bing0/ThroughWall
|
ChiselLogViewer/BodyContentViewController.swift
|
1
|
2578
|
//
// BodyContentViewController.swift
// ChiselLogViewer
//
// Created by Bingo on 09/07/2017.
// Copyright © 2017 Wu Bin. All rights reserved.
//
import Cocoa
class BodyContentViewController: NSViewController {
var hostTraffic: HostTraffic?
var isRequestBody = true
var data: Data?
var parseURL: URL!
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
if let _hostTraffic = hostTraffic {
if isRequestBody {
if let fileName = _hostTraffic.requestWholeBody?.fileName {
let url = parseURL.appendingPathComponent(fileName)
do {
data = try Data(contentsOf: url)
}catch{
print(error)
}
}
} else {
if let fileName = _hostTraffic.responseWholeBody?.fileName {
let url = parseURL.appendingPathComponent(fileName)
do {
data = try Data(contentsOf: url)
}catch{
print(error)
}
}
}
}
}
@IBAction func saveDocument(_ sender: AnyObject) {
let dialog = NSSavePanel();
// dialog.title = "Choose a .txt file";
dialog.showsResizeIndicator = true;
dialog.showsHiddenFiles = false;
dialog.canCreateDirectories = true;
if (dialog.runModal() == NSApplication.ModalResponse.OK) {
let result = dialog.url // Pathname of the file
if let _data = data {
do {
try _data.write(to: result!)
} catch {
print(error)
}
}
} else {
// User clicked on "Cancel"
return
}
}
@IBAction func cancel(_ sender: NSButton) {
dismiss(nil)
}
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
guard let tabViewController = segue.destinationController as? NSTabViewController else { return }
for controller in tabViewController.childViewControllers {
if let _controller = controller as? HexViewController {
_controller.data = data
} else if let _controller = controller as? PictureViewController {
_controller.data = data
}
}
}
}
|
gpl-3.0
|
7611c474c86ccf8b1bde2e2c374ce601
| 29.317647 | 105 | 0.499806 | 5.413866 | false | false | false | false |
JanGorman/MapleBacon
|
MapleBacon/Core/Download.swift
|
2
|
2153
|
//
// Copyright © 2020 Schnaub. All rights reserved.
//
import UIKit
/// A download task – this wraps the internal download instance and can be used to cancel an inflight request
public struct DownloadTask<T: DataConvertible> {
let download: Download<T>
public let cancelToken: CancelToken
public func cancel() {
download.cancel(cancelToken: cancelToken)
}
}
final class Download<T: DataConvertible> {
typealias Completion = (Result<T.Result, Error>) -> Void
let task: URLSessionDataTask
var completions: [Completion] {
defer {
lock.unlock()
}
lock.lock()
return Array(tokenCompletions.values)
}
private let lock = NSLock()
private(set) var data = Data()
private var currentToken: CancelToken = 0
private var backgroundTask: UIBackgroundTaskIdentifier = .invalid
private var tokenCompletions: [CancelToken: Completion] = [:]
init(task: URLSessionDataTask) {
self.task = task
}
deinit {
invalidateBackgroundTask()
}
func addCompletion(_ completion: @escaping Completion) -> CancelToken {
defer {
currentToken += 1
lock.unlock()
}
lock.lock()
tokenCompletions[currentToken] = completion
return currentToken
}
func removeCompletion(for token: CancelToken) -> Completion? {
defer {
lock.unlock()
}
lock.lock()
guard let completion = tokenCompletions[token] else {
return nil
}
tokenCompletions[token] = nil
return completion
}
func appendData(_ data: Data) {
self.data.append(data)
}
func start() {
backgroundTask = UIApplication.shared.beginBackgroundTask {
self.invalidateBackgroundTask()
}
}
func finish() {
invalidateBackgroundTask()
}
func cancel(cancelToken: CancelToken) {
guard let completion = removeCompletion(for: cancelToken) else {
return
}
if tokenCompletions.isEmpty {
task.cancel()
}
completion(.failure(DownloaderError.canceled))
}
}
private extension Download {
func invalidateBackgroundTask() {
UIApplication.shared.endBackgroundTask(backgroundTask)
backgroundTask = .invalid
}
}
|
mit
|
36556bb20d0311940b9fe3e2b1d99d3b
| 19.673077 | 109 | 0.682326 | 4.460581 | false | false | false | false |
justindarc/firefox-ios
|
Client/Frontend/Settings/SearchSettingsTableViewController.swift
|
1
|
15150
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import SDWebImage
import Shared
protocol SearchEnginePickerDelegate: AnyObject {
func searchEnginePicker(_ searchEnginePicker: SearchEnginePicker?, didSelectSearchEngine engine: OpenSearchEngine?)
}
class SearchSettingsTableViewController: ThemedTableViewController {
fileprivate let SectionDefault = 0
fileprivate let ItemDefaultEngine = 0
fileprivate let ItemDefaultSuggestions = 1
fileprivate let ItemAddCustomSearch = 2
fileprivate let NumberOfItemsInSectionDefault = 2
fileprivate let SectionOrder = 1
fileprivate let NumberOfSections = 2
fileprivate let IconSize = CGSize(width: OpenSearchEngine.PreferredIconSize, height: OpenSearchEngine.PreferredIconSize)
fileprivate let SectionHeaderIdentifier = "SectionHeaderIdentifier"
fileprivate var showDeletion = false
var profile: Profile?
var tabManager: TabManager?
fileprivate var isEditable: Bool {
// If the default engine is a custom one, make sure we have more than one since we can't edit the default.
// Otherwise, enable editing if we have at least one custom engine.
let customEngineCount = model.orderedEngines.filter({$0.isCustomEngine}).count
return model.defaultEngine.isCustomEngine ? customEngineCount > 1 : customEngineCount > 0
}
var model: SearchEngines!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = NSLocalizedString("Search", comment: "Navigation title for search settings.")
// To allow re-ordering the list of search engines at all times.
tableView.isEditing = true
// So that we push the default search engine controller on selection.
tableView.allowsSelectionDuringEditing = true
tableView.register(ThemedTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier)
// Insert Done button if being presented outside of the Settings Nav stack
if !(self.navigationController is ThemedNavigationController) {
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: Strings.SettingsSearchDoneButton, style: .done, target: self, action: #selector(self.dismissAnimated))
}
navigationItem.rightBarButtonItem = UIBarButtonItem(title: Strings.SettingsSearchEditButton, style: .plain, target: self,
action: #selector(beginEditing))
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Only show the Edit button if custom search engines are in the list.
// Otherwise, there is nothing to delete.
navigationItem.rightBarButtonItem?.isEnabled = isEditable
tableView.reloadData()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
setEditing(false, animated: false)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = ThemedTableViewCell()
var engine: OpenSearchEngine!
if indexPath.section == SectionDefault {
switch indexPath.item {
case ItemDefaultEngine:
engine = model.defaultEngine
cell.editingAccessoryType = .disclosureIndicator
cell.accessibilityLabel = NSLocalizedString("Default Search Engine", comment: "Accessibility label for default search engine setting.")
cell.accessibilityValue = engine.shortName
cell.textLabel?.text = engine.shortName
cell.imageView?.image = engine.image.createScaled(IconSize)
cell.imageView?.layer.cornerRadius = 4
cell.imageView?.layer.masksToBounds = true
case ItemDefaultSuggestions:
cell.textLabel?.text = NSLocalizedString("Show Search Suggestions", comment: "Label for show search suggestions setting.")
let toggle = UISwitchThemed()
toggle.onTintColor = UIColor.theme.tableView.controlTint
toggle.addTarget(self, action: #selector(didToggleSearchSuggestions), for: .valueChanged)
toggle.isOn = model.shouldShowSearchSuggestions
cell.editingAccessoryView = toggle
cell.selectionStyle = .none
default:
// Should not happen.
break
}
} else {
// The default engine is not a quick search engine.
let index = indexPath.item + 1
if index < model.orderedEngines.count {
engine = model.orderedEngines[index]
cell.showsReorderControl = true
let toggle = UISwitchThemed()
toggle.onTintColor = UIColor.theme.tableView.controlTint
// This is an easy way to get from the toggle control to the corresponding index.
toggle.tag = index
toggle.addTarget(self, action: #selector(didToggleEngine), for: .valueChanged)
toggle.isOn = model.isEngineEnabled(engine)
cell.editingAccessoryView = toggle
cell.textLabel?.text = engine.shortName
cell.textLabel?.adjustsFontSizeToFitWidth = true
cell.textLabel?.minimumScaleFactor = 0.5
cell.imageView?.image = engine.image.createScaled(IconSize)
cell.imageView?.layer.cornerRadius = 4
cell.imageView?.layer.masksToBounds = true
cell.selectionStyle = .none
} else {
cell.editingAccessoryType = .disclosureIndicator
cell.accessibilityLabel = Strings.SettingsAddCustomEngineTitle
cell.accessibilityIdentifier = "customEngineViewButton"
cell.textLabel?.text = Strings.SettingsAddCustomEngine
}
}
// So that the seperator line goes all the way to the left edge.
cell.separatorInset = .zero
return cell
}
override func numberOfSections(in tableView: UITableView) -> Int {
return NumberOfSections
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == SectionDefault {
return NumberOfItemsInSectionDefault
} else {
// The first engine -- the default engine -- is not shown in the quick search engine list.
// But the option to add Custom Engine is.
return model.orderedEngines.count
}
}
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if indexPath.section == SectionDefault && indexPath.item == ItemDefaultEngine {
let searchEnginePicker = SearchEnginePicker()
// Order alphabetically, so that picker is always consistently ordered.
// Every engine is a valid choice for the default engine, even the current default engine.
searchEnginePicker.engines = model.orderedEngines.sorted { e, f in e.shortName < f.shortName }
searchEnginePicker.delegate = self
searchEnginePicker.selectedSearchEngineName = model.defaultEngine.shortName
navigationController?.pushViewController(searchEnginePicker, animated: true)
} else if indexPath.item + 1 == model.orderedEngines.count {
let customSearchEngineForm = CustomSearchViewController()
customSearchEngineForm.profile = self.profile
customSearchEngineForm.successCallback = {
guard let window = self.view.window else { return }
SimpleToast().showAlertWithText(Strings.ThirdPartySearchEngineAdded, bottomContainer: window)
}
navigationController?.pushViewController(customSearchEngineForm, animated: true)
}
return nil
}
// Don't show delete button on the left.
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
if indexPath.section == SectionDefault || indexPath.item + 1 == model.orderedEngines.count {
return UITableViewCell.EditingStyle.none
}
let index = indexPath.item + 1
let engine = model.orderedEngines[index]
return (self.showDeletion && engine.isCustomEngine) ? .delete : .none
}
// Don't reserve space for the delete button on the left.
override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return false
}
// Hide a thin vertical line that iOS renders between the accessoryView and the reordering control.
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if cell.isEditing {
for v in cell.subviews where v.frame.width == 1.0 {
v.backgroundColor = UIColor.clear
}
}
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderIdentifier) as! ThemedTableSectionHeaderFooterView
var sectionTitle: String
if section == SectionDefault {
sectionTitle = NSLocalizedString("Default Search Engine", comment: "Title for default search engine settings section.")
} else {
sectionTitle = NSLocalizedString("Quick-Search Engines", comment: "Title for quick-search engines settings section.")
}
headerView.titleLabel.text = sectionTitle
return headerView
}
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
guard let footerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderIdentifier) as? ThemedTableSectionHeaderFooterView else {
return nil
}
footerView.showBottomBorder = false
footerView.applyTheme()
return footerView
}
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
if indexPath.section == SectionDefault || indexPath.item + 1 == model.orderedEngines.count {
return false
} else {
return true
}
}
override func tableView(_ tableView: UITableView, moveRowAt indexPath: IndexPath, to newIndexPath: IndexPath) {
// The first engine (default engine) is not shown in the list, so the indices are off-by-1.
let index = indexPath.item + 1
let newIndex = newIndexPath.item + 1
let engine = model.orderedEngines.remove(at: index)
model.orderedEngines.insert(engine, at: newIndex)
tableView.reloadData()
}
// Snap to first or last row of the list of engines.
override func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
// You can't drag or drop on the default engine.
if sourceIndexPath.section == SectionDefault || proposedDestinationIndexPath.section == SectionDefault {
return sourceIndexPath
}
//Can't drag/drop over "Add Custom Engine button"
if sourceIndexPath.item + 1 == model.orderedEngines.count || proposedDestinationIndexPath.item + 1 == model.orderedEngines.count {
return sourceIndexPath
}
if sourceIndexPath.section != proposedDestinationIndexPath.section {
var row = 0
if sourceIndexPath.section < proposedDestinationIndexPath.section {
row = tableView.numberOfRows(inSection: sourceIndexPath.section) - 1
}
return IndexPath(row: row, section: sourceIndexPath.section)
}
return proposedDestinationIndexPath
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let index = indexPath.item + 1
let engine = model.orderedEngines[index]
model.deleteCustomEngine(engine)
tableView.deleteRows(at: [indexPath], with: .right)
// End editing if we are no longer edit since we've deleted all editable cells.
if !isEditable {
finishEditing()
}
}
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
tableView.isEditing = true
showDeletion = editing
UIView.performWithoutAnimation {
self.navigationItem.rightBarButtonItem?.title = editing ? Strings.SettingsSearchDoneButton : Strings.SettingsSearchEditButton
}
navigationItem.rightBarButtonItem?.isEnabled = isEditable
navigationItem.rightBarButtonItem?.action = editing ?
#selector(finishEditing) : #selector(beginEditing)
tableView.reloadData()
}
}
// MARK: - Selectors
extension SearchSettingsTableViewController {
@objc func didToggleEngine(_ toggle: UISwitch) {
let engine = model.orderedEngines[toggle.tag] // The tag is 1-based.
if toggle.isOn {
model.enableEngine(engine)
} else {
model.disableEngine(engine)
}
}
@objc func didToggleSearchSuggestions(_ toggle: UISwitch) {
// Setting the value in settings dismisses any opt-in.
model.shouldShowSearchSuggestions = toggle.isOn
}
func cancel() {
_ = navigationController?.popViewController(animated: true)
}
@objc func dismissAnimated() {
self.dismiss(animated: true, completion: nil)
}
@objc func beginEditing() {
setEditing(true, animated: false)
}
@objc func finishEditing() {
setEditing(false, animated: false)
}
}
extension SearchSettingsTableViewController: SearchEnginePickerDelegate {
func searchEnginePicker(_ searchEnginePicker: SearchEnginePicker?, didSelectSearchEngine searchEngine: OpenSearchEngine?) {
if let engine = searchEngine {
model.defaultEngine = engine
self.tableView.reloadData()
UnifiedTelemetry.recordEvent(category: .action, method: .change, object: .setting, value: "defaultSearchEngine", extras: ["to": engine.engineID ?? "custom"])
}
_ = navigationController?.popViewController(animated: true)
}
}
|
mpl-2.0
|
c3c6f4f68822c7b10ddecbbd635eb0c0
| 44.223881 | 189 | 0.670099 | 5.797933 | false | false | false | false |
justindarc/firefox-ios
|
Shared/Extensions/UIImageExtensions.swift
|
1
|
3361
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import SDWebImage
private let imageLock = NSLock()
extension CGRect {
public init(width: CGFloat, height: CGFloat) {
self.init(x: 0, y: 0, width: width, height: height)
}
public init(size: CGSize) {
self.init(origin: .zero, size: size)
}
}
extension Data {
public var isGIF: Bool {
return [0x47, 0x49, 0x46].elementsEqual(prefix(3))
}
}
extension UIImage {
/// Despite docs that say otherwise, UIImage(data: NSData) isn't thread-safe (see bug 1223132).
/// As a workaround, synchronize access to this initializer.
/// This fix requires that you *always* use this over UIImage(data: NSData)!
public static func imageFromDataThreadSafe(_ data: Data) -> UIImage? {
imageLock.lock()
let image = UIImage(data: data)
imageLock.unlock()
return image
}
public static func createWithColor(_ size: CGSize, color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let context = UIGraphicsGetCurrentContext()
let rect = CGRect(size: size)
color.setFill()
context!.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
public func createScaled(_ size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
draw(in: CGRect(size: size))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage!
}
public static func templateImageNamed(_ name: String) -> UIImage? {
return UIImage(named: name)?.withRenderingMode(.alwaysTemplate)
}
// Uses compositor blending to apply color to an image.
public func tinted(withColor: UIColor) -> UIImage {
let img2 = UIImage.createWithColor(size, color: withColor)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
let renderer = UIGraphicsImageRenderer(size: size)
let result = renderer.image { ctx in
img2.draw(in: rect, blendMode: .normal, alpha: 1)
draw(in: rect, blendMode: .destinationIn, alpha: 1)
}
return result
}
// TESTING ONLY: not for use in release/production code.
// PNG comparison can return false negatives, be very careful using for non-equal comparison.
// PNG comparison requires UIImages to be constructed the same way in order for the metadata block to match,
// this function ensures that.
//
// This can be verified with this code:
// let image = UIImage(named: "fxLogo")!
// let data = UIImagePNGRepresentation(image)!
// assert(data != UIImagePNGRepresentation(UIImage(data: data)!))
public func isStrictlyEqual(to other: UIImage) -> Bool {
// Must use same constructor for PNG metadata block to be the same.
let imageA = UIImage(data: self.pngData()!)!
let imageB = UIImage(data: other.pngData()!)!
let dataA = imageA.pngData()!
let dataB = imageB.pngData()!
return dataA == dataB
}
}
|
mpl-2.0
|
b8139f8a6eba9e4de1aeaf94efb95e7e
| 36.764045 | 112 | 0.65546 | 4.463479 | false | false | false | false |
fqhuy/minimind
|
minimind/core/matrix.swift
|
1
|
24643
|
//
// matrix.swift
// minimind
//
// Created by Phan Quoc Huy on 5/29/17.
// Copyright © 2017 Phan Quoc Huy. All rights reserved.
// Copyright (c) 2014–2015 Mattt Thompson (http://mattt.me)
//
import Foundation
import Accelerate
typealias NumberType = Float
//MARK: SURGE
public enum MatrixAxies {
case row
case column
}
public struct Matrix<T> {
public typealias Element = T
public var rows: Int
public var columns: Int
public var size: Int {
get {
return rows * columns
}
}
public var shape: (Int, Int) {
get {
return (rows, columns)
}
}
var _grid: [Element]
public var grid: [Element] {
get {
return _grid
}
set(val) {
assert(val.count == size, "incompatible grid")
self._grid = val
}
}
//MARK: initialisations
public init() {
self.rows = 0
self.columns = 0
self._grid = []
}
public init(rows: Int, columns: Int, repeatedValue: Element) {
self.rows = rows
self.columns = columns
_grid = [Element](repeating: repeatedValue, count: rows * columns)
}
public init(_ rows: Int,_ columns: Int,_ data: [Element]) {
var rr: Int = rows
var cc: Int = columns
if rows == -1 && columns > 0{
rr = data.count / columns
} else if rows > 0 && columns == -1 {
cc = data.count / rows
}
precondition(data.count == rr * cc, "data.count != rows * columns")
self.rows = rr
self.columns = cc
_grid = data
}
public init(_ data: [[Element]]) {
precondition(data.count > 0)
precondition(minimind.all(data.map{ $0.count } == data[0].count) , "all dimensions in data must be equal")
rows = data.count
columns = data[0].count
_grid = flatten(data)
}
public subscript(row: Int, column: Int) -> Element {
get {
assert(indexIsValidForRow(row, column: column))
return grid[(row * columns) + column]
}
set {
assert(indexIsValidForRow(row, column: column))
grid[(row * columns) + column] = newValue
}
}
public subscript(row: Int) -> Matrix {
get {
assert(row < rows)
let startIndex = row * columns
let endIndex = row * columns + columns
return Matrix(1, columns, Array(grid[startIndex..<endIndex]))
}
set {
assert(row < rows)
assert(newValue.size == columns)
let startIndex = row * columns
let endIndex = row * columns + columns
grid.replaceSubrange(startIndex..<endIndex, with: newValue.grid)
}
}
public subscript(column column: Int) -> Matrix {
get {
var result: [Element] = []
for i in 0..<rows {
let index = i * columns + column
result.append(self.grid[index])
}
return Matrix(rows, 1, result)
}
set {
assert(column < columns)
assert(newValue.grid.count == rows)
for i in 0..<rows {
let index = i * columns + column
grid[index] = newValue.grid[i]
}
}
}
public subscript(_ rows: [Int], _ columns: [Int]) -> Matrix {
get {
var arr: [Element] = []
for r in 0..<rows.count {
for c in 0..<columns.count {
arr.append(self[rows[r], columns[c]])
}
}
return Matrix(rows.count, columns.count, arr)
}
set(val) {
for r in 0..<rows.count {
for c in 0..<columns.count {
self[rows[r], columns[c]] = val[r, c]
}
}
}
}
public subscript(_ rows: [Int], _ column: Int) -> Matrix {
return self[rows, [column]]
}
public subscript(_ row: Int, _ columns: [Int]) -> Matrix {
return self[[row], columns]
}
public subscript(_ frow: (Int) -> [Int], _ fcol: ((Int) -> [Int])) -> Matrix {
get {
let rows = frow(self.rows)
let cols = fcol(self.columns)
return self[rows, cols]
}
set(val) {
let rows = frow(self.rows)
let cols = fcol(self.columns)
self[rows, cols] = val
}
}
public subscript(_ rows: [Int]) -> Matrix {
return self[rows, Array(0..<columns)]
}
public subscript(cols columns: [Int]) -> Matrix {
return self[Array(0..<rows), columns]
}
public subscript(_ frow: (Int) -> [Int], _ col: Int) -> Matrix {
get {
let rows = frow(self.rows)
let cols = [col]
return self[rows, cols]
}
set(val) {
let rows = frow(self.rows)
let cols = [col]
self[rows, cols] = val
}
}
public subscript(_ row: Int, _ fcol: (Int) -> [Int]) -> Matrix {
get {
let rows = [row]
let cols = fcol(self.columns)
return self[rows, cols]
}
set(val) {
let rows = [row]
let cols = fcol(self.columns)
self[rows, cols] = val
}
}
public subscript(_ frow: (Int) -> [Int], _ cols: [Int]) -> Matrix {
get {
return self[frow(rows), cols]
}
set(val) {
self[frow(rows), cols] = val
}
}
public subscript(_ rows: [Int], _ fcol: (Int) -> [Int]) -> Matrix {
get {
return self[rows, fcol(columns)]
}
set(val) {
self[rows, fcol(columns)] = val
}
}
public subscript(_ mask: Matrix<Bool>) -> Matrix<Element> {
get {
var re: [Element] = []
for r in 0..<rows {
for c in 0..<columns {
if mask[r, c] == true {
re.append(self[r, c])
}
}
}
return Matrix(1, re.count, re)
}
set(arr) {
for r in 0..<rows {
for c in 0..<columns {
if mask[r, c] == true {
self[r, c] = arr[0, r * columns + c]
}
}
}
}
}
fileprivate func indexIsValidForRow(_ row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
public static func << <T>(lhs: inout Matrix<T>, rhs: T) {
for r in 0..<lhs.rows {
for c in 0..<lhs.columns {
lhs[r, c] = rhs
}
}
}
public func reshape(_ shape: [Int]) -> Matrix {
precondition((shape[0] * shape[1] == self.size) || (shape[0] == -1) || (shape[1] == -1), "invalid shape")
var mat = self
var (rr, cc) = tuple(shape)
if (shape[0] == -1) && (shape[1] > 0) {
assert(size % shape[1] == 0)
rr = size / shape[1]
cc = shape[1]
} else if (shape[1] == -1) && (shape[0] > 0) {
cc = size / shape[0]
rr = shape[0]
}
mat.rows = rr
mat.columns = cc
return mat
}
public var t: Matrix {
get {
return transpose(self)
}
}
}
// MARK: - Printable
extension Matrix: CustomStringConvertible {
public var description: String {
var description = ""
for i in 0..<rows {
let contents = (0..<columns).map{"\(self[i, $0])"}.joined(separator: "\t")
switch (i, rows) {
case (0, 1):
description += "(\t\(contents)\t)"
case (0, _):
description += "⎛\t\(contents)\t⎞"
case (rows - 1, _):
description += "⎝\t\(contents)\t⎠"
default:
description += "⎜\t\(contents)\t⎥"
}
description += "\n"
}
return description
}
}
// MARK: - SequenceType
//extension Matrix: Sequence {
// public func makeIterator() -> AnyIterator<ArraySlice<Element>> {
// let endIndex = rows * columns
// var nextRowStartIndex = 0
//
// return AnyIterator {
// if nextRowStartIndex == endIndex {
// return nil
// }
//
// let currentRowStartIndex = nextRowStartIndex
// nextRowStartIndex += self.columns
//
// return self.grid[currentRowStartIndex..<nextRowStartIndex]
// }
// }
//}
//extension Matrix: Equatable {}
//public func ==<T: Equatable> (lhs: Matrix<T>, rhs: Matrix<T>) -> Bool {
// return lhs.rows == rhs.rows && lhs.columns == rhs.columns && lhs.grid == rhs.grid
//}
//MARK: Matrix<ScalarType>
//TODO: It is possible to move apply to the above extension. Might hurts performance though.
public extension Matrix where T: ScalarType {
// apply a function to reduce an axis to scalar
//TODO: apply<T2> might subsume this one
public func apply(_ f: ([T]) -> T, _ axis: Int) -> Matrix {
if axis == 0 {
var m: Matrix = zeros(1, columns)
for col in 0..<columns {
m[0, col] = f(self[column: col].grid)
}
return m
} else if axis == 1 {
var m: Matrix = zeros(rows, 1)
for row in 0..<rows {
m[row, 0] = f(self[row].grid)
}
return m
} else {
return Matrix([[f(grid)]])
}
}
// apply a function to reduce an axis to scalar
public func apply<T2: ScalarType>(_ f: ([T]) -> T2, _ axis: Int) -> Matrix<T2> {
if axis == 0 {
var m: Matrix<T2> = minimind.zeros(1, columns)
for col in 0..<columns {
m[0, col] = f(self[column: col].grid)
}
return m
} else if axis == 1 {
var m: Matrix<T2> = minimind.zeros(rows, 1)
for row in 0..<rows {
m[row, 0] = f(self[row].grid)
}
return m
} else {
return Matrix<T2>([[f(grid)]])
}
}
// Apply a transformation function to an axis
public func apply(_ f: ([T]) -> [T], _ axis: Int) -> Matrix<Element> {
var re: Matrix<T> = self.zeros(rows, columns)
switch axis {
case 1: for c in 0..<columns {
re[0∶, c] = Matrix(rows, 1, f(self[column: c].grid))
}
case 0: for r in 0..<rows {
re[r, 0∶] = Matrix(1, columns, f(self[r].grid))
}
default :
fatalError("invalid axis")
}
return re
}
public func apply(f: ([T], [T]) -> [T], arr: [T], axis: Int) -> Matrix<Element> {
var re: Matrix<T> = self.zeros(rows, columns)
switch axis {
case 1: for c in 0..<columns {
assert(rows == arr.count, "incompatible shape. arr.count must be equal self.rows")
re[0∶, c] = Matrix(rows, 1, f(self[column: c].grid, arr))
}
case 0: for r in 0..<rows {
assert(columns == arr.count, "incompatible shape. arr.count must be equal columns")
re[r, 0∶] = Matrix(1, columns, f(self[r].grid, arr))
}
default :
fatalError("invalid axis")
}
return re
}
public func sum(axis: Int = -1) -> Matrix {
return apply(minimind.sum, axis)
}
public func sum() -> Element {
return minimind.sum(grid)
}
public func zeros(_ rows: Int, _ columns: Int) -> Matrix {
return minimind.zeros(rows, columns)
}
}
//MARK: OPERATORS
public func add<T: ScalarType>(_ x: Matrix<T>, y: Matrix<T>) -> Matrix<T> {
checkMatrices(x, y, "same")
return Matrix<T>( x.rows, x.columns, (0..<x.grid.count).map{ i in x.grid[i] + y.grid[i] } )
}
public func add<T: ScalarType>(_ x: Matrix<T>, y: T) -> Matrix<T> {
return Matrix<T>( x.rows, x.columns, (0..<x.grid.count).map{ i in x.grid[i] + y } )
}
public func add<T: ScalarType>(_ x: T, y: Matrix<T>) -> Matrix<T> {
return Matrix<T>( y.rows, y.columns, (0..<y.grid.count).map{ i in x + y.grid[i] } )
}
public func sub<T: ScalarType>(_ x: Matrix<T>, y: Matrix<T>) -> Matrix<T> {
checkMatrices(x, y, "same")
return Matrix<T>( x.rows, x.columns, (0..<x.grid.count).map{ i in x.grid[i] - y.grid[i] } )
}
public func sub<T: ScalarType>(_ x: Matrix<T>, y: T) -> Matrix<T> {
return Matrix<T>( x.rows, x.columns, (0..<x.grid.count).map{ i in x.grid[i] - y } )
}
public func sub<T: ScalarType>(_ x: T, y: Matrix<T>) -> Matrix<T> {
return Matrix<T>( y.rows, y.columns, (0..<y.grid.count).map{ i in x - y.grid[i] } )
}
public func mul<T: ScalarType>(_ x: Matrix<T>, y: Matrix<T>) -> Matrix<T> {
checkMatrices(x, y, "same")
return Matrix<T>( x.rows, x.columns, (0..<x.grid.count).map{ i in x.grid[i] * y.grid[i] } )
}
public func mul<T: ScalarType>(_ x: Matrix<T>, y: T) -> Matrix<T> {
return Matrix<T>( x.rows, x.columns, (0..<x.grid.count).map{ i in x.grid[i] * y } )
}
public func mul<T: ScalarType>(_ x: T, y: Matrix<T>) -> Matrix<T> {
return Matrix<T>( y.rows, y.columns, (0..<y.grid.count).map{ i in x * y.grid[i] } )
}
public func div<T: ScalarType>(_ x: Matrix<T>, y: Matrix<T>) -> Matrix<T> {
checkMatrices(x, y, "same")
return Matrix<T>( x.rows, x.columns, (0..<x.grid.count).map{ i in x.grid[i] / y.grid[i] } )
}
public func div<T: ScalarType>(_ x: Matrix<T>, y: T) -> Matrix<T> {
return Matrix<T>( x.rows, x.columns, (0..<x.grid.count).map{ i in x.grid[i] / y } )
}
public func div<T: ScalarType>(_ x: T, y: Matrix<T>) -> Matrix<T> {
return Matrix<T>( y.rows, y.columns, (0..<y.grid.count).map{ i in x / y.grid[i] } )
}
public func kron<T: ScalarType>(_ x: Matrix<T>, _ y: Matrix<T>) -> Matrix<T> {
var mat: Matrix<T> = zeros(x.rows * y.rows, x.columns * y.columns)
for lr in 0..<x.rows {
for lc in 0..<x.columns {
for rr in 0..<y.rows {
for rc in 0..<y.columns {
mat[lr * y.rows + rr, lc * y.columns + rc] = x[lr, lc] * x[rr, rc]
}
}
}
}
return mat
}
public func +<T: ScalarType>(_ x: Matrix<T>, y: Matrix<T>) -> Matrix<T> {
return add(x, y: y)
}
public func +<T: ScalarType>(_ x: Matrix<T>, y: T) -> Matrix<T> {
return add(x, y: y)
}
public func +<T: ScalarType>(_ x: T, y: Matrix<T>) -> Matrix<T> {
return add(x, y: y)
}
public func -<T: ScalarType>(_ x: Matrix<T>, y: Matrix<T>) -> Matrix<T> {
return sub(x, y: y)
}
public func -<T: ScalarType>(_ x: Matrix<T>, y: T) -> Matrix<T> {
return sub(x, y: y)
}
public func -<T: ScalarType>(_ x: T, y: Matrix<T>) -> Matrix<T> {
return sub(x, y: y)
}
public func *<T: ScalarType>(_ x: Matrix<T>, y: Matrix<T>) -> Matrix<T> {
return mul(x, y: y)
}
public func *<T: ScalarType>(_ x: Matrix<T>, y: T) -> Matrix<T> {
return mul(x, y: y)
}
public func *<T: ScalarType>(_ x: T, y: Matrix<T>) -> Matrix<T> {
return mul(x, y: y)
}
public func /<T: ScalarType>(_ x: Matrix<T>, y: Matrix<T>) -> Matrix<T> {
return div(x, y: y)
}
public func /<T: ScalarType>(_ x: Matrix<T>, y: T) -> Matrix<T> {
return div(x, y: y)
}
public func /<T: ScalarType>(_ x: T, y: Matrix<T>) -> Matrix<T> {
return div(x, y: y)
}
infix operator ∘
// Entry-wise product
public func ∘<T: ScalarType>(lhs: Matrix<T>, rhs: Matrix<T>) -> Matrix<T> {
var newmat = lhs
newmat.grid = lhs.grid * rhs.grid
return newmat
}
infix operator ⊗
//Kronecker product
public func ⊗ <T: ScalarType>(lhs: Matrix<T>, rhs: Matrix<T>) -> Matrix<T> {
var mat: Matrix<T> = zeros(lhs.rows * rhs.rows, lhs.columns * rhs.columns)
for lr in 0..<lhs.rows {
for lc in 0..<lhs.columns {
for rr in 0..<rhs.rows {
for rc in 0..<rhs.columns {
mat[lr * rhs.rows + rr, lc * rhs.columns + rc] = lhs[lr, lc] * rhs[rr, rc]
}
}
}
}
return mat
}
// Columns wise operators
infix operator |+
public func |+<T: ScalarType>(lhs: Matrix<T>, rhs: Matrix<T>) -> Matrix<T> {
return lhs.apply(f: {(x: [T], y: [T]) -> [T] in x + y}, arr: rhs.grid, axis: 1)
}
infix operator |-
public func |-<T: ScalarType>(lhs: Matrix<T>, rhs: Matrix<T>) -> Matrix<T> {
return lhs.apply(f: {(x: [T], y: [T]) -> [T] in x - y}, arr: rhs.grid, axis: 1)
}
infix operator |*
public func |*<T: ScalarType>(lhs: Matrix<T>, rhs: Matrix<T>) -> Matrix<T> {
return lhs.apply(f: {(x: [T], y: [T]) -> [T] in x * y}, arr: rhs.grid, axis: 1)
}
infix operator |∘
public func |∘<T: ScalarType>(lhs: Matrix<T>, rhs: Matrix<T>) -> Matrix<T> {
return lhs.apply(f: {(x: [T], y: [T]) -> [T] in x * y}, arr: rhs.grid, axis: 1)
}
infix operator |/
public func |/<T: ScalarType>(lhs: Matrix<T>, rhs: Matrix<T>) -> Matrix<T> {
return lhs.apply(f: {(x: [T], y: [T]) -> [T] in x / y}, arr: rhs.grid, axis: 1)
}
// Row-wise operators
infix operator .+
public func .+<T: ScalarType>(lhs: Matrix<T>, rhs: Matrix<T>) -> Matrix<T> {
return lhs.apply(f: {(x: [T], y: [T]) -> [T] in x + y}, arr: rhs.grid, axis: 0)
}
infix operator .-
public func .-<T: ScalarType>(lhs: Matrix<T>, rhs: Matrix<T>) -> Matrix<T> {
return lhs.apply(f: {(x: [T], y: [T]) -> [T] in x - y}, arr: rhs.grid, axis: 0)
}
infix operator .*
public func .*<T: ScalarType>(lhs: Matrix<T>, rhs: Matrix<T>) -> Matrix<T> {
return lhs.apply(f: {(x: [T], y: [T]) -> [T] in x * y}, arr: rhs.grid, axis: 0)
}
infix operator .∘
public func .∘<T: ScalarType>(lhs: Matrix<T>, rhs: Matrix<T>) -> Matrix<T> {
return lhs.apply(f: {(x: [T], y: [T]) -> [T] in x * y}, arr: rhs.grid, axis: 0)
}
infix operator ./
public func ./<T: ScalarType>(lhs: Matrix<T>, rhs: Matrix<T>) -> Matrix<T> {
return lhs.apply(f: {(x: [T], y: [T]) -> [T] in x / y}, arr: rhs.grid, axis: 0)
}
//MARK: LINEAR ALGEBRA & MATH
public func norm<T: FloatingPointScalarType>(_ mat: Matrix<T>, _ ord: String = "fro", p: T = 2, q: T = 1) -> T {
switch ord {
case "fro", "euclidean" :
return sqrt(trace(mat * mat.t))
default:
return sqrt(trace(mat * mat.t))
}
}
public func sign<T: ScalarType>(_ mat: Matrix<T>) -> Matrix<T> {
return Matrix<T>(mat.rows, mat.columns, sign(mat.grid))
}
public func sqrt<T: FloatType>(_ mat: Matrix<T>) -> Matrix<T> {
return Matrix<T>(mat.rows, mat.columns, sqrt(mat.grid))
}
public func abs<T: ScalarType>(_ mat: Matrix<T>) -> Matrix<T> {
var newmat = mat
newmat.grid = minimind.abs(newmat.grid)
return newmat
}
public func square<T: ScalarType>(_ mat: inout Matrix<T>, inplace: Bool = false) -> Matrix<T> {
if inplace {
for r in 0..<mat.grid.count {
mat.grid[r] = mat.grid[r] * mat.grid[r]
}
return mat
} else {
return Matrix<T>(mat.rows, mat.columns, mat.grid.map{ $0 * $0 })
}
}
public func max<T: ScalarType>(_ mat: Matrix<T>) -> T {
return minimind.max(mat.grid)
}
public func min<T: ScalarType>(_ mat: Matrix<T>) -> T {
return minimind.min(mat.grid)
}
public func max<T: ScalarType>(_ mat: Matrix<T>, axis: Int) -> Matrix<T> {
return mat.apply(minimind.max, axis)
}
// element wise max
public func fmax<T: ScalarType>(_ mat: Matrix<T>, _ a: T) -> Matrix<T> {
return Matrix<T>(mat.rows, mat.columns, mat.grid.map{ $0 > a ? $0 : a } )
}
public func min<T: ScalarType>(_ mat: Matrix<T>, axis: Int) -> Matrix<T> {
return mat.apply(minimind.min, axis)
}
public func argmax<T: ScalarType>(_ mat: Matrix<T>, _ axis: Int) -> Matrix<IndexType> {
return mat.apply(minimind.argmax, axis)
}
public func argmin<T: ScalarType>(_ mat: Matrix<T>, _ axis: Int) -> Matrix<IndexType> {
return mat.apply(minimind.argmin, axis)
}
public func cross_add<T: ScalarType>(_ lhs: Matrix<T>, _ rhs: Matrix<T>) -> Matrix<T> {
precondition((lhs.columns == 1) && (rhs.columns == 1), "lhs and rhs must have shape (N, 1)")
var re: Matrix<T> = zeros(lhs.rows, rhs.rows)
for i in 0..<lhs.rows {
for j in 0..<rhs.rows {
re[i, j] = lhs[i, 0] + rhs[j, 0]
}
}
return re
}
public func trace<T: ScalarType>(_ mat: Matrix<T>) ->T {
return sum(diag(mat).grid)
}
//MARK: TRAVERSE
public func reduce_sum<T: ScalarType>(_ mat: Matrix<T>, axis: Int = -1) -> Matrix<T> {
return mat.apply(minimind.sum, axis)
}
public func reduce_prod<T: ScalarType>(_ mat: Matrix<T>,_ axis: Int = -1) -> Matrix<T> {
return mat.apply(minimind.prod, axis)
}
//MARK: ACCESS
public func diag<T: ScalarType>(_ mat: Matrix<T>) -> Matrix<T> {
var dmat: Matrix<T> = zeros(1, mat.columns)
for i in 0..<mat.columns {
dmat[0, i] = mat[i, i]
}
return dmat
}
public func tril<T: ScalarType>(_ mat: Matrix<T>) -> Matrix<T> {
var dmat = mat
for i in 0..<mat.rows{
for j in 0...i {
if i != j {
dmat[j, i] = T.zero
}
}
}
return dmat
}
public func triu<T: ScalarType>(_ mat: Matrix<T>) -> Matrix<T> {
var dmat = mat
for i in 0..<mat.rows{
for j in 0...i {
if i != j {
dmat[i, j] = T.zero
}
}
}
return dmat
}
//MARK: TRANSFORMERS
public func transpose<T>(_ mat: Matrix<T>) -> Matrix<T>{
var newmat = mat
newmat.rows = mat.columns
newmat.columns = mat.rows
for r in 0..<newmat.rows {
for c in 0..<newmat.columns {
newmat[r, c] = mat[c, r]
}
}
return newmat
}
public func clip<T: ScalarType>(_ mat: Matrix<T>, _ floor: T, _ ceil: T, _ inplace: Bool = false) -> Matrix<T> {
var newmat = mat
newmat.grid = clip(mat.grid, floor, ceil)
return newmat
}
public func tile<T: ScalarType>(_ mat: Matrix<T>, _ shape: [Int]) -> Matrix<T> {
var newmat: Matrix<T> = zeros(mat.rows * shape[0], mat.columns * shape[1])
for row in 0..<shape[0] {
for col in 0..<shape[1] {
for i in 0..<mat.rows {
for j in 0..<mat.columns {
newmat[row * mat.rows + i, col * mat.columns + j] = mat[i, j]
}
}
}
}
return newmat
}
public func vstack<T>(_ mats: [Matrix<T>]) -> Matrix<T> {
checkMatrices(mats, "sameColumns")
let rows = mats.map{ x in x.rows}.sum()
var data = [T]()
for i in 0..<mats.count {
data.append(contentsOf: mats[i].grid)
}
return Matrix<T>(rows, mats[0].columns, data)
}
public func hstack<T>(_ mats: [Matrix<T>]) -> Matrix<T> {
checkMatrices(mats, "sameRows")
let cols = mats.map{ x in x.columns}.sum()
let newmats = mats.map{ transpose($0) }
return Matrix<T>(mats[0].rows, cols, transpose(vstack(newmats)).grid)
}
//MARK: CREATORS
public func meshgrid<T: ScalarType>(_ x: [T], _ y: [T]) -> (Matrix<T>, Matrix<T>) {
var X: Matrix<T> = zeros(len(y), len(x))
for r in 0..<len(y) {
X[r] = Matrix([x])
}
var Y: Matrix<T> = zeros(len(y), len(x))
for c in 0..<len(x) {
Y[column: c] = Matrix([y]).t
}
return (X, Y)
}
public func diagonal<T: ScalarType>(_ a: [T]) -> Matrix<T> {
var m: Matrix<T> = zeros(a.count, a.count)
for i in 0..<a.count {
m[i, i] = a[i]
}
return m
}
public func ones<T: ScalarType>(_ rows: Int, _ columns: Int) -> Matrix<T> {
return Matrix<T>(rows: rows, columns: columns, repeatedValue: T.one)
}
public func zeros<T: ScalarType>(_ rows: Int, _ columns: Int) -> Matrix<T> {
return Matrix<T>(rows: rows, columns: columns, repeatedValue: T.zero)
}
public func zeros_like<T: ScalarType>(_ mat: Matrix<T>) -> Matrix<T> {
return zeros(mat.rows, mat.columns)
}
public func eye<T: ScalarType>(_ D: Int) -> Matrix<T> {
var mat = Matrix<T>(rows: D, columns: D, repeatedValue: T.zero)
for i in 0..<D {
mat[i, i] = T.one
}
return mat
}
public func linspace<T: FloatingPointScalarType>(_ from: T, _ to: T, _ n: Int) -> Matrix<T> {
let step = (to - from) / T(n)
return Matrix<T>(1, n, (0..<n).map{ T($0) * step + from })
}
|
mit
|
cd0a4500c34877ab967768f9c16ba61d
| 28.014151 | 114 | 0.508901 | 3.219997 | false | false | false | false |
Peterrkang/SpotMe
|
SpotMe/SpotMe/Event.swift
|
1
|
1564
|
//
// Event.swift
// SpotMe
//
// Created by Peter Kang on 10/19/16.
// Copyright © 2016 Peter Kang. All rights reserved.
//
import Foundation
class Event {
private var _id: String
private var _title: String
private var _userId: String
var title: String {
return _title
}
var userId: String {
return _userId
}
var id: String {
return _id
}
init(id: String, userId: String, title: String){
_id = id
_userId = userId
_title = title
}
/*
private var _location: [Double]
private var _image: String
private var _duration: Double
private var _createdAt: String
private var _creator: String
private var _details: String
var image: String {
return _image
}
var createdAt: String {
return _createdAt
}
var location: [Double]{
return _location
}
var duration: Double {
return _duration
}
var creator: String {
return _creator
}
var details: String {
return _details
}
init(title: String, creator: String, location: [Double], duration: Double, image: String, createdAt: String, details: String){
_title = title
_image = image
_location = location
_creator = creator
_duration = duration
_createdAt = createdAt
_details = details
}
func distanceCheck(){
}
*/
}
|
mit
|
d527b500ff7b64dd6e02b99b10d2f3ce
| 15.98913 | 130 | 0.52975 | 4.570175 | false | false | false | false |
CrowdShelf/ios
|
CrowdShelf/CrowdShelf/Handlers/ExternalDatabaseHandler.swift
|
1
|
21169
|
//
// ExternalDatabaseHandler.swift
// CrowdShelf
//
// Created by Øyvind Grimnes on 03/11/15.
// Copyright © 2015 Øyvind Grimnes. All rights reserved.
//
import Foundation
import Alamofire
public class ExternalDatabaseHandler {
public class func resultsForQuery(query: String, withCompletionHandler completionHandler: (([BookInformation])->Void)) {
if query.characters.count < 2 {
return completionHandler([])
}
self.resultsFromGoogleForQuery(query) { (bookInformationArray) -> Void in
for bookInformation in bookInformationArray {
if bookInformation.thumbnailURLString == nil {
continue
}
if let URL = NSURL(string: bookInformation.thumbnailURLString!) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
if let thumbnailData = NSData(contentsOfURL: URL) {
bookInformation.thumbnailData = thumbnailData
completionHandler(bookInformationArray)
}
})
}
}
completionHandler(bookInformationArray)
}
}
/**
Retrieve information about a book
Checks the local cache for the information. If not present, it will query an information provider for the information and cache it for later
- parameter isbn: international standard book number of the book
- parameter completionHandler: closure which will be called with the result of the request
*/
public class func informationAboutBook(isbn: String, withCompletionHandler completionHandler: (([BookInformation])->Void)) {
if isbn.characters.count != 10 && isbn.characters.count != 13 {
return completionHandler([])
}
self.informationFromGoogleAboutBook(isbn) { (bookInformationArray: [BookInformation]) -> Void in
for bookInformation in bookInformationArray {
if bookInformation.thumbnailURLString == nil {
continue
}
if let URL = NSURL(string: bookInformation.thumbnailURLString!) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
if let thumbnailData = NSData(contentsOfURL: URL) {
bookInformation.thumbnailData = thumbnailData
}
completionHandler(bookInformationArray)
})
}
}
completionHandler(bookInformationArray)
}
}
// MARK: - Books
/**
Add book to database or update existing one
- parameter book: book that will be added or updated
- parameter completionHandler: closure which will be called with the result of the request
*/
public class func addBook(book: Book, withCompletionHandler completionHandler: ((Book?) -> Void)?) {
var data = book.serialize()
data.removeValueForKey("_id")
self.sendRequestWithSubRoute("books", usingMethod: .POST, andParameters: data) { (result, isSuccess) -> Void in
var book: Book?
if let resultDictionary = result as? [String: AnyObject] {
book = Book(dictionary: resultDictionary)
}
completionHandler?(book)
}
}
/**
Remove book from database
- parameter bookID: id of the book that will be removed
- parameter completionHandler: closure which will be called with the result of the request
*/
public class func removeBook(bookID: String, withCompletionHandler completionHandler: ((Bool) -> Void)?) {
self.sendRequestWithSubRoute("books/\(bookID)", usingMethod: .DELETE) { (result, isSuccess) -> Void in
completionHandler?(isSuccess)
}
}
/**
Get book from database
- parameter bookID: ID of the book
- parameter completionHandler: closure which will be called with the result of the request
*/
public class func getBook(bookID: String, withCompletionHandler completionHandler: ((Book?)->Void)) {
self.sendRequestWithSubRoute("books/\(bookID)", usingMethod: .GET) { (result, isSuccess) -> Void in
var book: Book?
if let value = result as? [String: AnyObject] {
book = Book(dictionary: value)
}
completionHandler(book)
}
}
/**
Get books from database matching query. Retrieves all books if parameters is nil
- parameter parameters: dictionary containing key-value parameters used for querying
- parameter completionHandler: closure which will be called with the result of the request
*/
public class func getBooksWithParameters(parameters: [String: AnyObject]?, useCache cache: Bool = true, andCompletionHandler completionHandler: (([Book])->Void)) {
self.sendRequestWithSubRoute("books", usingMethod: .GET, andParameters: parameters) { (result, isSuccess) -> Void in
var books: [Book] = []
if let resultDictionary = result as? [String: AnyObject] {
if let valueArray = resultDictionary["books"] as? [[String: AnyObject]] {
books = valueArray.map {Book(dictionary: $0)}
} else if let valueDictionary = resultDictionary["books"] as? [String: AnyObject] {
books = [Book(dictionary: valueDictionary)]
}
}
completionHandler(books)
}
}
// MARK: - Users
/**
Login as user with the provided username if it exists
- parameter username: screen name of the user
- parameter completionHandler: closure which will be called with the result of the request
*/
public class func loginWithUsername(username: String, andPassword password: String, withCompletionHandler completionHandler: ((User?)->Void)) {
self.sendRequestWithSubRoute("login", usingMethod: .POST, andParameters: ["username": username, "password": password]) { (result, isSuccess) -> Void in
var user: User?
if isSuccess {
if let userValue = result as? [String: AnyObject] {
user = User(dictionary: userValue)
}
}
completionHandler(user)
}
}
public class func userForUserID(userID: String, withCompletionHandler completionHandler: ((User?)->Void
)) {
self.sendRequestWithSubRoute("users/\(userID)", usingMethod: .GET) { (result, isSuccess) -> Void in
var user: User?
if isSuccess {
if let userValue = result as? [String: AnyObject] {
user = User(dictionary: userValue)
}
}
completionHandler(user)
}
}
public class func userForUsername(username: String, withCompletionHandler completionHandler: ((User?)->Void
)) {
self.sendRequestWithSubRoute("users", usingMethod: .GET, andParameters: ["username":username]) { (result, isSuccess) -> Void in
var user: User?
if isSuccess && result != nil {
if let userDictionaries = result!["users"] as? [AnyObject] {
if let userValue = userDictionaries.first as? [String: AnyObject] {
user = User(dictionary: userValue)
}
}
}
completionHandler(user)
}
}
/**
Get all users from the database
- parameter completionHandler: closure which will be called with the result of the request
*/
public class func usersWithCompletionHandler(completionHandler: (([User])->Void)) {
self.sendRequestWithSubRoute("users", usingMethod: .GET) { (result, isSuccess) -> Void in
var users: [User] = []
if isSuccess {
if let resultDictionary = result as? [String: AnyObject] {
if let resultsArray = resultDictionary["users"] as? [[String: AnyObject]] {
users = resultsArray.map {User(dictionary: $0)}
}
}
}
completionHandler(users)
}
}
/**
Get user with the provided ID if it exists
- parameter userID: ID of the user
- parameter completionHandler: closure which will be called with the result of the request
*/
public class func getUser(userID: String, withCompletionHandler completionHandler: ((User?)->Void)) {
self.sendRequestWithSubRoute("users/\(userID)", usingMethod: .GET) { (result, isSuccess) -> Void in
var user: User?
if isSuccess {
if let resultDictionary = result as? [String: AnyObject] {
user = User(dictionary: resultDictionary)
}
}
completionHandler(user)
}
}
/**
Create a user in the database
- parameter user: user object containing information needed to create a user
- parameter completionHandler: closure which will be called with the result of the request
*/
public class func createUser(user: User, withCompletionHandler completionHandler: ((User?)->Void )) {
var parameters = user.serialize()
parameters.removeValueForKey("_id")
self.sendRequestWithSubRoute("users", usingMethod: .POST, andParameters: parameters) { (result, isSuccess) -> Void in
var user: User?
if isSuccess {
if let value = result as? [String: AnyObject] {
user = User(dictionary: value)
}
}
completionHandler(user)
}
}
/**
Add renter to owners book in database
- parameter renter: username of the renter
- parameter bookID: the ID of the book
- parameter completionHandler: closure which will be called with the result of the request
*/
public class func addRenter(renterID: String, toBook bookID: String, withCompletionHandler completionHandler: ((Bool) -> Void)?) {
self.sendRequestWithSubRoute("books/\(bookID)/renter/\(renterID)", usingMethod: .PUT) { (result, isSuccess) -> Void in
completionHandler?(isSuccess)
}
}
/**
Remove renter from owners book in database
- parameter renter: username of the renter
- parameter bookID: the ID of the book
- parameter completionHandler: closure which will be called with the result of the request
*/
public class func removeRenter(renterID: String, fromBook bookID: String, withCompletionHandler completionHandler: ((Bool) -> Void)?) {
self.sendRequestWithSubRoute("books/\(bookID)/renter/\(renterID)", usingMethod: .DELETE, andParameters: nil) { (result, isSuccess) -> Void in
completionHandler?(isSuccess)
}
}
public class func forgotPassword(username: String, withCompletionHandler completionHandler: ((Bool)->Void)) {
self.sendRequestWithSubRoute("users/forgotpassword", usingMethod: .POST, andParameters: ["username": username]) { (_, isSuccess) -> Void in
completionHandler(isSuccess)
}
}
public class func resetPasswordForUser(username: String, password: String, key: String, withCompletionHandler completionHandler: ((Bool)->Void)) {
self.sendRequestWithSubRoute("users/resetpassword", usingMethod: .POST, andParameters: ["username": username, "key": key, "password": password]) { (_, isSuccess) -> Void in
completionHandler(isSuccess)
}
}
// MARK: - Crowds
public class func getCrowdsWithParameters(parameters: [String: AnyObject]?, andCompletionHandler completionHandler: (([Crowd]) -> Void)) {
self.sendRequestWithSubRoute("crowds", usingMethod: .GET, andParameters: parameters) { (result, isSuccess) -> Void in
var crowds: [Crowd] = []
if isSuccess {
if let resultDictionary = result as? [String: AnyObject] {
if let resultsArray = resultDictionary["crowds"] as? [[String: AnyObject]] {
crowds = resultsArray.map {Crowd(dictionary: $0)}
}
}
}
completionHandler(crowds)
}
}
public class func getCrowd(crowdID: String, withCompletionHandler completionHandler: ((Crowd?)->Void)) {
self.sendRequestWithSubRoute("crowds/\(crowdID)", usingMethod: .GET) { (result, isSuccess) -> Void in
var crowd: Crowd?
if let crowdValue = result as? [String: AnyObject] {
crowd = Crowd(dictionary: crowdValue)
}
completionHandler(crowd)
}
}
public class func createCrowd(crowd: Crowd, withCompletionHandler completionHandler: ((Crowd?)-> Void)) {
self.sendRequestWithSubRoute("crowds", usingMethod: .POST, andParameters: crowd.serialize()) { (result, isSuccess) -> Void in
var crowd: Crowd?
if isSuccess {
if let crowdDictionary = result as? [String: AnyObject] {
crowd = Crowd(dictionary: crowdDictionary)
}
}
completionHandler(crowd)
}
}
public class func updateCrowd(crowd: Crowd, withCompletionHandler completionHandler: ((Bool)-> Void)?) {
self.sendRequestWithSubRoute("crowds/\(crowd._id!)", usingMethod: .PUT, andParameters: crowd.serialize()) { (result, isSuccess) -> Void in
completionHandler?(isSuccess)
}
}
public class func deleteCrowd(crowdID: String, withCompletionHandler completionHandler: ((Bool)-> Void)?) {
self.sendRequestWithSubRoute("crowds/\(crowdID)", usingMethod: .DELETE) { (result, isSuccess) -> Void in
completionHandler?(isSuccess)
}
}
public class func addUser(userID: String, toCrowd crowdID: String, withCompletionHandler completionHandler: ((Bool)->Void)?) {
self.sendRequestWithSubRoute("crowds/\(crowdID)/members/\(userID)", usingMethod: .PUT) { (result, isSuccess) -> Void in
completionHandler?(isSuccess)
}
}
public class func removeUser(userID: String, fromCrowd crowdID: String, withCompletionHandler completionHandler: ((Bool)->Void)?) {
self.sendRequestWithSubRoute("crowds/\(crowdID)/members/\(userID)", usingMethod: .DELETE) { (result, isSuccess) -> Void in
completionHandler?(isSuccess)
}
}
// MARK: - General
/**
Extracts information from the results based on predefined, provider based key-value coded mapping. NSNull values are discarded
- parameter results: the dictionary retrieved form google's books API
returns: A dictionary containing values and keys based on the defined mapping
*/
public class func dictionaryFromDictionary(originalDictionary: NSDictionary, usingMapping mapping: [String: String]) -> [String: AnyObject]{
var dictionary: [String: AnyObject] = [:]
for (key, keyPath) in mapping {
if let value = originalDictionary.valueForKeyPath(keyPath) {
if !(value is NSNull) {
dictionary[key] = value
}
}
}
return dictionary
}
// MARK: - Internal
/**
Sends a request to a sub path of the enviroments host root
- parameter subRoute: subpath for the request from the environments host root
- parameter method: HTTP method that should be used
- parameter parameters: a dictionary with key-value parameters
- parameter parameterEncoding: the Alamofire.ParameterEncoding to be used (e.g. URL or JSON)
- parameter completionHandler: closure which will be called with the result of the request
*/
internal class func sendRequestWithSubRoute(subRoute: String,
usingMethod method: Alamofire.Method,
andParameters parameters: [String: AnyObject]? = nil,
withCompletionHandler completionHandler: ((AnyObject?, Bool)->Void)?) {
let route = CS_ENVIRONMENT.hostString() + subRoute
self.sendRequestWithRoute(route, usingMethod: method, andParameters: parameters, withCompletionHandler: completionHandler)
}
/**
The endpoint in the client application responsible for sending an asynchronous request and handle the response
- parameter route: route for the request
- parameter method: HTTP method that should be used
- parameter parameters: a dictionary with key-value parameters
- parameter parameterEncoding: the Alamofire.ParameterEncoding to be used (e.g. URL or JSON)
- parameter completionHandler: closure which will be called with the result of the request
*/
internal class func sendRequestWithRoute(route: String,
usingMethod method: Alamofire.Method,
andParameters parameters: [String: AnyObject]?,
withCompletionHandler completionHandler: ((AnyObject?, Bool)->Void)?) {
csprint(CS_DEBUG_NETWORK, "Send request to URL:", route)
let encoding: ParameterEncoding
switch method {
case .GET, .DELETE:
encoding = .URL
default:
encoding = .JSON
}
var parametersWithToken = parameters ?? [:]
if let token = User.localUser?.token {
parametersWithToken["token"] = token
}
var secondAttempt = false
Alamofire.request(method, route, parameters: parametersWithToken, encoding: encoding, headers: ["Content-Type": "application/json"])
.responseJSON { (request, response, result) -> Void in
let isSuccess = response!.statusCode == 200
if isSuccess {
csprint(CS_DEBUG_NETWORK, "Request successful:", request!, "\nStatus code:", response?.statusCode ?? "none")
} else {
csprint(CS_DEBUG_NETWORK, "Request failed:", request!, "\nStatus code:", response?.statusCode ?? "none", "\nError:", result)
}
if response?.statusCode == 401 {
if !secondAttempt {
secondAttempt = true
if let password = User.localUser?.password, username = User.localUser?.username {
self.loginWithUsername(username, andPassword: password, withCompletionHandler: { (user) -> Void in
User.loginUser(user!)
sendRequestWithRoute(route, usingMethod: method, andParameters: parameters, withCompletionHandler: completionHandler)
})
}
return
}
}
if isSuccess {
completionHandler?(result.value, isSuccess)
} else {
completionHandler?(nil, isSuccess)
csprint(CS_DEBUG_NETWORK, result.debugDescription)
}
}
}
}
|
mit
|
a18fc5d27f1c253d01f5fec6ae28a2ab
| 38.125693 | 180 | 0.556175 | 5.611347 | false | false | false | false |
QuarkX/Quark
|
Sources/Quark/HTTP/Serializer/RequestSerializer.swift
|
1
|
1627
|
public class RequestSerializer {
let stream: Stream
let bufferSize: Int
public init(stream: Stream, bufferSize: Int = 2048) {
self.stream = stream
self.bufferSize = bufferSize
}
public func serialize(_ request: Request) throws {
let newLine: Data = Data([13, 10])
try stream.write("\(request.method) \(request.uri.percentEncoded()) HTTP/\(request.version.major).\(request.version.minor)")
try stream.write(newLine)
for (name, value) in request.headers.headers {
try stream.write("\(name): \(value)")
try stream.write(newLine)
}
try stream.write(newLine)
switch request.body {
case .buffer(let buffer):
try stream.write(buffer)
case .reader(let reader):
var buffer = Data(count: bufferSize)
while !reader.closed {
let bytesRead = try reader.read(into: &buffer)
if bytesRead == 0 {
break
}
try stream.write(String(bytesRead, radix: 16))
try stream.write(newLine)
try stream.write(buffer, length: bytesRead)
try stream.write(newLine)
}
try stream.write("0")
try stream.write(newLine)
try stream.write(newLine)
case .writer(let writer):
let body = BodyStream(stream)
try writer(body)
try stream.write("0")
try stream.write(newLine)
try stream.write(newLine)
}
try stream.flush()
}
}
|
mit
|
b72541d686dbd3c127ea9e8bc67a33e7
| 28.053571 | 132 | 0.541487 | 4.688761 | false | false | false | false |
wscqs/FMDemo-
|
FMDemo/Classes/Module/Record/CutRecordViewController.swift
|
1
|
9407
|
//
// CutRecordViewController.swift
// FMDemo
//
// Created by mba on 17/1/25.
// Copyright © 2017年 mbalib. All rights reserved.
//
import UIKit
import AVFoundation
class CutRecordViewController: UIViewController {
var url: URL?
var pointXArray: [CGFloat]?{
didSet {
totalTime = Double(pointXArray?.count ?? 0) * 0.2
}
}
/// 保存点击图片
var imgDictArray: [RecordSelectImgModel] = [RecordSelectImgModel]()
/// 剪切后生成的url
var cutExportURL: URL?
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var bannerImg: UIImageView!
@IBOutlet weak var sliderTimeLabel: UILabel!
@IBOutlet weak var slider: CutBarWaveView!
@IBOutlet weak var listenShowTimeLabel: UILabel!
@IBOutlet weak var listenPlayBtn: UIButton!
@IBOutlet weak var listenStatusLabel: UILabel!
@IBOutlet weak var cutBtn: UIButton!
var thumbPointXIndex: Int = 0 {
didSet {
playTime = Double(thumbPointXIndex) * 0.2
}
}
var totalTime: TimeInterval = 0
var playTime: TimeInterval = 0
var cutTime: TimeInterval = 0
/// 播放的计时器
var sliderTimer: Timer?
var player: MBAAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
setup()
slider.isHidden = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if (pointXArray?.count ?? 0 ) < 15 {
bannerImg.isHidden = true
_ = navigationController?.popViewController(animated: true)
MBAToast.show(text: "时间太短,不能剪切")
return
}
guard let url = url else {
return
}
slider.isHidden = false
player = MBAAudioPlayer(contentsOf: url)
slider.pointXArray = pointXArray
// slider.pointXArray = testArray
slider.delegate = self
timeLabel.text = "00:00-\(totalTime.getFormatTime())"
initTimer()
pauseTimer()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
pausePlay()
}
func updateTime() {
if thumbPointXIndex >= (pointXArray?.count ?? 0){
stopPlay()
thumbPointXIndex = Int(self.cutTime / 0.2)
bannerImg.image = #imageLiteral(resourceName: "record_bannerBg")
listenShowTimeLabel.isHidden = true
return
}
thumbPointXIndex = thumbPointXIndex + 1
slider.setPlayProgress(thumbPointXIndex: thumbPointXIndex)
listenShowTimeLabel.text = "\(playTime.getFormatTime()) - \(totalTime.getFormatTime())"
setSpannerImg()
}
func sliderTimerEvent() {
updateTime()
}
}
extension CutRecordViewController {
func setup() {
listenPlayBtn.addTarget(self, action: #selector(actionPlayClick), for: .touchUpInside)
listenPlayBtn.adjustsImageWhenHighlighted = false
cutBtn.addTarget(self, action: #selector(actionCut), for: .touchUpInside)
}
}
extension CutRecordViewController {
//MARK: 点击播放
func actionPlayClick(sender: UIButton) {
sender.isSelected = !sender.isSelected
if sender.isSelected { // 播放状态
listenStatusLabel.text = "暂停"
listenShowTimeLabel.isHidden = false
player.currentTime = playTime
continuePlay()
} else {
listenShowTimeLabel.isHidden = true
listenStatusLabel.text = "播放"
pausePlay()
}
}
func actionCut(sender: UIButton) {
pausePlay()
let startCutTime = 0.0
let stopCutTime = cutTime
MBAAudioUtil.cutAudio(of: url!, startTime: startCutTime, stopTime: stopCutTime) { (cutExportURL) in
if let cutExportURL = cutExportURL {
// 剪切成功后,重新设置[cutExportURL,self.pointXArray ?? [],self.imgDictArray]]
if self.imgDictArray.count > 0 {
for (index,imgDict) in self.imgDictArray.enumerated() {
for i in self.thumbPointXIndex ..< (self.pointXArray?.count)! {
if i == imgDict.thumbPointXIndex {
if index < self.imgDictArray.count {
self.imgDictArray.removeSubrange(Range(uncheckedBounds: (lower: index, upper: self.imgDictArray.count)))
}
break
}
}
}
}
if Int(self.cutTime*5) < (self.pointXArray?.count)! {
self.pointXArray?.removeSubrange(Range(uncheckedBounds: (lower: Int(self.cutTime*5), upper: (self.pointXArray?.count)!)))
}
let notification = Notification(name: Notification.Name(rawValue: "cutComplet"), object: nil, userInfo: ["cutComplet":[cutExportURL,self.pointXArray ?? [],self.imgDictArray]])
NotificationCenter.default.post(notification)
_ = self.navigationController?.popViewController(animated: true)
// print(cutExportURL)
} else {
print("剪切失败")
}
}
}
}
extension CutRecordViewController {
func initTimer() {
sliderTimer = Timer.scheduledTimer(timeInterval: kWaveTime, target: self, selector: #selector(sliderTimerEvent), userInfo: nil, repeats: true)
}
func pauseTimer() {
sliderTimer?.fireDate = Date.distantFuture
}
func continueTimer() {
sliderTimer?.fireDate = Date()
}
func stopTimer() {
sliderTimer?.invalidate()
sliderTimer = nil
}
}
extension CutRecordViewController {
func pausePlay() {
player?.pausePlay()
pauseTimer()
}
func continuePlay() {
player?.continuePlay()
continueTimer()
}
func stopPlay() {
pauseTimer()
listenPlayBtn.isSelected = false
listenStatusLabel.text = "播放"
}
}
// MARK: - CutBarWaveViewDelegate
extension CutRecordViewController: CutBarWaveViewDelegate {
// 根据截取音频的滑块,变换时间位置,及播放时间
func changceTimeLabel(cutBarWaveView: CutBarWaveView, centerX: CGFloat, thumbPointXIndex: Int) {
setSliderTime(centerX: centerX, thumbPointXIndex: thumbPointXIndex)
setSpannerImg()
}
func setSliderTime(centerX: CGFloat, thumbPointXIndex: Int) {
let sliderTime = Double(thumbPointXIndex) * 0.2
sliderTimeLabel.text = sliderTime.getFormatTime()
sliderTimeLabel.sizeToFit()
sliderTimeLabel.textAlignment = .center
sliderTimeLabel.center = CGPoint(x: centerX, y: 12)
self.thumbPointXIndex = thumbPointXIndex
self.cutTime = Double(thumbPointXIndex) * 0.2
player.currentTime = playTime
timeLabel.text = "\(cutTime.getFormatTime()) - \(totalTime.getFormatTime())"
}
func setSpannerImg() {
if imgDictArray.count == 0 {
bannerImg.isHidden = true
return
}
bannerImg.isHidden = false
for (index,imgDict) in imgDictArray.enumerated() {
if thumbPointXIndex == imgDict.thumbPointXIndex {
bannerImg.image = imgDict.image
imgAnimation()
break
}
if index == 0 {
if thumbPointXIndex < imgDictArray[index].thumbPointXIndex {
bannerImg.image = #imageLiteral(resourceName: "record_bannerBg")
imgAnimation()
break
}
if imgDictArray.count == 1{
if thumbPointXIndex >= imgDictArray[index].thumbPointXIndex {
bannerImg.image = imgDictArray[index].image
imgAnimation()
break
}
}
} else if index == imgDictArray.count - 1 {
if thumbPointXIndex >= imgDictArray[index].thumbPointXIndex {
bannerImg.image = imgDictArray[index].image
imgAnimation()
break
} else {
bannerImg.image = imgDictArray[index - 1 ].image
imgAnimation()
break
}
} else {
if imgDictArray[index - 1].thumbPointXIndex < thumbPointXIndex &&
thumbPointXIndex < imgDictArray[index].thumbPointXIndex {
bannerImg.image = imgDictArray[index - 1].image
imgAnimation()
break
}
}
}
}
func imgAnimation() {
let transition = CATransition()
transition.duration = 0.5
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
transition.type = kCATransitionFade
bannerImg.layer.add(transition, forKey: nil)
}
}
|
apache-2.0
|
d2f46e60cf6abd4fbaf3c3484d60a96a
| 30.786942 | 191 | 0.563135 | 4.777893 | false | false | false | false |
GirAppe/Blackhole
|
Blackhole/Classes/Core/Blackhole+Listeners.swift
|
1
|
4115
|
//
// BlackholeListeners.swift
// GolfKeeper
//
// Created by Andrzej Michnia on 21/08/16.
// Copyright © 2016 yeslogo. All rights reserved.
//
import Foundation
import WatchConnectivity
// MARK: - Listener protocol
/// Adopting listener protocol allows responding to incoming communication
public protocol Listener: class {
var time: Date { get }
weak var blackhole: Blackhole? { get set }
func deliver(_ object: Any?) -> Any?
}
// MARK: - Default count of timeout value
extension Listener {
/// Unimplemented
var timeoutValue: TimeInterval { return abs(self.time.timeIntervalSinceNow) }
}
// MARK: - Message listeners
/// Listens for message message
open class MessageListener: Listener {
// MARK: - Properties
open let time = Date()
var handler: (BlackholeMessage)->(BlackholeMessage?)
var autoremoved: Bool = false
weak open var blackhole: Blackhole?
public init(handler: @escaping (BlackholeMessage)->(BlackholeMessage?)) {
self.handler = handler
}
open func deliver(_ object: Any?) -> Any? {
if self.autoremoved {
self.blackhole?.removeListener(self)
}
guard let message = object as? BlackholeMessage else {
return nil
}
return self.handler(message)
}
}
// MARK: - Data listeners
/// Listens for data message
open class DataListener: Listener {
// MARK: - Properties
open let time = Date()
var handler: (Data)->(Data?)
var autoremoved: Bool = false
weak open var blackhole: Blackhole?
// MARK: - Lifecycle
public init(handler: @escaping (Data)->(Data?)) {
self.handler = handler
}
// MARK: - Public
open func deliver(_ object: Any?) -> Any? {
if self.autoremoved {
self.blackhole?.removeListener(self)
}
guard let data = object as? Data else {
// TODO: Handle!
return nil
}
return self.handler(data)
}
}
// MARK: - Object listeners
/// Listens for specified object message
open class ObjectListener<T:BlackholeDataMappable>: Listener {
// MARK: - Properties
open let time = Date()
var handler: ((T)->(BlackholeDataConvertible?))?
private var voidHandler: ((T)->(Void))?
var autoremoved: Bool = false
weak open var blackhole: Blackhole?
// MARK: - Lifecycle
public init<R:BlackholeDataConvertible>(type: T.Type, responseType: R.Type, handler: @escaping (T)->(R?)) {
self.handler = handler
}
public init(type: T.Type, handler: @escaping (T)->()) {
self.voidHandler = handler
}
// MARK: - Public
open func deliver(_ object: Any?) -> Any? {
if self.autoremoved {
self.blackhole?.removeListener(self)
}
guard let data = object as? Data else {
return nil
}
guard let object = T(data: data) else {
return nil
}
if let handler = self.handler {
return handler(object)
}
else {
self.voidHandler?(object)
return nil
}
}
}
// MARK: - Object responders
/// Returns object for given message request
open class MessageObjectResponder<R:BlackholeDataConvertible>: Listener {
// MARK: - Properties
open let time = Date()
var handler: (BlackholeMessage)->(R?)
var autoremoved: Bool = false
weak open var blackhole: Blackhole?
public init(handler: @escaping (BlackholeMessage)->(R?)) {
self.handler = handler
}
open func deliver(_ object: Any?) -> Any? {
if self.autoremoved {
self.blackhole?.removeListener(self)
}
if let data = object as? Data, let message = Dictionary<String,Any>(data: data) {
return self.handler(message)
}
else if let message = object as? BlackholeMessage {
return self.handler(message)
}
else {
return nil
}
}
}
|
mit
|
212308d181eb91e81a70cc19c75e551e
| 24.874214 | 111 | 0.587506 | 4.423656 | false | false | false | false |
PekanMmd/Pokemon-XD-Code
|
GoDToolOSX/Views/GoDBattleTrainerView.swift
|
1
|
2670
|
//
// GoDBattleTrainerView.swift
// GoD Tool
//
// Created by Stars Momodu on 12/09/2020.
//
import Cocoa
class GoDBattleTrainerView: NSView {
var trainerImageView = NSImageView()
var pokemonImageViews = [NSImageView]()
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
setUpSubViews()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setUpSubViews()
}
func setupForTrainer(_ trainer: XGTrainer) {
let trainerImage = trainer.trainerModel.image
trainerImageView.image = trainerImage
for i in 0 ..< 6 {
pokemonImageViews[i].image = nil
pokemonImageViews[i].addBorder(colour: GoDDesign.colourBlack(), width: 1)
if (i < trainer.pokemon.count) {
let mon = trainer.pokemon[i]
pokemonImageViews[i].image = mon.data.species.face
if mon.isShadow {
pokemonImageViews[i].addBorder(colour: GoDDesign.colourPurple(), width: 1)
}
}
}
}
private func setUpSubViews() {
translatesAutoresizingMaskIntoConstraints = false
layer?.borderWidth = 1
layer?.cornerRadius = 10
setBackgroundColour(GoDDesign.colourLightGrey())
for _ in 0 ..< 6 {
let pokemonView = NSImageView()
pokemonView.translatesAutoresizingMaskIntoConstraints = false
pokemonView.pinHeight(as: 30)
pokemonView.pinWidth(as: 30)
pokemonView.layer?.cornerRadius = 15
pokemonView.layer?.borderWidth = 2
pokemonView.setBackgroundColour(GoDDesign.colourDarkGrey())
pokemonImageViews.append(pokemonView)
addSubview(pokemonView)
}
trainerImageView.pinHeight(as: 50)
trainerImageView.pinWidth(as: 50)
trainerImageView.layer?.cornerRadius = 25
trainerImageView.layer?.borderWidth = 2
trainerImageView.translatesAutoresizingMaskIntoConstraints = false
addSubview(trainerImageView)
layoutSubviews()
}
private func layoutSubviews() {
trainerImageView.pinTop(to: self, padding: 10)
pokemonImageViews[1].pinTopToBottom(of: trainerImageView, padding: 10)
pokemonImageViews[4].pinTopToBottom(of: pokemonImageViews[1], padding: 10)
pokemonImageViews[4].pinBottom(to: self, padding: 10)
trainerImageView.pinCenterX(to: self)
pokemonImageViews[1].pinCenterX(to: self)
pokemonImageViews[4].pinCenterX(to: self)
for i in [0,2] {
pokemonImageViews[i].pinLeading(to: self, padding: 10)
pokemonImageViews[i + 1].pinLeadingToTrailing(of: pokemonImageViews[i], padding: 10)
pokemonImageViews[i + 2].pinLeadingToTrailing(of: pokemonImageViews[i + 1], padding: 10)
pokemonImageViews[i + 2].pinTrailing(to: self, padding: 10)
pokemonImageViews[i].pinCenterY(to: pokemonImageViews[i + 1])
pokemonImageViews[i + 2].pinCenterY(to: pokemonImageViews[i + 1])
}
}
}
|
gpl-2.0
|
af3a69b42a909e987763a74c68d33752
| 30.046512 | 91 | 0.741573 | 3.427471 | false | false | false | false |
CoderST/XMLYDemo
|
XMLYDemo/XMLYDemo/Class/Tools/NetWorkTools.swift
|
1
|
834
|
//
// NetWorkTools.swift
// XMLYDemo
//
// Created by xiudou on 2016/12/21.
// Copyright © 2016年 CoderST. All rights reserved.
//
import UIKit
import Alamofire
enum MethodType {
case get
case post
}
class NetWorkTools {
static let shareInstance : NetWorkTools = NetWorkTools()
func requestData(_ type : MethodType, URLString : String, parameters:[String : Any]? = nil,finishCallBack : @escaping (_ result : Any) -> ()){
// 确定请求类型
let method = type == .get ? HTTPMethod.get : HTTPMethod.post
Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in
guard let result = response.result.value else { return }
finishCallBack(result: result)
}
}
}
|
mit
|
34a8383f1880f2eb624437a0e940c016
| 24.59375 | 146 | 0.610501 | 4.627119 | false | false | false | false |
kiwitechnologies/ServiceClientiOS
|
ServiceClient/ServiceClient/TSGServiceClient/External/AFNetworking/Manager.swift
|
1
|
39772
|
//
// Manager.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/**
Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`.
*/
public class Manager {
// MARK: - Properties
/**
A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly
for any ad hoc requests.
*/
public static let sharedInstance: Manager = {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
return Manager(configuration: configuration)
}()
/**
Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers.
*/
public static let defaultHTTPHeaders: [String: String] = {
// Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3
let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5"
// Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5
let acceptLanguage = NSLocale.preferredLanguages().prefix(6).enumerate().map { index, languageCode in
let quality = 1.0 - (Double(index) * 0.1)
return "\(languageCode);q=\(quality)"
}.joinWithSeparator(", ")
// User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3
// Example: `iOS Example/1.0 (com.alamofire.iOS-Example; build:1; iOS 9.3.0) Alamofire/3.4.2`
let userAgent: String = {
if let info = NSBundle.mainBundle().infoDictionary {
let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown"
let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown"
let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown"
let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown"
let osNameVersion: String = {
let versionString: String
if #available(OSX 10.10, *) {
let version = NSProcessInfo.processInfo().operatingSystemVersion
versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
} else {
versionString = "10.9"
}
let osName: String = {
#if os(iOS)
return "iOS"
#elseif os(watchOS)
return "watchOS"
#elseif os(tvOS)
return "tvOS"
#elseif os(OSX)
return "OS X"
#elseif os(Linux)
return "Linux"
#else
return "Unknown"
#endif
}()
return "\(osName) \(versionString)"
}()
let alamofireVersion: String = {
guard
let afInfo = NSBundle(forClass: Manager.self).infoDictionary,
build = afInfo["CFBundleShortVersionString"]
else { return "Unknown" }
return "Alamofire/\(build)"
}()
return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)"
}
return "Alamofire"
}()
return [
"Accept-Encoding": acceptEncoding,
"Accept-Language": acceptLanguage,
"User-Agent": userAgent
]
}()
let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)
/// The underlying session.
public let session: NSURLSession
/// The session delegate handling all the task and session delegate callbacks.
public let delegate: SessionDelegate
/// Whether to start requests immediately after being constructed. `true` by default.
public var startRequestsImmediately: Bool = true
/**
The background completion handler closure provided by the UIApplicationDelegate
`application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background
completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation
will automatically call the handler.
If you need to handle your own events before the handler is called, then you need to override the
SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished.
`nil` by default.
*/
public var backgroundCompletionHandler: (() -> Void)?
// MARK: - Lifecycle
/**
Initializes the `Manager` instance with the specified configuration, delegate and server trust policy.
- parameter configuration: The configuration used to construct the managed session.
`NSURLSessionConfiguration.defaultSessionConfiguration()` by default.
- parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by
default.
- parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
challenges. `nil` by default.
- returns: The new `Manager` instance.
*/
public init(
configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate: SessionDelegate = SessionDelegate(),
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
self.delegate = delegate
self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
/**
Initializes the `Manager` instance with the specified session, delegate and server trust policy.
- parameter session: The URL session.
- parameter delegate: The delegate of the URL session. Must equal the URL session's delegate.
- parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
challenges. `nil` by default.
- returns: The new `Manager` instance if the URL session's delegate matches the delegate parameter.
*/
public init?(
session: NSURLSession,
delegate: SessionDelegate,
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
guard delegate === session.delegate else { return nil }
self.delegate = delegate
self.session = session
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
private func commonInit(serverTrustPolicyManager serverTrustPolicyManager: ServerTrustPolicyManager?) {
session.serverTrustPolicyManager = serverTrustPolicyManager
delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in
guard let strongSelf = self else { return }
dispatch_async(dispatch_get_main_queue()) { strongSelf.backgroundCompletionHandler?() }
}
}
deinit {
session.invalidateAndCancel()
}
// MARK: - Request
/**
Creates a request for the specified method, URL string, parameters, parameter encoding and headers.
- parameter method: The HTTP method.
- parameter URLString: The URL string.
- parameter parameters: The parameters. `nil` by default.
- parameter encoding: The parameter encoding. `.URL` by default.
- parameter headers: The HTTP headers. `nil` by default.
- returns: The created request.
*/
public func request(
method: Method,
_ URLString: URLStringConvertible,
parameters: [String: AnyObject]? = nil,
queryParameters: [String: String]? = nil,
encoding: ParameterEncoding = .URL,
cachePolicy:NSURLRequestCachePolicy?=nil,
headers: [String: String]? = nil)
-> Request
{
let mutableURLRequest = URLRequest(method, URLString, queryParameter: queryParameters,cachePolicies:cachePolicy, headers: headers)
if TSGHelper.sharedInstance.enableLog {
print("Complete Request \(mutableURLRequest)")
}
let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0
return request(encodedURLRequest)
}
/**
Creates a request for the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter URLRequest: The URL request
- returns: The created request.
*/
public func request(URLRequest: URLRequestConvertible) -> Request {
var dataTask: NSURLSessionDataTask!
dispatch_sync(queue) { dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest) }
let request = Request(session: session, task: dataTask)
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
// MARK: - SessionDelegate
/**
Responsible for handling all delegate callbacks for the underlying session.
*/
public class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
private var subdelegates: [Int: Request.TaskDelegate] = [:]
private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
/// Access the task delegate for the specified task in a thread-safe manner.
public subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
get {
var subdelegate: Request.TaskDelegate?
dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] }
return subdelegate
}
set {
dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue }
}
}
/**
Initializes the `SessionDelegate` instance.
- returns: The new `SessionDelegate` instance.
*/
public override init() {
super.init()
}
// MARK: - NSURLSessionDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didBecomeInvalidWithError:`.
public var sessionDidBecomeInvalidWithError: ((NSURLSession, NSError?) -> Void)?
/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`.
public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
/// Overrides all behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:` and requires the caller to call the `completionHandler`.
public var sessionDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`.
public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)?
// MARK: Delegate Methods
/**
Tells the delegate that the session has been invalidated.
- parameter session: The session object that was invalidated.
- parameter error: The error that caused invalidation, or nil if the invalidation was explicit.
*/
public func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
sessionDidBecomeInvalidWithError?(session, error)
}
/**
Requests credentials from the delegate in response to a session-level authentication request from the remote server.
- parameter session: The session containing the task that requested authentication.
- parameter challenge: An object that contains the request for authentication.
- parameter completionHandler: A handler that your delegate method must call providing the disposition and credential.
*/
public func URLSession(
session: NSURLSession,
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
{
guard sessionDidReceiveChallengeWithCompletion == nil else {
sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler)
return
}
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
if let sessionDidReceiveChallenge = sessionDidReceiveChallenge {
(disposition, credential) = sessionDidReceiveChallenge(session, challenge)
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let host = challenge.protectionSpace.host
if let
serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host),
serverTrust = challenge.protectionSpace.serverTrust
{
if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) {
disposition = .UseCredential
credential = NSURLCredential(forTrust: serverTrust)
} else {
disposition = .CancelAuthenticationChallenge
}
}
}
completionHandler(disposition, credential)
}
/**
Tells the delegate that all messages enqueued for a session have been delivered.
- parameter session: The session that no longer has any outstanding requests.
*/
public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
sessionDidFinishEventsForBackgroundURLSession?(session)
}
// MARK: - NSURLSessionTaskDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`.
public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:` and
/// requires the caller to call the `completionHandler`.
public var taskWillPerformHTTPRedirectionWithCompletion: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest, NSURLRequest? -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`.
public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:` and
/// requires the caller to call the `completionHandler`.
public var taskDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`.
public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)?
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:` and
/// requires the caller to call the `completionHandler`.
public var taskNeedNewBodyStreamWithCompletion: ((NSURLSession, NSURLSessionTask, NSInputStream? -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didCompleteWithError:`.
public var taskDidComplete: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)?
// MARK: Delegate Methods
/**
Tells the delegate that the remote server requested an HTTP redirect.
- parameter session: The session containing the task whose request resulted in a redirect.
- parameter task: The task whose request resulted in a redirect.
- parameter response: An object containing the server’s response to the original request.
- parameter request: A URL request object filled out with the new location.
- parameter completionHandler: A closure that your handler should call with either the value of the request
parameter, a modified URL request object, or NULL to refuse the redirect and
return the body of the redirect response.
*/
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
willPerformHTTPRedirection response: NSHTTPURLResponse,
newRequest request: NSURLRequest,
completionHandler: NSURLRequest? -> Void)
{
guard taskWillPerformHTTPRedirectionWithCompletion == nil else {
taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler)
return
}
var redirectRequest: NSURLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
}
completionHandler(redirectRequest)
}
/**
Requests credentials from the delegate in response to an authentication request from the remote server.
- parameter session: The session containing the task whose request requires authentication.
- parameter task: The task whose request requires authentication.
- parameter challenge: An object that contains the request for authentication.
- parameter completionHandler: A handler that your delegate method must call providing the disposition and credential.
*/
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)
{
guard taskDidReceiveChallengeWithCompletion == nil else {
taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler)
return
}
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
let result = taskDidReceiveChallenge(session, task, challenge)
completionHandler(result.0, result.1)
} else if let delegate = self[task] {
delegate.URLSession(
session,
task: task,
didReceiveChallenge: challenge,
completionHandler: completionHandler
)
} else {
URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler)
}
}
/**
Tells the delegate when a task requires a new request body stream to send to the remote server.
- parameter session: The session containing the task that needs a new body stream.
- parameter task: The task that needs a new body stream.
- parameter completionHandler: A completion handler that your delegate method should call with the new body stream.
*/
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
needNewBodyStream completionHandler: NSInputStream? -> Void)
{
guard taskNeedNewBodyStreamWithCompletion == nil else {
taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler)
return
}
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
completionHandler(taskNeedNewBodyStream(session, task))
} else if let delegate = self[task] {
delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
}
}
/**
Periodically informs the delegate of the progress of sending body content to the server.
- parameter session: The session containing the data task.
- parameter task: The data task.
- parameter bytesSent: The number of bytes sent since the last time this delegate method was called.
- parameter totalBytesSent: The total number of bytes sent so far.
- parameter totalBytesExpectedToSend: The expected length of the body data.
*/
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64)
{
if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else if let delegate = self[task] as? Request.UploadTaskDelegate {
delegate.URLSession(
session,
task: task,
didSendBodyData: bytesSent,
totalBytesSent: totalBytesSent,
totalBytesExpectedToSend: totalBytesExpectedToSend
)
}
}
/**
Tells the delegate that the task finished transferring data.
- parameter session: The session containing the task whose request finished transferring data.
- parameter task: The task whose request finished transferring data.
- parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil.
*/
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if let taskDidComplete = taskDidComplete {
taskDidComplete(session, task, error)
} else if let delegate = self[task] {
delegate.URLSession(session, task: task, didCompleteWithError: error)
}
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidComplete, object: task)
self[task] = nil
}
// MARK: - NSURLSessionDataDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
/// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:` and
/// requires caller to call the `completionHandler`.
public var dataTaskDidReceiveResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSURLResponse, NSURLSessionResponseDisposition -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`.
public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveData:`.
public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`.
public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)?
/// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:` and
/// requires caller to call the `completionHandler`.
public var dataTaskWillCacheResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse, NSCachedURLResponse? -> Void) -> Void)?
// MARK: Delegate Methods
/**
Tells the delegate that the data task received the initial reply (headers) from the server.
- parameter session: The session containing the data task that received an initial reply.
- parameter dataTask: The data task that received an initial reply.
- parameter response: A URL response object populated with headers.
- parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a
constant to indicate whether the transfer should continue as a data task or
should become a download task.
*/
public func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
didReceiveResponse response: NSURLResponse,
completionHandler: NSURLSessionResponseDisposition -> Void)
{
guard dataTaskDidReceiveResponseWithCompletion == nil else {
dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler)
return
}
var disposition: NSURLSessionResponseDisposition = .Allow
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
}
completionHandler(disposition)
}
/**
Tells the delegate that the data task was changed to a download task.
- parameter session: The session containing the task that was replaced by a download task.
- parameter dataTask: The data task that was replaced by a download task.
- parameter downloadTask: The new download task that replaced the data task.
*/
public func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask)
{
if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask {
dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask)
} else {
let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask)
self[downloadTask] = downloadDelegate
}
}
/**
Tells the delegate that the data task has received some of the expected data.
- parameter session: The session containing the data task that provided data.
- parameter dataTask: The data task that provided data.
- parameter data: A data object containing the transferred data.
*/
public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
}
}
/**
Asks the delegate whether the data (or upload) task should store the response in the cache.
- parameter session: The session containing the data (or upload) task.
- parameter dataTask: The data (or upload) task.
- parameter proposedResponse: The default caching behavior. This behavior is determined based on the current
caching policy and the values of certain received headers, such as the Pragma
and Cache-Control headers.
- parameter completionHandler: A block that your handler must call, providing either the original proposed
response, a modified version of that response, or NULL to prevent caching the
response. If your delegate implements this method, it must call this completion
handler; otherwise, your app leaks memory.
*/
public func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
willCacheResponse proposedResponse: NSCachedURLResponse,
completionHandler: NSCachedURLResponse? -> Void)
{
guard dataTaskWillCacheResponseWithCompletion == nil else {
dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler)
return
}
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse))
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
delegate.URLSession(
session,
dataTask: dataTask,
willCacheResponse: proposedResponse,
completionHandler: completionHandler
)
} else {
completionHandler(proposedResponse)
}
}
// MARK: - NSURLSessionDownloadDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didFinishDownloadingToURL:`.
public var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> Void)?
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`.
public var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`.
public var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)?
// MARK: Delegate Methods
/**
Tells the delegate that a download task has finished downloading.
- parameter session: The session containing the download task that finished.
- parameter downloadTask: The download task that finished.
- parameter location: A file URL for the temporary file. Because the file is temporary, you must either
open the file for reading or move it to a permanent location in your app’s sandbox
container directory before returning from this delegate method.
*/
public func URLSession(
session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didFinishDownloadingToURL location: NSURL)
{
if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL {
downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location)
}
}
/**
Periodically informs the delegate about the download’s progress.
- parameter session: The session containing the download task.
- parameter downloadTask: The download task.
- parameter bytesWritten: The number of bytes transferred since the last time this delegate
method was called.
- parameter totalBytesWritten: The total number of bytes transferred so far.
- parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length
header. If this header was not provided, the value is
`NSURLSessionTransferSizeUnknown`.
*/
public func URLSession(
session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64)
{
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(
session,
downloadTask: downloadTask,
didWriteData: bytesWritten,
totalBytesWritten: totalBytesWritten,
totalBytesExpectedToWrite: totalBytesExpectedToWrite
)
}
}
/**
Tells the delegate that the download task has resumed downloading.
- parameter session: The session containing the download task that finished.
- parameter downloadTask: The download task that resumed. See explanation in the discussion.
- parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the
existing content, then this value is zero. Otherwise, this value is an
integer representing the number of bytes on disk that do not need to be
retrieved again.
- parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header.
If this header was not provided, the value is NSURLSessionTransferSizeUnknown.
*/
public func URLSession(
session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64)
{
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(
session,
downloadTask: downloadTask,
didResumeAtOffset: fileOffset,
expectedTotalBytes: expectedTotalBytes
)
}
}
// MARK: - NSURLSessionStreamDelegate
var _streamTaskReadClosed: Any?
var _streamTaskWriteClosed: Any?
var _streamTaskBetterRouteDiscovered: Any?
var _streamTaskDidBecomeInputStream: Any?
// MARK: - NSObject
public override func respondsToSelector(selector: Selector) -> Bool {
#if !os(OSX)
if selector == #selector(NSURLSessionDelegate.URLSessionDidFinishEventsForBackgroundURLSession(_:)) {
return sessionDidFinishEventsForBackgroundURLSession != nil
}
#endif
switch selector {
case #selector(NSURLSessionDelegate.URLSession(_:didBecomeInvalidWithError:)):
return sessionDidBecomeInvalidWithError != nil
case #selector(NSURLSessionDelegate.URLSession(_:didReceiveChallenge:completionHandler:)):
return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil)
case #selector(NSURLSessionTaskDelegate.URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)):
return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil)
case #selector(NSURLSessionDataDelegate.URLSession(_:dataTask:didReceiveResponse:completionHandler:)):
return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil)
default:
return self.dynamicType.instancesRespondToSelector(selector)
}
}
}
}
|
mit
|
3d47806819739ba20c251e7ee9883bf6
| 48.645443 | 197 | 0.64193 | 6.743429 | false | false | false | false |
peteratseneca/dps923winter2015
|
Week_10/Places/Classes/PlaceList.swift
|
1
|
2983
|
//
// PlaceList.swift
// Scroll
//
// Created by Peter McIntyre on 2015-04-11.
// Copyright (c) 2015 School of ICT, Seneca College. All rights reserved.
//
import UIKit
import CoreData
// Notice the protocol conformance
class PlaceList: UITableViewController, NSFetchedResultsControllerDelegate {
// MARK: - Private properties
var frc: NSFetchedResultsController!
// MARK: - Properties
// Passed in by the app delegate during app initialization
var model: Model!
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Places List"
// Configure and load the fetched results controller (frc)
frc = model.frc_place
// This controller will be the frc delegate
frc.delegate = self;
// No predicate (which means the results will NOT be filtered)
frc.fetchRequest.predicate = nil;
// Create an error object
var error: NSError? = nil
// Perform fetch, and if there's an error, log it
if !frc.performFetch(&error) { println(error?.description) }
}
// MARK: - Table view methods
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.frc.sections?.count ?? 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = self.frc.sections![section] as! NSFetchedResultsSectionInfo
return sectionInfo.numberOfObjects
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
self.configureCell(cell, atIndexPath: indexPath)
return cell
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let item: AnyObject = frc.objectAtIndexPath(indexPath)
cell.textLabel!.text = item.valueForKey("address")! as? String
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "toPlaceDetail" {
// Get a reference to the destination view controller
let vc = segue.destinationViewController as! PlaceDetail
// From the data source (the fetched results controller)...
// Get a reference to the object for the tapped/selected table view row
let item = frc.objectAtIndexPath(self.tableView.indexPathForSelectedRow()!) as! Place
// Pass on the object
vc.item = item
// Configure the view if you wish
vc.title = item.address
}
}
}
|
mit
|
eff928bcf8041e4417ea5fdaad0cacb6
| 30.4 | 118 | 0.620181 | 5.483456 | false | false | false | false |
oliverschaefer/ResearchKit
|
ResearchKit/Common/ORKStepNavigationRule.swift
|
5
|
3056
|
/*
Copyright (c) 2015, Ricardo Sánchez-Sáez.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
public extension ORKPredicateStepNavigationRule {
#if swift(>=3.0)
convenience init(resultPredicatesAndDestinationStepIdentifiers tuples: [ (resultPredicate: Predicate, destinationStepIdentifier: String) ], defaultStepIdentifierOrNil: String? = nil ) {
var resultPredicates: [Predicate] = []
var destinationStepIdentifiers: [String] = []
for tuple in tuples {
resultPredicates.append(tuple.resultPredicate)
destinationStepIdentifiers.append(tuple.destinationStepIdentifier)
}
self.init(resultPredicates: resultPredicates, destinationStepIdentifiers: destinationStepIdentifiers, defaultStepIdentifier: defaultStepIdentifierOrNil, validateArrays: true);
}
#else
convenience init(resultPredicatesAndDestinationStepIdentifiers tuples: [ (resultPredicate: NSPredicate, destinationStepIdentifier: String) ], defaultStepIdentifierOrNil: String? = nil ) {
var resultPredicates: [NSPredicate] = []
var destinationStepIdentifiers: [String] = []
for tuple in tuples {
resultPredicates.append(tuple.resultPredicate)
destinationStepIdentifiers.append(tuple.destinationStepIdentifier)
}
self.init(resultPredicates: resultPredicates, destinationStepIdentifiers: destinationStepIdentifiers, defaultStepIdentifier: defaultStepIdentifierOrNil, validateArrays: true);
}
#endif
}
|
bsd-3-clause
|
3c5dbd600f35ef4dca2f5afdb7532f24
| 49.9 | 191 | 0.776359 | 5.132773 | false | false | false | false |
tensorflow/tensorflow-pywrap_saved_model
|
tensorflow/lite/swift/Tests/SignatureRunnerTest.swift
|
11
|
5949
|
// Copyright 2022 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 XCTest
@testable import TensorFlowLite
class SignatureRunnerTest: XCTestCase {
func testSignatureKeys() throws {
let interpreter = try Interpreter(modelPath: MultiSignaturesModel.path)
XCTAssertEqual(interpreter.signatureKeys, MultiSignaturesModel.signatureKeys)
XCTAssertNotNil(try interpreter.signatureRunner(with: MultiSignaturesModel.AddSignature.key))
XCTAssertThrowsError(try interpreter.signatureRunner(with: "dummy")) { error in
self.assertEqualErrors(
actual: error, expected: .failedToCreateSignatureRunner(signatureKey: "dummy"))
}
}
func testResizeInputTensor() throws {
let interpreter = try Interpreter(modelPath: MultiSignaturesModel.path)
let addRunner = try interpreter.signatureRunner(with: MultiSignaturesModel.AddSignature.key)
XCTAssertEqual(addRunner.inputs, MultiSignaturesModel.AddSignature.inputs)
let inputTensor = try addRunner.input(named: "x")
// Validate signature "add" input tensor "x" before resizing.
XCTAssertEqual(inputTensor.name, MultiSignaturesModel.AddSignature.inputTensor.name)
XCTAssertEqual(inputTensor.dataType, MultiSignaturesModel.AddSignature.inputTensor.dataType)
XCTAssertEqual(inputTensor.shape, [1])
// Test fail to copy data before resizing the tensor
XCTAssertThrowsError(
try addRunner.copy(MultiSignaturesModel.AddSignature.inputData, toInputNamed: "x")
) { error in
self.assertEqualErrors(
actual: error, expected: .invalidTensorDataCount(provided: 8, required: 4))
}
// Resize signature "add" input tensor "x"
try addRunner.resizeInput(named: "x", toShape: MultiSignaturesModel.AddSignature.shape)
try addRunner.allocateTensors()
// Copy data to input tensor "x"
try addRunner.copy(MultiSignaturesModel.AddSignature.inputData, toInputNamed: "x")
// Validate signature "add" input tensor "x" after resizing and copying data.
XCTAssertEqual(
try addRunner.input(named: "x"), MultiSignaturesModel.AddSignature.inputTensor)
}
func testResizeInputTensor_invalidTensor() throws {
let interpreter = try Interpreter(modelPath: MultiSignaturesModel.path)
let addRunner = try interpreter.signatureRunner(with: MultiSignaturesModel.AddSignature.key)
// Test fail to get input tensor for a dummy input name.
XCTAssertThrowsError(
try addRunner.input(named: "dummy")
) { error in
self.assertEqualErrors(
actual: error, expected: .failedToGetTensor(tensorType: "input", nameInSignature: "dummy"))
}
// Test fail to resize dummy input tensor
XCTAssertThrowsError(
try addRunner.resizeInput(named: "dummy", toShape: [2])
) { error in
self.assertEqualErrors(
actual: error, expected: .failedToResizeInputTensor(inputName: "dummy"))
}
}
func testInvokeWithInputs() throws {
let interpreter = try Interpreter(modelPath: MultiSignaturesModel.path)
let addRunner = try interpreter.signatureRunner(with: MultiSignaturesModel.AddSignature.key)
XCTAssertEqual(addRunner.outputs, MultiSignaturesModel.AddSignature.outputs)
// Validate signature "add" output tensor "output_0" before inference
let outputTensor = try addRunner.output(named: "output_0")
XCTAssertEqual(outputTensor.name, MultiSignaturesModel.AddSignature.outputTensor.name)
XCTAssertEqual(outputTensor.dataType, MultiSignaturesModel.AddSignature.outputTensor.dataType)
XCTAssertEqual(outputTensor.shape, [1])
// Resize signature "add" input tensor "x"
try addRunner.resizeInput(named: "x", toShape: MultiSignaturesModel.AddSignature.shape)
// Invoke signature "add" with inputs.
try addRunner.invoke(with: ["x": MultiSignaturesModel.AddSignature.inputData])
// Validate signature "add" output tensor "output_0" after inference
XCTAssertEqual(
try addRunner.output(named: "output_0"), MultiSignaturesModel.AddSignature.outputTensor)
}
// MARK: - Private
private func assertEqualErrors(actual: Error, expected: SignatureRunnerError) {
guard let actual = actual as? SignatureRunnerError else {
XCTFail("Actual error should be of type SignatureRunnerError.")
return
}
XCTAssertEqual(actual, expected)
}
}
// MARK: - Constants
/// Values for the `multi_signatures.bin` model.
enum MultiSignaturesModel {
static let info = (name: "multi_signatures", extension: "bin")
static let signatureKeys = [AddSignature.key, SubSignature.key]
static var path: String = {
let bundle = Bundle(for: SignatureRunnerTest.self)
guard let path = bundle.path(forResource: info.name, ofType: info.extension) else { return "" }
return path
}()
enum AddSignature {
static let key = "add"
static let inputs = ["x"]
static let outputs = ["output_0"]
static let inputData = Data(copyingBufferOf: [Float32(2.0), Float32(4.0)])
static let outputData = Data(copyingBufferOf: [Float32(4.0), Float32(6.0)])
static let shape: Tensor.Shape = [2]
static let inputTensor = Tensor(
name: "add_x:0",
dataType: .float32,
shape: shape,
data: inputData
)
static let outputTensor = Tensor(
name: "StatefulPartitionedCall:0",
dataType: .float32,
shape: shape,
data: outputData
)
}
enum SubSignature {
static let key = "sub"
}
}
|
apache-2.0
|
70a6a8446f34c8bbf4175c19e6700685
| 41.191489 | 99 | 0.732896 | 4.198306 | false | true | false | false |
fahlout/OptionsMenu
|
OptionsMenuDemo/OptionsMenuDemo/SmallOptionsMenuViewController.swift
|
1
|
2665
|
//
// SmallOptionsMenuViewController.swift
// OptionsMenuDemo
//
// Created by Niklas Fahl on 9/2/15.
// Copyright © 2015 CAPS. All rights reserved.
//
import UIKit
class SmallOptionsMenuViewController: UIViewController {
var optionsMenu: CAPSOptionsMenu?
@IBOutlet weak var durationSegmentedControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "Small Options Menu"
addOptionsMenu()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func addOptionsMenu() {
optionsMenu = CAPSOptionsMenu(viewController: self, barButtonSystemItem: UIBarButtonSystemItem.Organize, keepBarButtonAtEdge: true)
optionsMenu?.menuActionButtonsHighlightedColor(UIColor(red: 242.0/255.0, green: 242.0/255.0, blue: 242.0/255.0, alpha: 1.0))
optionsMenu?.menuCornerRadius(2.0)
let menuAction1: CAPSOptionsMenuAction = CAPSOptionsMenuAction(title: "Action Title 1") { (action: CAPSOptionsMenuAction) -> Void in
print("Tapped Action Button 1")
}
optionsMenu?.addAction(menuAction1)
let menuAction2: CAPSOptionsMenuAction = CAPSOptionsMenuAction(title: "Action Title 2") { (action: CAPSOptionsMenuAction) -> Void in
print("Tapped Action Button 2")
}
optionsMenu?.addAction(menuAction2)
let menuAction3: CAPSOptionsMenuAction = CAPSOptionsMenuAction(title: "Action Title 3") { (action: CAPSOptionsMenuAction) -> Void in
print("Tapped Action Button 3")
}
optionsMenu?.addAction(menuAction3)
}
@IBAction func animationSegmentedControlChangedValue(sender: UISegmentedControl) {
if sender.selectedSegmentIndex == 0 {
durationSegmentedControl.hidden = false
optionsMenu?.menuAnimationOption(AnimationOption.Expand)
} else if sender.selectedSegmentIndex == 1 {
durationSegmentedControl.hidden = false
optionsMenu?.menuAnimationOption(AnimationOption.Fade)
} else {
durationSegmentedControl.hidden = true
optionsMenu?.menuAnimationOption(AnimationOption.None)
}
}
@IBAction func animationDurationSegmentedControlChangedValue(sender: UISegmentedControl) {
if sender.selectedSegmentIndex == 0 {
optionsMenu?.menuAnimationDuration(0.2)
} else {
optionsMenu?.menuAnimationDuration(0.0)
}
}
}
|
bsd-3-clause
|
f51a7eba1ca251c3b6fadfc752e178a8
| 36 | 140 | 0.671547 | 4.906077 | false | false | false | false |
ScottRobbins/RxCocoaTouch
|
Pod/Classes/UITextView+Rx.swift
|
1
|
3514
|
import RxSwift
extension UITextView {
// MARK: - Configuring the Text Attributes
public var rx_attributedText: ObserverOf<NSAttributedString?> {
return observerOfWithPropertySetter { [weak self] (attributedText: NSAttributedString?) in
self?.attributedText = attributedText
}
}
public var rx_font: ObserverOf<UIFont?> {
return observerOfWithPropertySetter { [weak self] (font: UIFont?) in
self?.font = font
}
}
public var rx_textColor: ObserverOf<UIColor> {
return observerOfWithPropertySetter { [weak self] (textColor: UIColor) in
self?.textColor = textColor
}
}
public var rx_editable: ObserverOf<Bool> {
return observerOfWithPropertySetter { [weak self] (editable: Bool) in
self?.editable = editable
}
}
public var rx_allowsEditingTextAttributes: ObserverOf<Bool> {
return observerOfWithPropertySetter { [weak self] (allowsEditingTextAttributes: Bool) in
self?.allowsEditingTextAttributes = allowsEditingTextAttributes
}
}
public var rx_dataDetectorTypes: ObserverOf<UIDataDetectorTypes> {
return observerOfWithPropertySetter { [weak self] (dataDetectorTypes: UIDataDetectorTypes) in
self?.dataDetectorTypes = dataDetectorTypes
}
}
public var rx_textAlignment: ObserverOf<NSTextAlignment> {
return observerOfWithPropertySetter { [weak self] (textAlignment: NSTextAlignment) in
self?.textAlignment = textAlignment
}
}
public var rx_typingAttributes: ObserverOf<[String : AnyObject]> {
return observerOfWithPropertySetter { [weak self] (typingAttributes: [String : AnyObject]) in
self?.typingAttributes = typingAttributes
}
}
public var rx_linkTextAttributes: ObserverOf<[String : AnyObject]> {
return observerOfWithPropertySetter { [weak self] (linkTextAttributes: [String : AnyObject]) in
self?.linkTextAttributes = linkTextAttributes
}
}
public var rx_textContainerInset: ObserverOf<UIEdgeInsets> {
return observerOfWithPropertySetter { [weak self] (textContainerInset: UIEdgeInsets) in
self?.textContainerInset = textContainerInset
}
}
// MARK: - Working with the Selection
public var rx_selectedRange: ObserverOf<NSRange> {
return observerOfWithPropertySetter { [weak self] (textContainerInset: NSRange) in
self?.selectedRange = selectedRange
}
}
public var rx_clearsOnInsertion: ObserverOf<Bool> {
return observerOfWithPropertySetter { [weak self] (clearsOnInsertion: Bool) in
self?.clearsOnInsertion = clearsOnInsertion
}
}
public var rx_selectable: ObserverOf<Bool> {
return observerOfWithPropertySetter { [weak self] (selectable: Bool) in
self?.selectable = selectable
}
}
// MARK: - Replacing the System Input Views
public var rx_inputView: ObserverOf<UIView?> {
return observerOfWithPropertySetter { [weak self] (inputView: UIView?) in
self?.inputView = inputView
}
}
public var rx_inputAccessoryView: ObserverOf<UIView?> {
return observerOfWithPropertySetter { [weak self] (inputAccessoryView: UIView?) in
self?.inputAccessoryView = inputAccessoryView
}
}
}
|
mit
|
1e677c3b8a22cd09d001a725e48f3db3
| 34.14 | 103 | 0.651964 | 5.490625 | false | false | false | false |
coach-plus/ios
|
Pods/RxSwift/RxSwift/Deprecated.swift
|
6
|
29742
|
//
// Deprecated.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/5/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
import Foundation
extension Observable {
/**
Converts a optional to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- parameter optional: Optional element in the resulting observable sequence.
- returns: An observable sequence containing the wrapped value or not from given optional.
*/
@available(*, deprecated, message: "Implicit conversions from any type to optional type are allowed and that is causing issues with `from` operator overloading.", renamed: "from(optional:)")
public static func from(_ optional: Element?) -> Observable<Element> {
return Observable.from(optional: optional)
}
/**
Converts a optional to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- parameter optional: Optional element in the resulting observable sequence.
- parameter scheduler: Scheduler to send the optional element on.
- returns: An observable sequence containing the wrapped value or not from given optional.
*/
@available(*, deprecated, message: "Implicit conversions from any type to optional type are allowed and that is causing issues with `from` operator overloading.", renamed: "from(optional:scheduler:)")
public static func from(_ optional: Element?, scheduler: ImmediateSchedulerType) -> Observable<Element> {
return Observable.from(optional: optional, scheduler: scheduler)
}
}
extension ObservableType {
/**
Projects each element of an observable sequence into a new form by incorporating the element's index.
- seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html)
- parameter selector: A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
- returns: An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
@available(*, deprecated, message: "Please use enumerated().map()")
public func mapWithIndex<Result>(_ selector: @escaping (Element, Int) throws -> Result)
-> Observable<Result> {
return self.enumerated().map { try selector($0.element, $0.index) }
}
/**
Projects each element of an observable sequence to an observable sequence by incorporating the element's index and merges the resulting observable sequences into one observable sequence.
- seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html)
- parameter selector: A transform function to apply to each element; the second parameter of the function represents the index of the source element.
- returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.
*/
@available(*, deprecated, message: "Please use enumerated().flatMap()")
public func flatMapWithIndex<Source: ObservableConvertibleType>(_ selector: @escaping (Element, Int) throws -> Source)
-> Observable<Source.Element> {
return self.enumerated().flatMap { try selector($0.element, $0.index) }
}
/**
Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
The element's index is used in the logic of the predicate function.
- seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html)
- parameter predicate: A function to test each element for a condition; the second parameter of the function represents the index of the source element.
- returns: An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
@available(*, deprecated, message: "Please use enumerated().skipWhile().map()")
public func skipWhileWithIndex(_ predicate: @escaping (Element, Int) throws -> Bool) -> Observable<Element> {
return self.enumerated().skipWhile { try predicate($0.element, $0.index) }.map { $0.element }
}
/**
Returns elements from an observable sequence as long as a specified condition is true.
The element's index is used in the logic of the predicate function.
- seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html)
- parameter predicate: A function to test each element for a condition; the second parameter of the function represents the index of the source element.
- returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
@available(*, deprecated, message: "Please use enumerated().takeWhile().map()")
public func takeWhileWithIndex(_ predicate: @escaping (Element, Int) throws -> Bool) -> Observable<Element> {
return self.enumerated().takeWhile { try predicate($0.element, $0.index) }.map { $0.element }
}
}
extension Disposable {
/// Deprecated in favor of `disposed(by:)`
///
///
/// Adds `self` to `bag`.
///
/// - parameter bag: `DisposeBag` to add `self` to.
@available(*, deprecated, message: "use disposed(by:) instead", renamed: "disposed(by:)")
public func addDisposableTo(_ bag: DisposeBag) {
self.disposed(by: bag)
}
}
extension ObservableType {
/**
Returns an observable sequence that shares a single subscription to the underlying sequence, and immediately upon subscription replays latest element in buffer.
This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
- seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html)
- returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
@available(*, deprecated, message: "use share(replay: 1) instead", renamed: "share(replay:)")
public func shareReplayLatestWhileConnected()
-> Observable<Element> {
return self.share(replay: 1, scope: .whileConnected)
}
}
extension ObservableType {
/**
Returns an observable sequence that shares a single subscription to the underlying sequence, and immediately upon subscription replays maximum number of elements in buffer.
This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
- seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html)
- parameter bufferSize: Maximum element count of the replay buffer.
- returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
@available(*, deprecated, message: "Suggested replacement is `share(replay: 1)`. In case old 3.x behavior of `shareReplay` is required please use `share(replay: 1, scope: .forever)` instead.", renamed: "share(replay:)")
public func shareReplay(_ bufferSize: Int)
-> Observable<Element> {
return self.share(replay: bufferSize, scope: .forever)
}
}
/// Variable is a wrapper for `BehaviorSubject`.
///
/// Unlike `BehaviorSubject` it can't terminate with error, and when variable is deallocated
/// it will complete its observable sequence (`asObservable`).
///
/// **This concept will be deprecated from RxSwift but offical migration path hasn't been decided yet.**
/// https://github.com/ReactiveX/RxSwift/issues/1501
///
/// Current recommended replacement for this API is `RxCocoa.BehaviorRelay` because:
/// * `Variable` isn't a standard cross platform concept, hence it's out of place in RxSwift target.
/// * It doesn't have a counterpart for handling events (`PublishRelay`). It models state only.
/// * It doesn't have a consistent naming with *Relay or other Rx concepts.
/// * It has an inconsistent memory management model compared to other parts of RxSwift (completes on `deinit`).
///
/// Once plans are finalized, official availability attribute will be added in one of upcoming versions.
@available(*, deprecated, message: "Variable is deprecated. Please use `BehaviorRelay` as a replacement.")
public final class Variable<Element> {
private let _subject: BehaviorSubject<Element>
private var _lock = SpinLock()
// state
private var _value: Element
#if DEBUG
private let _synchronizationTracker = SynchronizationTracker()
#endif
/// Gets or sets current value of variable.
///
/// Whenever a new value is set, all the observers are notified of the change.
///
/// Even if the newly set value is same as the old value, observers are still notified for change.
public var value: Element {
get {
self._lock.lock(); defer { self._lock.unlock() }
return self._value
}
set(newValue) {
#if DEBUG
self._synchronizationTracker.register(synchronizationErrorMessage: .variable)
defer { self._synchronizationTracker.unregister() }
#endif
self._lock.lock()
self._value = newValue
self._lock.unlock()
self._subject.on(.next(newValue))
}
}
/// Initializes variable with initial value.
///
/// - parameter value: Initial variable value.
public init(_ value: Element) {
self._value = value
self._subject = BehaviorSubject(value: value)
}
/// - returns: Canonical interface for push style sequence
public func asObservable() -> Observable<Element> {
return self._subject
}
deinit {
self._subject.on(.completed)
}
}
extension ObservableType {
/**
Returns an observable sequence by the source observable sequence shifted forward in time by a specified delay. Error events from the source observable sequence are not delayed.
- seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html)
- parameter dueTime: Relative time shift of the source by.
- parameter scheduler: Scheduler to run the subscription delay timer on.
- returns: the source Observable shifted in time by the specified delay.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "delay(_:scheduler:)")
public func delay(_ dueTime: Foundation.TimeInterval, scheduler: SchedulerType)
-> Observable<Element> {
return self.delay(.milliseconds(Int(dueTime * 1000.0)), scheduler: scheduler)
}
}
extension ObservableType {
/**
Applies a timeout policy for each element in the observable sequence. If the next element isn't received within the specified timeout duration starting from its predecessor, a TimeoutError is propagated to the observer.
- seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html)
- parameter dueTime: Maximum duration between values before a timeout occurs.
- parameter scheduler: Scheduler to run the timeout timer on.
- returns: An observable sequence with a `RxError.timeout` in case of a timeout.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "timeout(_:scheduler:)")
public func timeout(_ dueTime: Foundation.TimeInterval, scheduler: SchedulerType)
-> Observable<Element> {
return timeout(.milliseconds(Int(dueTime * 1000.0)), scheduler: scheduler)
}
/**
Applies a timeout policy for each element in the observable sequence, using the specified scheduler to run timeout timers. If the next element isn't received within the specified timeout duration starting from its predecessor, the other observable sequence is used to produce future messages from that point on.
- seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html)
- parameter dueTime: Maximum duration between values before a timeout occurs.
- parameter other: Sequence to return in case of a timeout.
- parameter scheduler: Scheduler to run the timeout timer on.
- returns: The source sequence switching to the other sequence in case of a timeout.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "timeout(_:other:scheduler:)")
public func timeout<OtherSource: ObservableConvertibleType>(_ dueTime: Foundation.TimeInterval, other: OtherSource, scheduler: SchedulerType)
-> Observable<Element> where Element == OtherSource.Element {
return timeout(.milliseconds(Int(dueTime * 1000.0)), other: other, scheduler: scheduler)
}
}
extension ObservableType {
/**
Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
- seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html)
- parameter duration: Duration for skipping elements from the start of the sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "skip(_:scheduler:)")
public func skip(_ duration: Foundation.TimeInterval, scheduler: SchedulerType)
-> Observable<Element> {
return skip(.milliseconds(Int(duration * 1000.0)), scheduler: scheduler)
}
}
extension ObservableType where Element : RxAbstractInteger {
/**
Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages.
- seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html)
- parameter period: Period for producing the values in the resulting sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence that produces a value after each period.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "interval(_:scheduler:)")
public static func interval(_ period: Foundation.TimeInterval, scheduler: SchedulerType)
-> Observable<Element> {
return interval(.milliseconds(Int(period * 1000.0)), scheduler: scheduler)
}
}
extension ObservableType where Element: RxAbstractInteger {
/**
Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers.
- seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html)
- parameter dueTime: Relative time at which to produce the first value.
- parameter period: Period to produce subsequent values.
- parameter scheduler: Scheduler to run timers on.
- returns: An observable sequence that produces a value after due time has elapsed and then each period.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "timer(_:period:scheduler:)")
public static func timer(_ dueTime: Foundation.TimeInterval, period: Foundation.TimeInterval? = nil, scheduler: SchedulerType)
-> Observable<Element> {
return timer(.milliseconds(Int(dueTime * 1000.0)), period: period.map { .milliseconds(Int($0 * 1000.0)) }, scheduler: scheduler)
}
}
extension ObservableType {
/**
Returns an Observable that emits the first and the latest item emitted by the source Observable during sequential time windows of a specified duration.
This operator makes sure that no two elements are emitted in less then dueTime.
- seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html)
- parameter dueTime: Throttling duration for each element.
- parameter latest: Should latest element received in a dueTime wide time window since last element emission be emitted.
- parameter scheduler: Scheduler to run the throttle timers on.
- returns: The throttled sequence.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "throttle(_:latest:scheduler:)")
public func throttle(_ dueTime: Foundation.TimeInterval, latest: Bool = true, scheduler: SchedulerType)
-> Observable<Element> {
return throttle(.milliseconds(Int(dueTime * 1000.0)), latest: latest, scheduler: scheduler)
}
}
extension ObservableType {
/**
Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
- seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html)
- parameter duration: Duration for taking elements from the start of the sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence with the elements taken during the specified duration from the start of the source sequence.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "take(_:scheduler:)")
public func take(_ duration: Foundation.TimeInterval, scheduler: SchedulerType)
-> Observable<Element> {
return take(.milliseconds(Int(duration * 1000.0)), scheduler: scheduler)
}
}
extension ObservableType {
/**
Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers.
- seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html)
- parameter dueTime: Relative time shift of the subscription.
- parameter scheduler: Scheduler to run the subscription delay timer on.
- returns: Time-shifted sequence.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "delaySubscription(_:scheduler:)")
public func delaySubscription(_ dueTime: Foundation.TimeInterval, scheduler: SchedulerType)
-> Observable<Element> {
return delaySubscription(.milliseconds(Int(dueTime * 1000.0)), scheduler: scheduler)
}
}
extension ObservableType {
/**
Projects each element of an observable sequence into a window that is completed when either it’s full or a given amount of time has elapsed.
- seealso: [window operator on reactivex.io](http://reactivex.io/documentation/operators/window.html)
- parameter timeSpan: Maximum time length of a window.
- parameter count: Maximum element count of a window.
- parameter scheduler: Scheduler to run windowing timers on.
- returns: An observable sequence of windows (instances of `Observable`).
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "window(_:)")
public func window(timeSpan: Foundation.TimeInterval, count: Int, scheduler: SchedulerType)
-> Observable<Observable<Element>> {
return window(timeSpan: .milliseconds(Int(timeSpan * 1000.0)), count: count, scheduler: scheduler)
}
}
extension PrimitiveSequence {
/**
Returns an observable sequence by the source observable sequence shifted forward in time by a specified delay. Error events from the source observable sequence are not delayed.
- seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html)
- parameter dueTime: Relative time shift of the source by.
- parameter scheduler: Scheduler to run the subscription delay timer on.
- returns: the source Observable shifted in time by the specified delay.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "delay(_:scheduler:)")
public func delay(_ dueTime: Foundation.TimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<Trait, Element> {
return delay(.milliseconds(Int(dueTime * 1000.0)), scheduler: scheduler)
}
/**
Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers.
- seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html)
- parameter dueTime: Relative time shift of the subscription.
- parameter scheduler: Scheduler to run the subscription delay timer on.
- returns: Time-shifted sequence.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "delaySubscription(_:scheduler:)")
public func delaySubscription(_ dueTime: Foundation.TimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<Trait, Element> {
return delaySubscription(.milliseconds(Int(dueTime * 1000.0)), scheduler: scheduler)
}
/**
Applies a timeout policy for each element in the observable sequence. If the next element isn't received within the specified timeout duration starting from its predecessor, a TimeoutError is propagated to the observer.
- seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html)
- parameter dueTime: Maximum duration between values before a timeout occurs.
- parameter scheduler: Scheduler to run the timeout timer on.
- returns: An observable sequence with a `RxError.timeout` in case of a timeout.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "timeout(_:scheduler:)")
public func timeout(_ dueTime: Foundation.TimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<Trait, Element> {
return timeout(.milliseconds(Int(dueTime * 1000.0)), scheduler: scheduler)
}
/**
Applies a timeout policy for each element in the observable sequence, using the specified scheduler to run timeout timers. If the next element isn't received within the specified timeout duration starting from its predecessor, the other observable sequence is used to produce future messages from that point on.
- seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html)
- parameter dueTime: Maximum duration between values before a timeout occurs.
- parameter other: Sequence to return in case of a timeout.
- parameter scheduler: Scheduler to run the timeout timer on.
- returns: The source sequence switching to the other sequence in case of a timeout.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "timeout(_:other:scheduler:)")
public func timeout(_ dueTime: Foundation.TimeInterval,
other: PrimitiveSequence<Trait, Element>,
scheduler: SchedulerType) -> PrimitiveSequence<Trait, Element> {
return timeout(.milliseconds(Int(dueTime * 1000.0)), other: other, scheduler: scheduler)
}
}
extension PrimitiveSequenceType where Trait == SingleTrait {
/**
Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- parameter onSubscribe: Action to invoke before subscribing to source observable sequence.
- parameter onSubscribed: Action to invoke after subscribing to source observable sequence.
- parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed.
- returns: The source sequence with the side-effecting behavior applied.
*/
@available(*, deprecated, renamed: "do(onSuccess:onError:onSubscribe:onSubscribed:onDispose:)")
public func `do`(onNext: ((Element) throws -> Void)?,
onError: ((Swift.Error) throws -> Void)? = nil,
onSubscribe: (() -> Void)? = nil,
onSubscribed: (() -> Void)? = nil,
onDispose: (() -> Void)? = nil)
-> Single<Element> {
return self.`do`(
onSuccess: onNext,
onError: onError,
onSubscribe: onSubscribe,
onSubscribed: onSubscribed,
onDispose: onDispose
)
}
}
extension ObservableType {
/**
Projects each element of an observable sequence into a buffer that's sent out when either it's full or a given amount of time has elapsed, using the specified scheduler to run timers.
A useful real-world analogy of this overload is the behavior of a ferry leaving the dock when all seats are taken, or at the scheduled time of departure, whichever event occurs first.
- seealso: [buffer operator on reactivex.io](http://reactivex.io/documentation/operators/buffer.html)
- parameter timeSpan: Maximum time length of a buffer.
- parameter count: Maximum element count of a buffer.
- parameter scheduler: Scheduler to run buffering timers on.
- returns: An observable sequence of buffers.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "buffer(timeSpan:count:scheduler:)")
public func buffer(timeSpan: Foundation.TimeInterval, count: Int, scheduler: SchedulerType)
-> Observable<[Element]> {
return buffer(timeSpan: .milliseconds(Int(timeSpan * 1000.0)), count: count, scheduler: scheduler)
}
}
extension PrimitiveSequenceType where Element: RxAbstractInteger
{
/**
Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers.
- seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html)
- parameter dueTime: Relative time at which to produce the first value.
- parameter scheduler: Scheduler to run timers on.
- returns: An observable sequence that produces a value after due time has elapsed and then each period.
*/
@available(*, deprecated, message: "Use DispatchTimeInterval overload instead.", renamed: "timer(_:scheduler:)")
public static func timer(_ dueTime: Foundation.TimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<Trait, Element> {
return timer(.milliseconds(Int(dueTime * 1000.0)), scheduler: scheduler)
}
}
extension Completable {
/**
Merges the completion of all Completables from a collection into a single Completable.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Collection of Completables to merge.
- returns: A Completable that merges the completion of all Completables.
*/
@available(*, deprecated, message: "Use Completable.zip instead.", renamed: "zip")
public static func merge<Collection: Swift.Collection>(_ sources: Collection) -> Completable
where Collection.Element == Completable {
return zip(sources)
}
/**
Merges the completion of all Completables from an array into a single Completable.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Array of observable sequences to merge.
- returns: A Completable that merges the completion of all Completables.
*/
@available(*, deprecated, message: "Use Completable.zip instead.", renamed: "zip")
public static func merge(_ sources: [Completable]) -> Completable {
return zip(sources)
}
/**
Merges the completion of all Completables into a single Completable.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Collection of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
@available(*, deprecated, message: "Use Completable.zip instead.", renamed: "zip")
public static func merge(_ sources: Completable...) -> Completable {
return zip(sources)
}
}
|
mit
|
66e8bf81c9e77cd620431cfd45a31194
| 50.185886 | 316 | 0.712633 | 5.064544 | false | false | false | false |
davidjinhan/ButtonMenuPopup
|
ButtonMenuPopup/ButtonViewModel.swift
|
1
|
2781
|
//
// ButtonViewModel.swift
// ButtonMenuPopup
//
// Created by HanJin on 2017. 3. 27..
// Copyright © 2017년 DavidJinHan. All rights reserved.
//
import Foundation
import RxSwift
class ButtonViewModel {
var buttonModels: Variable<[ButtonModel]>!
var enabledButtons: [ButtonModel] {
return buttonModels.value.filter { $0.isVisible.value }
}
private let disposeBag = DisposeBag()
let type: ButtonType
init(type: ButtonType) {
self.type = type
setupButtonModels()
}
private var buttonModelFromUserDefaultsHelper: [ButtonModel] {
let format = type == .fruit ? "icon_fruit_%@" : "icon_vegetable_%@"
let buttonColor = type == .fruit ? UIColor(red: 117 / 255, green: 118 / 255, blue: 179 / 255, alpha: 1.0) : UIColor(red: 86 / 255, green: 191 / 255, blue: 244 / 255, alpha: 1.0)
switch type {
case .fruit:
return UserDefaultsHelper.Fruits.buttonsSequence.map {
let visible = UserDefaultsHelper.Fruits.enabledButtons.contains($0)
return ButtonModel(image: String(format: format, $0), title: $0, color: buttonColor, type: type, isVisible: visible)
}
case .vegetable:
return UserDefaultsHelper.Vegetable.buttonsSequence.map {
let visible = UserDefaultsHelper.Vegetable.enabledButtons.contains($0)
return ButtonModel(image: String(format: format, $0), title: $0, color: buttonColor, type: type, isVisible: visible)
}
}
}
private func setupButtonModels() {
buttonModels = Variable(buttonModelFromUserDefaultsHelper)
}
func saveButtonSequence(fromSourceIndex sourceIndex: Int, destinationIndex: Int) {
var array = buttonModels.value
let source = array[sourceIndex]
array.remove(at: sourceIndex)
array.insert(source, at: destinationIndex)
buttonModels.value = array
}
func confirmCurrentButtonSettings() {
switch type {
case .fruit:
UserDefaultsHelper.Fruits.buttonsSequence = buttonModels.value.map { $0.buttonTitle }
UserDefaultsHelper.Fruits.enabledButtons = buttonModels.value.filter({ $0.isVisible.value }).map { $0.buttonTitle }
case .vegetable:
UserDefaultsHelper.Vegetable.buttonsSequence = buttonModels.value.map { $0.buttonTitle }
UserDefaultsHelper.Vegetable.enabledButtons = buttonModels.value.filter({ $0.isVisible.value }).map { $0.buttonTitle }
}
}
func cancelCurrentButtonSettings() {
if buttonModels.value != buttonModelFromUserDefaultsHelper {
buttonModels.value = buttonModelFromUserDefaultsHelper
}
}
}
|
mit
|
3dfabc94dd7506fc77e558494284332f
| 36.04 | 185 | 0.642549 | 4.402536 | false | false | false | false |
iscriptology/swamp
|
Swamp/Messages/RPC/Callee/InvocationSwampMessage.swift
|
2
|
1621
|
//
// InvocationSwampMessage.swift
// Pods
//
// Created by Yossi Abraham on 01/09/2016.
//
//
import Foundation
// [INVOCATION, requestId|number, registration|number, details|dict, args|array?, kwargs|dict?]
class InvocationSwampMessage: SwampMessage {
let requestId: Int
let registration: Int
let details: [String: AnyObject]
let args: [AnyObject]?
let kwargs: [String: AnyObject]?
init(requestId: Int, registration: Int, details: [String: AnyObject], args: [AnyObject]?=nil, kwargs: [String: AnyObject]?=nil) {
self.requestId = requestId
self.registration = registration
self.details = details
self.args = args
self.kwargs = kwargs
}
// MARK: SwampMessage protocol
required init(payload: [Any]) {
self.requestId = payload[0] as! Int
self.registration = payload[1] as! Int
self.details = payload[2] as! [String: AnyObject]
self.args = payload[safe: 3] as? [AnyObject]
self.kwargs = payload[safe: 4] as? [String: AnyObject]
}
func marshal() -> [Any] {
var marshalled: [Any] = [SwampMessages.invocation.rawValue, self.requestId, self.registration, self.details]
if let args = self.args {
marshalled.append(args)
if let kwargs = self.kwargs {
marshalled.append(kwargs)
}
} else {
if let kwargs = self.kwargs {
marshalled.append([])
marshalled.append(kwargs)
}
}
return marshalled
}
}
|
mit
|
8f834c4e348dc1c59058adb20f9cc79e
| 27.438596 | 133 | 0.582357 | 4.012376 | false | false | false | false |
Brandon-J-Campbell/codemash
|
AutoLayoutSession/demos/demo7/codemash/ScheduleCollectionViewController.swift
|
1
|
5555
|
//
// ScheduleCollectionViewController.swift
// codemash
//
// Created by Brandon Campbell on 12/30/16.
// Copyright © 2016 Brandon Campbell. All rights reserved.
//
import Foundation
import UIKit
class ScheduleeRow {
var header : String?
var items = Array<ScheduleeRow>()
var session : Session?
convenience init(withHeader: String, items: Array<ScheduleeRow>) {
self.init()
self.header = withHeader
self.items = items
}
convenience init(withSession: Session) {
self.init()
self.session = withSession
}
}
class ScheduleCollectionCell : UICollectionViewCell {
@IBOutlet var titleLabel : UILabel?
@IBOutlet var roomLabel: UILabel?
@IBOutlet var speakerImageView: UIImageView?
var session : Session?
static func cellIdentifier() -> String {
return "ScheduleCollectionCell"
}
static func cell(forCollectionView collectionView: UICollectionView, indexPath: IndexPath, session: Session) -> ScheduleCollectionCell {
let cell : ScheduleCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: ScheduleCollectionCell.cellIdentifier(), for: indexPath) as! ScheduleCollectionCell
cell.speakerImageView?.image = nil
cell.titleLabel?.text = session.title
cell.roomLabel?.text = session.rooms[0]
cell.session = session
if let url = URL.init(string: "https:" + (session.speakers[0].gravatarUrl)) {
URLSession.shared.dataTask(with: url) {
(data, response, error) in
guard let data = data, error == nil else { return }
print(response?.suggestedFilename ?? url.lastPathComponent)
print("Download Finished")
DispatchQueue.main.async() { () -> Void in
cell.speakerImageView?.image = UIImage(data: data)
}
}.resume()
}
return cell
}
}
class ScheduleCollectionHeaderView : UICollectionReusableView {
@IBOutlet var headerLabel : UILabel?
static func cellIdentifier() -> String {
return "ScheduleCollectionHeaderView"
}
}
class ScheduleCollectionViewController : UICollectionViewController {
var sections = Array<ScheduleTableRow>()
var sessions : Array<Session> = Array<Session>.init() {
didSet {
self.data = Dictionary<Date, Array<Session>>()
self.setupSections()
}
}
var data = Dictionary<Date, Array<Session>>()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showSession" {
let vc = segue.destination as! SessionViewController
let cell = sender as! ScheduleCollectionCell
vc.session = cell.session
}
}
func setupSections() {
let timeFormatter = DateFormatter.init()
timeFormatter.dateFormat = "EEEE h:mm:ssa"
for session in self.sessions {
if data[session.startTime] == nil {
data[session.startTime] = Array<Session>()
}
data[session.startTime]?.append(session)
}
var sections : Array<ScheduleTableRow> = []
for key in data.keys.sorted() {
var rows : Array<ScheduleTableRow> = []
for session in data[key]! {
rows.append(ScheduleTableRow.init(withSession: session))
}
let time = timeFormatter.string(from: key)
sections.append(ScheduleTableRow.init(withHeader: time, items: rows))
}
self.sections = sections
self.collectionView?.reloadData()
}
}
extension ScheduleCollectionViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return self.sections.count
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let section = self.sections[section]
return section.items.count
}
}
extension ScheduleCollectionViewController {
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let section = self.sections[indexPath.section]
let row = section.items[indexPath.row]
let cell = ScheduleCollectionCell.cell(forCollectionView: collectionView, indexPath: indexPath, session: row.session!)
return cell
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let section = self.sections[indexPath.section]
let headerView: ScheduleCollectionHeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ScheduleCollectionHeaderView.cellIdentifier(), for: indexPath) as! ScheduleCollectionHeaderView
headerView.headerLabel?.text = section.header
return headerView
}
}
extension ScheduleCollectionViewController : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
var width : CGFloat = collectionView.bounds.size.width
return CGSize.init(width: width, height: 100.0)
}
}
|
mit
|
d53799a9ddcb0c6fad7791ceffe452c2
| 34.832258 | 233 | 0.651782 | 5.350674 | false | false | false | false |
haugli/Bullitt
|
Pods/CryptoSwift/CryptoSwift/NSDataExtension.swift
|
3
|
2775
|
//
// PGPDataExtension.swift
// SwiftPGP
//
// Created by Marcin Krzyzanowski on 05/07/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
import Foundation
extension NSMutableData {
/** Convenient way to append bytes */
internal func appendBytes(arrayOfBytes: [UInt8]) {
self.appendBytes(arrayOfBytes, length: arrayOfBytes.count)
}
}
extension NSData {
public func checksum() -> UInt16 {
var s:UInt32 = 0;
var bytesArray = self.arrayOfBytes()
for (var i = 0; i < bytesArray.count; i++) {
var b = bytesArray[i]
s = s + UInt32(bytesArray[i])
}
s = s % 65536;
return UInt16(s);
}
public func md5() -> NSData? {
return Hash.md5(self).calculate()
}
public func sha1() -> NSData? {
return Hash.sha1(self).calculate()
}
public func sha224() -> NSData? {
return Hash.sha224(self).calculate()
}
public func sha256() -> NSData? {
return Hash.sha256(self).calculate()
}
public func sha384() -> NSData? {
return Hash.sha384(self).calculate()
}
public func sha512() -> NSData? {
return Hash.sha512(self).calculate()
}
public func crc32() -> NSData? {
return Hash.crc32(self).calculate()
}
public func encrypt(cipher: Cipher) -> NSData? {
if let encrypted = cipher.encrypt(self.arrayOfBytes()) {
return NSData.withBytes(encrypted)
}
return nil
}
public func decrypt(cipher: Cipher) -> NSData? {
if let decrypted = cipher.decrypt(self.arrayOfBytes()) {
return NSData.withBytes(decrypted)
}
return nil;
}
public func authenticate(authenticator: Authenticator) -> NSData? {
if let result = authenticator.authenticate(self.arrayOfBytes()) {
return NSData.withBytes(result)
}
return nil
}
}
extension NSData {
public func toHexString() -> String {
let count = self.length / sizeof(UInt8)
var bytesArray = [UInt8](count: count, repeatedValue: 0)
self.getBytes(&bytesArray, length:count * sizeof(UInt8))
var s:String = "";
for byte in bytesArray {
s = s + String(format:"%02x", byte)
}
return s
}
public func arrayOfBytes() -> [UInt8] {
let count = self.length / sizeof(UInt8)
var bytesArray = [UInt8](count: count, repeatedValue: 0)
self.getBytes(&bytesArray, length:count * sizeof(UInt8))
return bytesArray
}
class public func withBytes(bytes: [UInt8]) -> NSData {
return NSData(bytes: bytes, length: bytes.count)
}
}
|
mit
|
130cc6b45cea99f32b16a78f88907d3f
| 24.227273 | 73 | 0.575135 | 4.217325 | false | false | false | false |
raymondshadow/SwiftDemo
|
SwiftApp/SwiftApp/AnimationSummary/RayDynamicBehaviorViewController.swift
|
1
|
3633
|
//
// RayDynamicBehaviorViewController.swift
// SwiftApp
//
// Created by 邬勇鹏 on 2018/6/14.
// Copyright © 2018年 raymond. All rights reserved.
//
import UIKit
class RayDynamicBehaviorViewController: UIViewController {
fileprivate lazy var mator: UIDynamicAnimator = {
let temp = UIDynamicAnimator(referenceView: self.view)
// temp.delegate = self
return temp
}()
fileprivate lazy var subject: UIView = {
let temp = UIView(frame: CGRect(x: 150, y: 300, width: 100, height: 100))
temp.backgroundColor = .red
return temp
}()
override func viewDidLoad() {
super.viewDidLoad()
setupSubViews()
}
private func setupSubViews() {
let titles = ["重力", "碰撞", "吸附", "振动", "推"]
for index in 0..<5 {
let temp = UIButton().then { (btn) in
btn.setTitle(titles[index], for: .normal)
btn.backgroundColor = .green
btn.tag = index + 10
btn.addTarget(self, action: #selector(menuClickAction(btn:)), for: .touchUpInside)
btn.frame = CGRect(x: 15 + (60 + 10) * index, y: 64, width: 60, height: 25)
}
self.view.addSubview(temp)
}
self.view.addSubview(self.subject)
}
}
extension RayDynamicBehaviorViewController {
@objc fileprivate func menuClickAction(btn: UIButton) {
self.mator.removeAllBehaviors()
switch btn.tag - 10 {
case 0:
gravityBehavoir()
break
case 1:
gravityBehavoir()
collisionBehavior()
break
case 2:
pushBehavior()
collisionBehavior()
break
case 3:
gravityBehavoir()
break
default:
self.navigationController?.pushViewController(RayDynamicBehaviorSampleController(), animated: true)
break
}
}
}
extension RayDynamicBehaviorViewController: UIDynamicAnimatorDelegate {
fileprivate func gravityBehavoir() {
let gravity = UIGravityBehavior(items: [subject])
gravity.gravityDirection = CGVector(dx: 0, dy: 1)
gravity.magnitude = 2
self.mator.addBehavior(gravity)
}
fileprivate func collisionBehavior() {
let collision = UICollisionBehavior(items: [subject])
collision.translatesReferenceBoundsIntoBoundary = false
collision.setTranslatesReferenceBoundsIntoBoundary(with: UIEdgeInsets(top: subject.y, left: 0, bottom: 0, right: 0))
collision.collisionMode = .everything
// collision.collisionDelegate = self
self.mator.addBehavior(collision)
let behavior = UIDynamicItemBehavior(items: [subject])
behavior.elasticity = 0.6
behavior.friction = 3
// behavior.resistance = 3
behavior.allowsRotation = false
self.mator.addBehavior(behavior)
}
fileprivate func pushBehavior() {
let push = UIPushBehavior(items: [subject], mode: .continuous)
push.active = true
push.magnitude = 112
push.pushDirection = CGVector(dx: 0, dy: 1)
self.mator.addBehavior(push)
}
fileprivate func attachmentBehavior() {
// let attach = UIAttachmentBehavior(item: subject, attachedTo: <#T##UIDynamicItem#>)
}
fileprivate func snapBehavior() {
// let snap = UISnapBehavior(item: subject, snapTo: <#T##CGPoint#>)
}
}
|
apache-2.0
|
568c46f820fd921850f765537fb98f58
| 29.302521 | 124 | 0.5868 | 4.689207 | false | false | false | false |
ktmswzw/FeelClient
|
FeelingClient/MVC/VM/CenterMessageModel.swift
|
1
|
4596
|
//
// CenterMessageModel.swift
// FeelingClient
//
// Created by vincent on 10/3/16.
// Copyright © 2016 xecoder. All rights reserved.
//
import Foundation
import MapKit
public class MessageViewModel {
public let msgs: Messages = Messages.defaultMessages
var selfSendMsgs = [MessageBean]()
//id
var id: String = ""
//msgId
var msgId = ""
//问题
var question = ""
//答案
var answer = ""
//接受对象
var to: String = ""
//期限
var limitDate: String = ""
//内容
var content: String = ""
//图片地址
var photos: [String] = [""]
//视频地址
var video: String = ""
//音频地址
var sound: String = ""
//阅后即焚
var burnAfterReading: Bool = true
var annotationArray = [MyAnnotation]()
var latitude:Double = 0.0
var longitude:Double = 0.0
//发起人id
var fromId = ""
public weak var delegate: MessageViewModelDelegate?
var imageData = [UIImage]()
var imageDataThumbnail = [UIImage]()
private var index: Int = -1
var isNew: Bool {
return index == -1
}
var address = ""
// new initializer
public init(delegate: MessageViewModelDelegate) {
self.delegate = delegate
}
func sendMessage(se:AnyObject?) {
let msg = MessageBean()
msg.burnAfterReading = burnAfterReading
msg.to = to
msg.limitDate = limitDate
msg.video = video
msg.sound = sound
msg.content = content
msg.x = latitude
msg.y = longitude
msg.question = question
msg.answer = answer
msg.address = address
self.msgs.saveMsg(msg, imags: self.imageData) { (r:BaseApi.Result) -> Void in
switch (r) {
case .Success(let value):
print(value)
self.selfSendMsgs.append(msg)
se!.navigationController!!.view.hideToastActivity()
se!.view!!.makeToast("发表成功", duration: 2, position: .Center)
se!.navigationController?!.popViewControllerAnimated(true)
break;
case .Failure(let value):
print(value)
self.selfSendMsgs.append(msg)
se!.navigationController!!.view.hideToastActivity()
se!.view!!.makeToast("发表失败", duration: 2, position: .Center)
break;
}
}
}
func searchMessage(to:String, map: MKMapView, view: UIView) {
view.makeToastActivity(.Center)
msgs.searchMsg(to, x: "\(latitude)", y: "\(longitude)", page: 0, size: 100) { (r:BaseApi.Result) -> Void in
switch (r) {
case .Success(let r):
map.removeAnnotations(map.annotations)
if let msgs = r {
if(msgs.count==0){
view.makeToast("未找到你想要信件", duration: 2, position: .Center)
}
else{
for msg in r as! [MessageBean] {
let oneAnnotation = MyAnnotation()
oneAnnotation.original_coordinate = CLLocationCoordinate2DMake(msg.y, msg.x)
oneAnnotation.coordinate = CLLocationCoordinate2DMake(msg.y, msg.x).toMars()// 转换火星地图
oneAnnotation.title = "寄给:\(msg.to)"
oneAnnotation.question = "问题:\(msg.question)"
oneAnnotation.id = msg.id
oneAnnotation.url = msg.avatar
oneAnnotation.fromId = msg.fromId
self.annotationArray.append(oneAnnotation)
}
map.addAnnotations(self.annotationArray)
view.makeToast("共找到 \(msgs.count) 封未开启蜜信", duration: 2, position: .Center)
}
}
view.hideToastActivity();
break;
case .Failure(_):
view.hideToastActivity();
view.makeToast("搜索失败", duration: 2, position: .Center)
break;
}
}
}
}
public protocol MessageViewModelDelegate: class {
}
|
mit
|
0949348124ccedcf9bcff2f57efe7bae
| 29.278912 | 115 | 0.493597 | 4.8171 | false | false | false | false |
kfix/MacPin
|
Sources/MacPinOSX/StatusBarController.swift
|
1
|
2100
|
/// MacPin StatusBarController
///
/// Controls a textfield that displays a WebViewController's current hovered URL
import AppKit
import WebKitPrivates
@objc class StatusBarField: NSTextField { // FIXMEios UILabel + UITextField
override var stringValue: String {
didSet {
invalidateIntrinsicContentSize()
sizeToFit() // shrink field to match text, like Safari
isHidden = stringValue.isEmpty
}
}
}
@objc class StatusBarController: NSViewController {
let statusbox = StatusBarField()
@objc weak var hovered: _WKHitTestResult? = nil {
didSet {
if let hovered = hovered {
statusbox.stringValue = hovered.absoluteLinkURL.absoluteString
// Safari also seems to use SegmentedText to bold the scheme+host (origin)
} else {
statusbox.isHidden = true
}
}
}
required init?(coder: NSCoder) { super.init(coder: coder) }
override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) { super.init(nibName:nil, bundle:nil) } // calls loadView()
override func loadView() { view = statusbox } // NIBless
convenience init() {
self.init(nibName:nil, bundle:nil)
}
@objc override func viewDidLoad() {
super.viewDidLoad()
view.autoresizingMask = [.width]
statusbox.backgroundColor = NSColor.textBackgroundColor
statusbox.textColor = NSColor.labelColor
statusbox.toolTip = ""
if let cell = statusbox.cell as? NSTextFieldCell {
cell.placeholderString = ""
cell.isScrollable = false
cell.target = self
cell.usesSingleLineMode = true
cell.focusRingType = .none
cell.isEditable = false
cell.isSelectable = false
cell.backgroundStyle = .lowered
}
statusbox.isHidden = true
statusbox.maximumNumberOfLines = 1
statusbox.isBezeled = false
// "In order to prevent inconsistent rendering, background color rendering is disabled for rounded-bezel text fields."
/// seems that any .bezelStyle disables background color...
statusbox.isBordered = true // in case we have more issues with text colors, at least the box will be apparent
statusbox.drawsBackground = true
}
deinit { hovered = nil }
}
|
gpl-3.0
|
bd2328f7915911e8496901b15902a97f
| 28.166667 | 141 | 0.732381 | 3.98482 | false | false | false | false |
dfuerle/elondore-swift
|
elondore/GameBoard/GameViewController.swift
|
1
|
3739
|
//
// GameViewController.swift
// elondore
//
// Created by Dmitri Fuerle on 9/9/15.
// Copyright (c) 2015 Dmitri Fuerle. All rights reserved.
//
import SpriteKit
import UIKit
class GameViewController: UIViewController, GameSceneDelegate, LevelEndViewControllerDelegate {
let levelOverSegue = "levelOverSegue"
let levelEndViewControllerIdentifier = "levelEndViewController"
lazy var animator: UIDynamicAnimator = {
let animator = UIDynamicAnimator(referenceView: self.view)
return animator
}()
var snapBehavior: UISnapBehavior!
var game: Game? {
didSet {
guard let game = game else { return }
let scene = GameScene(game: game, size: CGSize(width: 375, height: 667))
scene.gameSceneDelegate = self
let skView = self.view as! SKView
skView.showsFPS = false
skView.showsNodeCount = false
skView.ignoresSiblingOrder = true
scene.scaleMode = .aspectFit
skView.presentScene(scene)
}
}
// MARK: - Overrides
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.offWhite()
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override var prefersStatusBarHidden: Bool {
return true
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender _: Any?) {
if segue.identifier == levelOverSegue {
let levelEndViewController = segue.destination as! LevelEndViewController
levelEndViewController.game = game
}
}
@IBAction func unwindFromLevelEndAction(_: UIStoryboardSegue) {}
// MARK: - GameSceneDelegate
func gameScene(_: GameScene, didFinishWithGame _: Game) {
let viewController = storyboard?.instantiateViewController(withIdentifier: levelEndViewControllerIdentifier) as! LevelEndViewController
viewController.game = game
viewController.delegate = self
addChild(viewController)
viewController.view.frame = CGRect(origin: CGPoint(x: view.center.x - 150, y: -400), size: CGSize(width: 300, height: 400))
view.addSubview(viewController.view)
viewController.didMove(toParent: self)
// Animate the entry
snapBehavior = UISnapBehavior(item: viewController.view, snapTo: view.center)
snapBehavior.damping = 0.5
animator.addBehavior(snapBehavior)
}
// MARK: - LevelEndViewControllerDelegate
func levelEndViewController(_ levelEndViewController: LevelEndViewController, didChooseOption option: LevelEndChoice) {
levelEndViewController.view.removeFromSuperview()
levelEndViewController.removeFromParent()
// Remove animation
if snapBehavior != nil {
animator.removeBehavior(snapBehavior)
}
switch option {
case .playAgain:
if let game = self.game {
self.game = game
}
case .nextLevel:
if let game = self.game {
if game.isRandomLevel() {
game.randomLevel()
} else {
game.nextLevel()
}
self.game = game
}
case .mainMenu:
if let game = self.game {
if game.success && game.hasNextLevel() {
game.nextLevel()
}
}
navigationController?.popToRootViewController(animated: true)
}
}
}
|
gpl-2.0
|
7cc2fc7ac219479cd4828ab727fe4eb9
| 30.158333 | 143 | 0.618347 | 5.229371 | false | false | false | false |
bugitapp/bugit
|
bugit/Extensions/xUIImage.swift
|
1
|
1763
|
//
// xUIImage.swift
// bugit
//
// Created by Ernest on 12/3/16.
// Copyright © 2016 BugIt App. All rights reserved.
//
import UIKit
extension UIImage {
// Usage: canvasImageView.image = canvasImageView.image?.pixellated(scale: 20)
func pixellated(scale: Int = 7) -> UIImage? {
guard let ciImage = UIKit.CIImage(image: self),
let filter = CIFilter(name: "CIPixellate") else {
return nil
}
filter.setValue(ciImage, forKey: "inputImage")
filter.setValue(scale, forKey: "inputScale")
let vector = CIVector(x: 120.0, y: 120.0)
filter.setValue(vector, forKey: "inputCenter")
guard let output = filter.outputImage else {
return nil
}
return UIImage(ciImage: output)
}
// Usage: x.crop(bounds: CGRect(x, y, w, h))
func crop(bounds: CGRect) -> UIImage? {
dlog("bounds: \(bounds)")
guard let cgImage = self.cgImage else {
return nil
}
guard let cgCroppedImage = cgImage.cropping(to: bounds) else {
return nil
}
let img = UIImage(cgImage: cgCroppedImage)
dlog("img: \(img)")
return img
}
func simpleScale(newSize: CGSize) -> UIImage? {
var scaledImage: UIImage? = nil
let hasAlpha = false
let scale: CGFloat = self.scale
UIGraphicsBeginImageContextWithOptions(newSize, !hasAlpha, scale)
self.draw(in: CGRect(origin: CGPoint.zero, size: newSize))
scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
}
|
apache-2.0
|
2a1087afdee4c3fd5e6d92d9f6d268c0
| 26.53125 | 82 | 0.566402 | 4.529563 | false | false | false | false |
anbo0123/ios5-weibo
|
microblog/microblog/Classes/Module/Main/View/ABMainTabBar.swift
|
1
|
2037
|
//
// ABMainTabBar.swift
// microblog
//
// Created by 安波 on 15/10/27.
// Copyright © 2015年 anbo. All rights reserved.
//
import UIKit
class ABMainTabBar: UITabBar {
// 确定tabBar的个数
private let count = 5
/// tabBar的布局
override func layoutSubviews() {
super.layoutSubviews()
// 计算width
let width = bounds.width / CGFloat(count)
// 设置frame
let frame = CGRect(x: 0, y: 0, width: width, height: bounds.height)
// 记录点击的索引下标
var index = 0
// 遍历tabBar,并判断设置frame
for view in subviews {
// 判断是否为某个类型
if view is UIControl && !(view is UIButton){
print("view: \(view)")
// 设置对应位置的frame值
view.frame = CGRectOffset(frame, width * CGFloat(index), 0)
// 改变索引下标的值
// index++
// if index == 2 {
// index++
// }
index += index == 1 ? 2 : 1
}
}
print("----------------")
// 设置撰写按钮的frame
composeButton.frame = CGRectOffset(frame, width * 2, 0)
}
// MARK: - 懒加载
lazy var composeButton: UIButton = {
//创建按钮
let button = UIButton()
//设置按钮图片
button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
//设置按钮背景
button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
//添加到父控件
self.addSubview(button)
//返回
return button
}()
}
|
apache-2.0
|
2b1622a327465b04f94da6d36085c7c0
| 28 | 124 | 0.540409 | 4.356808 | false | false | false | false |
jterhorst/TacoDemoiOS
|
TacoDemoIOS/AppDelegate.swift
|
1
|
3161
|
//
// AppDelegate.swift
// TacoDemoIOS
//
// Created by Jason Terhorst on 3/22/16.
// Copyright © 2016 Jason Terhorst. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
splitViewController.delegate = self
splitViewController.preferredDisplayMode = UISplitViewController.DisplayMode.primaryOverlay
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
TacosDAO.sharedInstance.saveContext()
}
// MARK: - Split view
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool {
return true
}
}
|
mit
|
535e92af8ad716faf0ae151ade07b171
| 49.967742 | 285 | 0.75981 | 6.076923 | false | false | false | false |
niunaruto/DeDaoAppSwift
|
testSwift/Pods/RxCocoa/RxCocoa/Traits/ControlEvent.swift
|
13
|
2513
|
//
// ControlEvent.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 8/28/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import RxSwift
/// A protocol that extends `ControlEvent`.
public protocol ControlEventType : ObservableType {
/// - returns: `ControlEvent` interface
func asControlEvent() -> ControlEvent<Element>
}
/**
A trait for `Observable`/`ObservableType` that represents an event on a UI element.
Properties:
- it never fails,
- it doesn’t send any initial value on subscription,
- it `Complete`s the sequence when the control deallocates,
- it never errors out, and
- it delivers events on `MainScheduler.instance`.
**The implementation of `ControlEvent` will ensure that sequence of events is being subscribed on main scheduler
(`subscribeOn(ConcurrentMainScheduler.instance)` behavior).**
**It is the implementor’s responsibility to make sure that all other properties enumerated above are satisfied.**
**If they aren’t, using this trait will communicate wrong properties, and could potentially break someone’s code.**
**If the `events` observable sequence passed into thr initializer doesn’t satisfy all enumerated
properties, don’t use this trait.**
*/
public struct ControlEvent<PropertyType> : ControlEventType {
public typealias Element = PropertyType
let _events: Observable<PropertyType>
/// Initializes control event with a observable sequence that represents events.
///
/// - parameter events: Observable sequence that represents events.
/// - returns: Control event created with a observable sequence of events.
public init<Ev: ObservableType>(events: Ev) where Ev.Element == Element {
self._events = events.subscribeOn(ConcurrentMainScheduler.instance)
}
/// Subscribes an observer to control events.
///
/// - parameter observer: Observer to subscribe to events.
/// - returns: Disposable object that can be used to unsubscribe the observer from receiving control events.
public func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
return self._events.subscribe(observer)
}
/// - returns: `Observable` interface.
public func asObservable() -> Observable<Element> {
return self._events
}
/// - returns: `ControlEvent` interface.
public func asControlEvent() -> ControlEvent<Element> {
return self
}
}
|
mit
|
659c4699f58d4960193750468540bbf2
| 35.231884 | 121 | 0.71 | 4.930966 | false | false | false | false |
rusty1s/RSContactGrid
|
RSContactGrid/RSContactGrid/Implementation/SquareTile.swift
|
1
|
3625
|
//
// SquareTile.swift
// RSContactGrid
//
// Created by Matthias Fey on 24.06.15.
// Copyright © 2015 Matthias Fey. All rights reserved.
//
private struct SquareTileData {
private static var width: CGFloat = 20
private static var height: CGFloat = 20
}
public struct SquareTile<T, S> : TileType {
// MARK: Associated typed
public typealias DataType = Data<T, S>
// MARK: Initializers
public init(x: Int, y: Int) {
self.x = x
self.y = y
self.data = DataType()
}
// MARK: Instance variables
public let x: Int
public let y: Int
public let data: DataType
// MARK: Static variables
/// The width of the tile. The width has a minimum value of 1.
/// The default value is 20.0.
public static var width: CGFloat {
set { SquareTileData.width = max(1, newValue) }
get { return SquareTileData.width }
}
/// The height of the tile. The height has a minimum value of 1.
/// The default value is 20.0.
public static var height: CGFloat {
set { SquareTileData.height = max(1, newValue) }
get { return SquareTileData.height }
}
}
// MARK: Instance variables
extension SquareTile {
public var frame: CGRect {
return CGRect(x: CGFloat(x)*SquareTile<T, S>.width,
y: CGFloat(y)*SquareTile<T, S>.height,
width: SquareTile<T, S>.width,
height: SquareTile<T, S>.height)
}
public var vertices: [CGPoint] {
let frame = self.frame
return [frame.origin,
CGPoint(x: frame.origin.x, y: frame.origin.y+frame.size.height),
CGPoint(x: frame.origin.x+frame.size.width, y: frame.origin.y+frame.size.height),
CGPoint(x: frame.origin.x+frame.size.width, y: frame.origin.y)]
}
}
// MARK: Instance functions
extension SquareTile {
public func intersectsRelativeLineSegment(point1 point1: RelativeRectPoint, point2: RelativeRectPoint) -> Bool {
return true
}
}
// MARK: Static functions
extension SquareTile {
public static func tilesInRect<T, S>(rect: CGRect) -> Set<SquareTile<T, S>> {
let startX = segmentXOfCoordinate(rect.origin.x)
let startY = segmentYOfCoordinate(rect.origin.y)
let endX = segmentXOfCoordinate(rect.origin.x+rect.size.width)
let endY = segmentYOfCoordinate(rect.origin.y+rect.size.height)
var elements = Set<SquareTile<T, S>>(minimumCapacity: (1+endX-startX)*(1+endY-startY))
for x in startX...endX {
for y in startY...endY {
elements.insert(SquareTile<T, S>(x: x, y: y))
}
}
return elements
}
private static func segmentXOfCoordinate(coordinate: CGFloat) -> Int {
return coordinate < 0 && fmod(coordinate, width) != 0 ? Int(coordinate/width)-1 : Int(coordinate/width)
}
private static func segmentYOfCoordinate(coordinate: CGFloat) -> Int {
return coordinate < 0 && fmod(coordinate, height) != 0 ? Int(coordinate/height)-1 : Int(coordinate/height)
}
}
// MARK: Comparable
extension SquareTile {}
public func == <T, S>(lhs: SquareTile<T, S>, rhs: SquareTile<T, S>) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
public func < <T, S>(lhs: SquareTile<T, S>, rhs: SquareTile<T, S>) -> Bool {
return lhs.y < rhs.y || (lhs.y == rhs.y && lhs.x < rhs.x)
}
// MARK: CustomDebugStringConvertible
extension SquareTile {
public var debugDescription: String { return "SquareTile(\(self)" }
}
|
mit
|
726fa4ca35d260c90ace93f4d4623019
| 27.093023 | 116 | 0.610927 | 3.739938 | false | false | false | false |
hooman/swift
|
benchmark/single-source/Differentiation.swift
|
3
|
1868
|
//===--- Differentiation.swift -------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 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
//
//===----------------------------------------------------------------------===//
#if canImport(_Differentiation)
import TestsUtils
import _Differentiation
public let Differentiation = [
BenchmarkInfo(
name: "DifferentiationIdentity",
runFunction: run_DifferentiationIdentity,
tags: [.regression, .differentiation]
),
BenchmarkInfo(
name: "DifferentiationSquare",
runFunction: run_DifferentiationSquare,
tags: [.regression, .differentiation]
),
BenchmarkInfo(
name: "DifferentiationArraySum",
runFunction: run_DifferentiationArraySum,
tags: [.regression, .differentiation],
setUpFunction: { blackHole(onesArray) }
),
]
@inline(never)
public func run_DifferentiationIdentity(N: Int) {
func f(_ x: Float) -> Float {
x
}
for _ in 0..<1000*N {
blackHole(valueWithGradient(at: 1, of: f))
}
}
@inline(never)
public func run_DifferentiationSquare(N: Int) {
func f(_ x: Float) -> Float {
x * x
}
for _ in 0..<1000*N {
blackHole(valueWithGradient(at: 1, of: f))
}
}
let onesArray: [Float] = Array(repeating: 1, count: 50)
@inline(never)
public func run_DifferentiationArraySum(N: Int) {
func sum(_ array: [Float]) -> Float {
var result: Float = 0
for i in withoutDerivative(at: 0..<array.count) {
result += array[i]
}
return result
}
for _ in 0..<N {
blackHole(valueWithGradient(at: onesArray, of: sum))
}
}
#endif
|
apache-2.0
|
4892f53751bf5a73655bb30cd78688ec
| 24.589041 | 80 | 0.631692 | 3.940928 | false | false | false | false |
thomasjcarey/BLSNavigationController
|
BLSKit/BLSNavigationController.swift
|
2
|
3277
|
//
// BLSNavigationController.swift
// BLSNavigationController
//
// Created by Thomas Carey on 12/1/15.
// Copyright © 2015 BLS. All rights reserved.
//
import WebKit
class BLSNavigationController: UINavigationController, UINavigationBarDelegate {
let progressView = UIProgressView(progressViewStyle: .Bar)
var webView: WKWebView? {
didSet {
if let _ = webView {
webView?.addObserver(self, forKeyPath: "estimatedProgress", options: .New, context: nil)
webView?.addObserver(self, forKeyPath: "title", options: .New, context: nil)
}
}
willSet {
if newValue == nil {
webView?.removeObserver(self, forKeyPath: "estimatedProgress")
webView?.removeObserver(self, forKeyPath: "title")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
configureView()
configureConstraints()
}
private func configureView() {
progressView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(progressView)
}
private func configureConstraints() {
NSLayoutConstraint(item: progressView, attribute: .Bottom, relatedBy: .Equal, toItem: navigationBar, attribute: .Bottom, multiplier: 1.0, constant: -0.5).active = true
NSLayoutConstraint(item: progressView, attribute: .Leading, relatedBy: .Equal, toItem: navigationBar, attribute: .Leading, multiplier: 1.0, constant: 0.0).active = true
NSLayoutConstraint(item: progressView, attribute: .Trailing, relatedBy: .Equal, toItem: navigationBar, attribute: .Trailing, multiplier: 1.0, constant: 0.0).active = true
}
func navigationBar(navigationBar: UINavigationBar, shouldPopItem item: UINavigationItem) -> Bool {
// See http://stackoverflow.com/questions/6413595/uinavigationcontroller-and-uinavigationbardelegate-shouldpopitem-with-monotouc/7453933#7453933
// for future reference in getting this to work
if let webView = topViewController?.view as? WKWebView {
if webView.canGoBack {
webView.goBack()
return false
} else {
self.webView = nil
popViewControllerAnimated(true)
}
} else {
webView = nil
popViewControllerAnimated(true)
}
return true
}
private func updateProgress(progress: Float) {
if progress == 1.0 {
finishNavigation()
} else {
progressView.setProgress(progress, animated: true)
}
}
private func finishNavigation() {
UIView.animateWithDuration(0.33, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: [], animations: { () -> Void in
self.progressView.setProgress(1.0, animated: true)
self.progressView.alpha = 0.0
}, completion: { finished in
self.progressView.setProgress(0.0, animated: false)
self.progressView.alpha = 1.0
})
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "estimatedProgress" {
if let webView = webView {
updateProgress(Float(webView.estimatedProgress))
}
} else if keyPath == "title" {
let newTitle = change?["new"] as? String
topViewController?.title = newTitle
}
}
}
|
mit
|
1f759e232d8a318058fa6b64e766f500
| 33.125 | 174 | 0.682234 | 4.556328 | false | false | false | false |
dreamsxin/swift
|
test/attr/attr_availability.swift
|
1
|
43480
|
// RUN: %target-parse-verify-swift
@available(*, unavailable)
func unavailable_func() {}
@available(*, unavailable, message: "message")
func unavailable_func_with_message() {}
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(iOS, unavailable)
@available(OSX, unavailable)
func unavailable_multiple_platforms() {}
@available // expected-error {{expected '(' in 'available' attribute}}
func noArgs() {}
@available(*) // expected-error {{expected ',' in 'available' attribute}}
func noKind() {}
@available(badPlatform, unavailable) // expected-warning {{unknown platform 'badPlatform' for attribute 'available'}}
func unavailable_bad_platform() {}
// Handle unknown platform.
@available(HAL9000, unavailable) // expected-warning {{unknown platform 'HAL9000'}}
func availabilityUnknownPlatform() {}
// <rdar://problem/17669805> Availability can't appear on a typealias
@available(*, unavailable, message: "oh no you don't")
typealias int = Int // expected-note {{'int' has been explicitly marked unavailable here}}
@available(*, unavailable, renamed: "Float")
typealias float = Float // expected-note {{'float' has been explicitly marked unavailable here}}
struct MyCollection<Element> {
@available(*, unavailable, renamed: "Element")
typealias T = Element // expected-note 2{{'T' has been explicitly marked unavailable here}}
func foo(x: T) { } // expected-error {{'T' has been renamed to 'Element'}} {{15-16=Element}}
}
extension MyCollection {
func append(element: T) { } // expected-error {{'T' has been renamed to 'Element'}} {{24-25=Element}}
}
@available(*, unavailable, renamed: "MyCollection")
typealias YourCollection<Element> = MyCollection<Element> // expected-note {{'YourCollection' has been explicitly marked unavailable here}}
var x : YourCollection<Int> // expected-error {{'YourCollection' has been renamed to 'MyCollection'}}{{9-23=MyCollection}}
var x : int // expected-error {{'int' is unavailable: oh no you don't}}
var y : float // expected-error {{'float' has been renamed to 'Float'}}{{9-14=Float}}
// Encoded message
@available(*, unavailable, message: "This message has a double quote \"")
func unavailableWithDoubleQuoteInMessage() {} // expected-note {{'unavailableWithDoubleQuoteInMessage()' has been explicitly marked unavailable here}}
func useWithEscapedMessage() {
unavailableWithDoubleQuoteInMessage() // expected-error {{'unavailableWithDoubleQuoteInMessage()' is unavailable: This message has a double quote \"}}
}
// More complicated parsing.
@available(OSX, message: "x", unavailable)
let _: Int
@available(OSX, introduced: 1, deprecated: 2.0, obsoleted: 3.0.0)
let _: Int
@available(OSX, introduced: 1.0.0, deprecated: 2.0, obsoleted: 3, unavailable, renamed: "x")
let _: Int
// Meaningless but accepted.
@available(OSX, message: "x")
let _: Int
// Parse errors.
@available() // expected-error{{expected platform name or '*' for 'available' attribute}}
let _: Int
@available(OSX,) // expected-error{{expected 'available' option such as 'unavailable', 'introduced', 'deprecated', 'obsoleted', 'message', or 'renamed'}}
let _: Int
@available(OSX, message) // expected-error{{expected ':' after 'message' in 'available' attribute}}
let _: Int
@available(OSX, message: ) // expected-error{{expected string literal in 'available' attribute}}
let _: Int
@available(OSX, message: x) // expected-error{{expected string literal in 'available' attribute}}
let _: Int
@available(OSX, unavailable:) // expected-error{{expected ')' in 'available' attribute}} expected-error{{expected declaration}}
let _: Int
@available(OSX, introduced) // expected-error{{expected ':' after 'introduced' in 'available' attribute}}
let _: Int
@available(OSX, introduced: ) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: x) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: 1.x) // expected-error{{expected ')' in 'available' attribute}} expected-error {{expected declaration}}
let _: Int
@available(OSX, introduced: 1.0.x) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: 0x1) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: 1.0e4) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: -1) // expected-error{{expected version number in 'available' attribute}} expected-error{{expected declaration}}
let _: Int
@available(OSX, introduced: 1.0.1e4) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: 1.0.0x4) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(*, renamed: "bad name") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, renamed: "_") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, renamed: "a+b") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, renamed: "a(") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, renamed: "a(:)") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, renamed: "a(:b:)") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, deprecated, unavailable, message: "message") // expected-error{{'available' attribute cannot be both unconditionally 'unavailable' and 'deprecated'}}
struct BadUnconditionalAvailability { };
// Encoding in messages
@available(*, deprecated, message: "Say \"Hi\"")
func deprecated_func_with_message() {}
// 'PANDA FACE' (U+1F43C)
@available(*, deprecated, message: "Pandas \u{1F43C} are cute")
struct DeprecatedTypeWithMessage { }
func use_deprecated_with_message() {
deprecated_func_with_message() // expected-warning{{'deprecated_func_with_message()' is deprecated: Say \"Hi\"}}
var _: DeprecatedTypeWithMessage // expected-warning{{'DeprecatedTypeWithMessage' is deprecated: Pandas \u{1F43C} are cute}}
}
@available(*, deprecated, message: "message")
func use_deprecated_func_with_message2() {
deprecated_func_with_message() // no diagnostic
}
@available(*, deprecated, renamed: "blarg")
func deprecated_func_with_renamed() {}
@available(*, deprecated, message: "blarg is your friend", renamed: "blarg")
func deprecated_func_with_message_renamed() {}
@available(*, deprecated, renamed: "wobble")
struct DeprecatedTypeWithRename { }
func use_deprecated_with_renamed() {
deprecated_func_with_renamed() // expected-warning{{'deprecated_func_with_renamed()' is deprecated: renamed to 'blarg'}}
// expected-note@-1{{use 'blarg'}}{{3-31=blarg}}
deprecated_func_with_message_renamed() //expected-warning{{'deprecated_func_with_message_renamed()' is deprecated: blarg is your friend}}
// expected-note@-1{{use 'blarg'}}{{3-39=blarg}}
var _: DeprecatedTypeWithRename // expected-warning{{'DeprecatedTypeWithRename' is deprecated: renamed to 'wobble'}}
// expected-note@-1{{use 'wobble'}}{{10-34=wobble}}
}
// Short form of @available()
@available(iOS 8.0, *)
func functionWithShortFormIOSAvailable() {}
@available(iOS 8, *)
func functionWithShortFormIOSVersionNoPointAvailable() {}
@available(iOS 8.0, OSX 10.10.3, *)
func functionWithShortFormIOSOSXAvailable() {}
@available(iOS 8.0 // expected-error {{must handle potential future platforms with '*'}} {{19-19=, *}}
func shortFormMissingParen() { // expected-error {{expected ')' in 'available' attribute}}
}
@available(iOS 8.0, // expected-error {{expected platform name}}
func shortFormMissingPlatform() {
}
@available(iOS 8.0, *
func shortFormMissingParenAfterWildcard() { // expected-error {{expected ')' in 'available' attribute}}
}
@available(*) // expected-error {{expected ',' in 'available' attribute}}
func onlyWildcardInAvailable() {}
@available(iOS 8.0, *, OSX 10.10.3)
func shortFormWithWildcardInMiddle() {}
@available(iOS 8.0, OSX 10.10.3) // expected-error {{must handle potential future platforms with '*'}} {{32-32=, *}}
func shortFormMissingWildcard() {}
@availability(OSX, introduced: 10.10) // expected-error {{@availability has been renamed to @available}} {{2-14=available}}
func someFuncUsingOldAttribute() { }
// <rdar://problem/23853709> Compiler crash on call to unavailable "print"
func OutputStreamTest(message: String, to: inout OutputStream) {
print(message, &to) // expected-error {{'print' is unavailable: Please use the 'to' label for the target stream: 'print((...), to: &...)'}}
}
// expected-note@+1{{'T' has been explicitly marked unavailable here}}
struct UnavailableGenericParam<@available(*, unavailable, message: "nope") T> {
func f(t: T) { } // expected-error{{'T' is unavailable: nope}}
}
struct DummyType {}
@available(*, unavailable, renamed: "&+")
func +(x: DummyType, y: DummyType) {} // expected-note {{here}}
@available(*, deprecated, renamed: "&-")
func -(x: DummyType, y: DummyType) {}
func testOperators(x: DummyType, y: DummyType) {
x + y // expected-error {{'+' has been renamed to '&+'}} {{5-6=&+}}
x - y // expected-warning {{'-' is deprecated: renamed to '&-'}} expected-note {{use '&-' instead}} {{5-6=&-}}
}
@available(*, unavailable, renamed: "DummyType.foo")
func unavailableMember() {} // expected-note {{here}}
@available(*, deprecated, renamed: "DummyType.bar")
func deprecatedMember() {}
@available(*, unavailable, renamed: "DummyType.Inner.foo")
func unavailableNestedMember() {} // expected-note {{here}}
@available(*, unavailable, renamed: "DummyType.Foo")
struct UnavailableType {} // expected-note {{here}}
@available(*, deprecated, renamed: "DummyType.Bar")
typealias DeprecatedType = Int
func testGlobalToMembers() {
unavailableMember() // expected-error {{'unavailableMember()' has been renamed to 'DummyType.foo'}} {{3-20=DummyType.foo}}
deprecatedMember() // expected-warning {{'deprecatedMember()' is deprecated: renamed to 'DummyType.bar'}} expected-note {{use 'DummyType.bar' instead}} {{3-19=DummyType.bar}}
unavailableNestedMember() // expected-error {{'unavailableNestedMember()' has been renamed to 'DummyType.Inner.foo'}} {{3-26=DummyType.Inner.foo}}
let x: UnavailableType? = nil // expected-error {{'UnavailableType' has been renamed to 'DummyType.Foo'}} {{10-25=DummyType.Foo}}
_ = x
let y: DeprecatedType? = nil // expected-warning {{'DeprecatedType' is deprecated: renamed to 'DummyType.Bar'}} expected-note {{use 'DummyType.Bar' instead}} {{10-24=DummyType.Bar}}
_ = y
}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableArgNames(a: Int) {} // expected-note {{here}}
@available(*, deprecated, renamed: "moreShinyLabeledArguments(example:)")
func deprecatedArgNames(b: Int) {}
@available(*, unavailable, renamed: "DummyType.shinyLabeledArguments(example:)")
func unavailableMemberArgNames(a: Int) {} // expected-note {{here}}
@available(*, deprecated, renamed: "DummyType.moreShinyLabeledArguments(example:)")
func deprecatedMemberArgNames(b: Int) {}
@available(*, unavailable, renamed: "DummyType.shinyLabeledArguments(example:)", message: "ha")
func unavailableMemberArgNamesMsg(a: Int) {} // expected-note {{here}}
@available(*, deprecated, renamed: "DummyType.moreShinyLabeledArguments(example:)", message: "ha")
func deprecatedMemberArgNamesMsg(b: Int) {}
@available(*, unavailable, renamed: "shinyLabeledArguments()")
func unavailableNoArgs() {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:)")
func unavailableSame(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableUnnamed(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:)")
func unavailableUnnamedSame(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:)")
func unavailableNewlyUnnamed(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(veryLongNameToOverflowASmallStringABCDEFGHIJKLMNOPQRSTUVWXYZ:)")
func unavailableVeryLongArgNames(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)")
func unavailableMultiSame(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:another:)")
func unavailableMultiUnnamed(_ a: Int, _ b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)")
func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)")
func unavailableMultiNewlyUnnamed(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.init(other:)")
func unavailableInit(a: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "Foo.Bar.init(other:)")
func unavailableNestedInit(a: Int) {} // expected-note 2 {{here}}
func testArgNames() {
unavailableArgNames(a: 0) // expected-error {{'unavailableArgNames(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{3-22=shinyLabeledArguments}} {{23-24=example}}
deprecatedArgNames(b: 1) // expected-warning {{'deprecatedArgNames(b:)' is deprecated: renamed to 'moreShinyLabeledArguments(example:)'}} expected-note {{use 'moreShinyLabeledArguments(example:)' instead}} {{3-21=moreShinyLabeledArguments}} {{22-23=example}}
unavailableMemberArgNames(a: 0) // expected-error {{'unavailableMemberArgNames(a:)' has been replaced by 'DummyType.shinyLabeledArguments(example:)'}} {{3-28=DummyType.shinyLabeledArguments}} {{29-30=example}}
deprecatedMemberArgNames(b: 1) // expected-warning {{'deprecatedMemberArgNames(b:)' is deprecated: replaced by 'DummyType.moreShinyLabeledArguments(example:)'}} expected-note {{use 'DummyType.moreShinyLabeledArguments(example:)' instead}} {{3-27=DummyType.moreShinyLabeledArguments}} {{28-29=example}}
unavailableMemberArgNamesMsg(a: 0) // expected-error {{'unavailableMemberArgNamesMsg(a:)' has been replaced by 'DummyType.shinyLabeledArguments(example:)': ha}} {{3-31=DummyType.shinyLabeledArguments}} {{32-33=example}}
deprecatedMemberArgNamesMsg(b: 1) // expected-warning {{'deprecatedMemberArgNamesMsg(b:)' is deprecated: ha}} expected-note {{use 'DummyType.moreShinyLabeledArguments(example:)' instead}} {{3-30=DummyType.moreShinyLabeledArguments}} {{31-32=example}}
unavailableNoArgs() // expected-error {{'unavailableNoArgs()' has been renamed to 'shinyLabeledArguments()'}} {{3-20=shinyLabeledArguments}}
unavailableSame(a: 0) // expected-error {{'unavailableSame(a:)' has been renamed to 'shinyLabeledArguments(a:)'}} {{3-18=shinyLabeledArguments}}
unavailableUnnamed(0) // expected-error {{'unavailableUnnamed' has been renamed to 'shinyLabeledArguments(example:)'}} {{3-21=shinyLabeledArguments}} {{22-22=example: }}
unavailableUnnamedSame(0) // expected-error {{'unavailableUnnamedSame' has been renamed to 'shinyLabeledArguments(_:)'}} {{3-25=shinyLabeledArguments}}
unavailableNewlyUnnamed(a: 0) // expected-error {{'unavailableNewlyUnnamed(a:)' has been renamed to 'shinyLabeledArguments(_:)'}} {{3-26=shinyLabeledArguments}} {{27-30=}}
unavailableVeryLongArgNames(a: 0) // expected-error {{'unavailableVeryLongArgNames(a:)' has been renamed to 'shinyLabeledArguments(veryLongNameToOverflowASmallStringABCDEFGHIJKLMNOPQRSTUVWXYZ:)'}} {{3-30=shinyLabeledArguments}} {{31-32=veryLongNameToOverflowASmallStringABCDEFGHIJKLMNOPQRSTUVWXYZ}}
unavailableMultiSame(a: 0, b: 1) // expected-error {{'unavailableMultiSame(a:b:)' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{3-23=shinyLabeledArguments}}
unavailableMultiUnnamed(0, 1) // expected-error {{'unavailableMultiUnnamed' has been renamed to 'shinyLabeledArguments(example:another:)'}} {{3-26=shinyLabeledArguments}} {{27-27=example: }} {{30-30=another: }}
unavailableMultiUnnamedSame(0, 1) // expected-error {{'unavailableMultiUnnamedSame' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{3-30=shinyLabeledArguments}}
unavailableMultiNewlyUnnamed(a: 0, b: 1) // expected-error {{'unavailableMultiNewlyUnnamed(a:b:)' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{3-31=shinyLabeledArguments}} {{32-35=}} {{38-41=}}
unavailableInit(a: 0) // expected-error {{'unavailableInit(a:)' has been replaced by 'Int.init(other:)'}} {{3-18=Int}} {{19-20=other}}
let fn = unavailableInit // expected-error {{'unavailableInit(a:)' has been replaced by 'Int.init(other:)'}} {{12-27=Int.init}}
fn(a: 1)
unavailableNestedInit(a: 0) // expected-error {{'unavailableNestedInit(a:)' has been replaced by 'Foo.Bar.init(other:)'}} {{3-24=Foo.Bar}} {{25-26=other}}
let fn2 = unavailableNestedInit // expected-error {{'unavailableNestedInit(a:)' has been replaced by 'Foo.Bar.init(other:)'}} {{13-34=Foo.Bar.init}}
fn2(a: 1)
}
@available(*, unavailable, renamed: "shinyLabeledArguments()")
func unavailableTooFew(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments()")
func unavailableTooFewUnnamed(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)")
func unavailableTooMany(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)")
func unavailableTooManyUnnamed(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:)")
func unavailableNoArgsTooMany() {} // expected-note {{here}}
func testRenameArgMismatch() {
unavailableTooFew(a: 0) // expected-error{{'unavailableTooFew(a:)' has been renamed to 'shinyLabeledArguments()'}} {{3-20=shinyLabeledArguments}}
unavailableTooFewUnnamed(0) // expected-error{{'unavailableTooFewUnnamed' has been renamed to 'shinyLabeledArguments()'}} {{3-27=shinyLabeledArguments}}
unavailableTooMany(a: 0) // expected-error{{'unavailableTooMany(a:)' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{3-21=shinyLabeledArguments}}
unavailableTooManyUnnamed(0) // expected-error{{'unavailableTooManyUnnamed' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{3-28=shinyLabeledArguments}}
unavailableNoArgsTooMany() // expected-error{{'unavailableNoArgsTooMany()' has been renamed to 'shinyLabeledArguments(a:)'}} {{3-27=shinyLabeledArguments}}
}
@available(*, unavailable, renamed: "Int.foo(self:)")
func unavailableInstance(a: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "Int.foo(self:)")
func unavailableInstanceUnlabeled(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:other:)")
func unavailableInstanceFirst(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(other:self:)")
func unavailableInstanceSecond(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(_:self:c:)")
func unavailableInstanceSecondOfThree(a: Int, b: Int, c: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:)", message: "blah")
func unavailableInstanceMessage(a: Int) {} // expected-note {{here}}
@available(*, deprecated, renamed: "Int.foo(self:)")
func deprecatedInstance(a: Int) {}
@available(*, deprecated, renamed: "Int.foo(self:)", message: "blah")
func deprecatedInstanceMessage(a: Int) {}
@available(*, unavailable, renamed: "Foo.Bar.foo(self:)")
func unavailableNestedInstance(a: Int) {} // expected-note {{here}}
func testRenameInstance() {
unavailableInstance(a: 0) // expected-error{{'unavailableInstance(a:)' has been replaced by instance method 'Int.foo()'}} {{3-22=0.foo}} {{23-27=}}
unavailableInstanceUnlabeled(0) // expected-error{{'unavailableInstanceUnlabeled' has been replaced by instance method 'Int.foo()'}} {{3-31=0.foo}} {{32-33=}}
unavailableInstanceFirst(a: 0, b: 1) // expected-error{{'unavailableInstanceFirst(a:b:)' has been replaced by instance method 'Int.foo(other:)'}} {{3-27=0.foo}} {{28-34=}} {{34-35=other}}
unavailableInstanceSecond(a: 0, b: 1) // expected-error{{'unavailableInstanceSecond(a:b:)' has been replaced by instance method 'Int.foo(other:)'}} {{3-28=1.foo}} {{29-30=other}} {{33-39=}}
unavailableInstanceSecondOfThree(a: 0, b: 1, c: 2) // expected-error{{'unavailableInstanceSecondOfThree(a:b:c:)' has been replaced by instance method 'Int.foo(_:c:)'}} {{3-35=1.foo}} {{36-39=}} {{42-48=}}
unavailableInstance(a: 0 + 0) // expected-error{{'unavailableInstance(a:)' has been replaced by instance method 'Int.foo()'}} {{3-22=(0 + 0).foo}} {{23-31=}}
unavailableInstanceMessage(a: 0) // expected-error{{'unavailableInstanceMessage(a:)' has been replaced by instance method 'Int.foo()': blah}} {{3-29=0.foo}} {{30-34=}}
deprecatedInstance(a: 0) // expected-warning{{'deprecatedInstance(a:)' is deprecated: replaced by instance method 'Int.foo()'}} expected-note{{use 'Int.foo()' instead}} {{3-21=0.foo}} {{22-26=}}
deprecatedInstanceMessage(a: 0) // expected-warning{{'deprecatedInstanceMessage(a:)' is deprecated: blah}} expected-note{{use 'Int.foo()' instead}} {{3-28=0.foo}} {{29-33=}}
unavailableNestedInstance(a: 0) // expected-error{{'unavailableNestedInstance(a:)' has been replaced by instance method 'Foo.Bar.foo()'}} {{3-28=0.foo}} {{29-33=}}
}
@available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:)")
func unavailableInstanceTooFew(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:)")
func unavailableInstanceTooFewUnnamed(_ a: Int, _ b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:b:)")
func unavailableInstanceTooMany(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:b:)")
func unavailableInstanceTooManyUnnamed(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:)")
func unavailableInstanceNoArgsTooMany() {} // expected-note {{here}}
func testRenameInstanceArgMismatch() {
unavailableInstanceTooFew(a: 0, b: 1) // expected-error{{'unavailableInstanceTooFew(a:b:)' has been replaced by instance method 'Int.shinyLabeledArguments()'}} {{none}}
unavailableInstanceTooFewUnnamed(0, 1) // expected-error{{'unavailableInstanceTooFewUnnamed' has been replaced by instance method 'Int.shinyLabeledArguments()'}} {{none}}
unavailableInstanceTooMany(a: 0) // expected-error{{'unavailableInstanceTooMany(a:)' has been replaced by instance method 'Int.shinyLabeledArguments(b:)'}} {{none}}
unavailableInstanceTooManyUnnamed(0) // expected-error{{'unavailableInstanceTooManyUnnamed' has been replaced by instance method 'Int.shinyLabeledArguments(b:)'}} {{none}}
unavailableInstanceNoArgsTooMany() // expected-error{{'unavailableInstanceNoArgsTooMany()' has been replaced by instance method 'Int.shinyLabeledArguments()'}} {{none}}
}
@available(*, unavailable, renamed: "getter:Int.prop(self:)")
func unavailableInstanceProperty(a: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "getter:Int.prop(self:)")
func unavailableInstancePropertyUnlabeled(_ a: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "getter:Int.prop()")
func unavailableClassProperty() {} // expected-note {{here}}
@available(*, unavailable, renamed: "getter:global()")
func unavailableGlobalProperty() {} // expected-note {{here}}
@available(*, unavailable, renamed: "getter:Int.prop(self:)", message: "blah")
func unavailableInstancePropertyMessage(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "getter:Int.prop()", message: "blah")
func unavailableClassPropertyMessage() {} // expected-note {{here}}
@available(*, unavailable, renamed: "getter:global()", message: "blah")
func unavailableGlobalPropertyMessage() {} // expected-note {{here}}
@available(*, deprecated, renamed: "getter:Int.prop(self:)")
func deprecatedInstanceProperty(a: Int) {}
@available(*, deprecated, renamed: "getter:Int.prop()")
func deprecatedClassProperty() {}
@available(*, deprecated, renamed: "getter:global()")
func deprecatedGlobalProperty() {}
@available(*, deprecated, renamed: "getter:Int.prop(self:)", message: "blah")
func deprecatedInstancePropertyMessage(a: Int) {}
@available(*, deprecated, renamed: "getter:Int.prop()", message: "blah")
func deprecatedClassPropertyMessage() {}
@available(*, deprecated, renamed: "getter:global()", message: "blah")
func deprecatedGlobalPropertyMessage() {}
func testRenameGetters() {
unavailableInstanceProperty(a: 1) // expected-error{{'unavailableInstanceProperty(a:)' has been replaced by property 'Int.prop'}} {{3-30=1.prop}} {{30-36=}}
unavailableInstancePropertyUnlabeled(1) // expected-error{{'unavailableInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-39=1.prop}} {{39-42=}}
unavailableInstanceProperty(a: 1 + 1) // expected-error{{'unavailableInstanceProperty(a:)' has been replaced by property 'Int.prop'}} {{3-30=(1 + 1).prop}} {{30-40=}}
unavailableInstancePropertyUnlabeled(1 + 1) // expected-error{{'unavailableInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-39=(1 + 1).prop}} {{39-46=}}
unavailableClassProperty() // expected-error{{'unavailableClassProperty()' has been replaced by property 'Int.prop'}} {{3-27=Int.prop}} {{27-29=}}
unavailableGlobalProperty() // expected-error{{'unavailableGlobalProperty()' has been replaced by 'global'}} {{3-28=global}} {{28-30=}}
unavailableInstancePropertyMessage(a: 1) // expected-error{{'unavailableInstancePropertyMessage(a:)' has been replaced by property 'Int.prop': blah}} {{3-37=1.prop}} {{37-43=}}
unavailableClassPropertyMessage() // expected-error{{'unavailableClassPropertyMessage()' has been replaced by property 'Int.prop': blah}} {{3-34=Int.prop}} {{34-36=}}
unavailableGlobalPropertyMessage() // expected-error{{'unavailableGlobalPropertyMessage()' has been replaced by 'global': blah}} {{3-35=global}} {{35-37=}}
deprecatedInstanceProperty(a: 1) // expected-warning {{'deprecatedInstanceProperty(a:)' is deprecated: replaced by property 'Int.prop'}} expected-note{{use 'Int.prop' instead}} {{3-29=1.prop}} {{29-35=}}
deprecatedClassProperty() // expected-warning {{'deprecatedClassProperty()' is deprecated: replaced by property 'Int.prop'}} expected-note{{use 'Int.prop' instead}} {{3-26=Int.prop}} {{26-28=}}
deprecatedGlobalProperty() // expected-warning {{'deprecatedGlobalProperty()' is deprecated: replaced by 'global'}} expected-note{{use 'global' instead}} {{3-27=global}} {{27-29=}}
deprecatedInstancePropertyMessage(a: 1) // expected-warning {{'deprecatedInstancePropertyMessage(a:)' is deprecated: blah}} expected-note{{use 'Int.prop' instead}} {{3-36=1.prop}} {{36-42=}}
deprecatedClassPropertyMessage() // expected-warning {{'deprecatedClassPropertyMessage()' is deprecated: blah}} expected-note{{use 'Int.prop' instead}} {{3-33=Int.prop}} {{33-35=}}
deprecatedGlobalPropertyMessage() // expected-warning {{'deprecatedGlobalPropertyMessage()' is deprecated: blah}} expected-note{{use 'global' instead}} {{3-34=global}} {{34-36=}}
}
@available(*, unavailable, renamed: "setter:Int.prop(self:_:)")
func unavailableSetInstanceProperty(a: Int, b: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "setter:Int.prop(_:self:)")
func unavailableSetInstancePropertyReverse(a: Int, b: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "setter:Int.prop(self:newValue:)")
func unavailableSetInstancePropertyUnlabeled(_ a: Int, _ b: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "setter:Int.prop(newValue:self:)")
func unavailableSetInstancePropertyUnlabeledReverse(_ a: Int, _ b: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "setter:Int.prop(x:)")
func unavailableSetClassProperty(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "setter:global(_:)")
func unavailableSetGlobalProperty(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "setter:Int.prop(self:_:)")
func unavailableSetInstancePropertyInout(a: inout Int, b: Int) {} // expected-note {{here}}
func testRenameSetters() {
unavailableSetInstanceProperty(a: 1, b: 2) // expected-error{{'unavailableSetInstanceProperty(a:b:)' has been replaced by property 'Int.prop'}} {{3-33=1.prop}} {{33-43= = }} {{44-45=}}
unavailableSetInstancePropertyUnlabeled(1, 2) // expected-error{{'unavailableSetInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-42=1.prop}} {{42-46= = }} {{47-48=}}
unavailableSetInstancePropertyReverse(a: 1, b: 2) // expected-error{{'unavailableSetInstancePropertyReverse(a:b:)' has been replaced by property 'Int.prop'}} {{3-40=2.prop}} {{40-44= = }} {{45-52=}}
unavailableSetInstancePropertyUnlabeledReverse(1, 2) // expected-error{{'unavailableSetInstancePropertyUnlabeledReverse' has been replaced by property 'Int.prop'}} {{3-49=2.prop}} {{49-50= = }} {{51-55=}}
unavailableSetInstanceProperty(a: 1 + 1, b: 2 + 2) // expected-error{{'unavailableSetInstanceProperty(a:b:)' has been replaced by property 'Int.prop'}} {{3-33=(1 + 1).prop}} {{33-47= = }} {{52-53=}}
unavailableSetInstancePropertyUnlabeled(1 + 1, 2 + 2) // expected-error{{'unavailableSetInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-42=(1 + 1).prop}} {{42-50= = }} {{55-56=}}
unavailableSetInstancePropertyReverse(a: 1 + 1, b: 2 + 2) // expected-error{{'unavailableSetInstancePropertyReverse(a:b:)' has been replaced by property 'Int.prop'}} {{3-40=(2 + 2).prop}} {{40-44= = }} {{49-60=}}
unavailableSetInstancePropertyUnlabeledReverse(1 + 1, 2 + 2) // expected-error{{'unavailableSetInstancePropertyUnlabeledReverse' has been replaced by property 'Int.prop'}} {{3-49=(2 + 2).prop}} {{49-50= = }} {{55-63=}}
unavailableSetClassProperty(a: 1) // expected-error{{'unavailableSetClassProperty(a:)' has been replaced by property 'Int.prop'}} {{3-30=Int.prop}} {{30-34= = }} {{35-36=}}
unavailableSetGlobalProperty(1) // expected-error{{'unavailableSetGlobalProperty' has been replaced by 'global'}} {{3-31=global}} {{31-32= = }} {{33-34=}}
var x = 0
unavailableSetInstancePropertyInout(a: &x, b: 2) // expected-error{{'unavailableSetInstancePropertyInout(a:b:)' has been replaced by property 'Int.prop'}} {{3-38=x.prop}} {{38-49= = }} {{50-51=}}
}
@available(*, unavailable, renamed: "Int.foo(self:execute:)")
func trailingClosure(_ value: Int, fn: () -> Void) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:bar:execute:)")
func trailingClosureArg(_ value: Int, _ other: Int, fn: () -> Void) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(bar:self:execute:)")
func trailingClosureArg2(_ value: Int, _ other: Int, fn: () -> Void) {} // expected-note {{here}}
func testInstanceTrailingClosure() {
trailingClosure(0) {} // expected-error {{'trailingClosure(_:fn:)' has been replaced by instance method 'Int.foo(execute:)'}} {{3-18=0.foo}} {{19-20=}}
trailingClosureArg(0, 1) {} // expected-error {{'trailingClosureArg(_:_:fn:)' has been replaced by instance method 'Int.foo(bar:execute:)'}} {{3-21=0.foo}} {{22-25=}} {{25-25=bar: }}
trailingClosureArg2(0, 1) {} // expected-error {{'trailingClosureArg2(_:_:fn:)' has been replaced by instance method 'Int.foo(bar:execute:)'}} {{3-22=1.foo}} {{23-23=bar: }} {{24-27=}}
}
@available(*, unavailable, renamed: "+")
func add(_ value: Int, _ other: Int) {} // expected-note {{here}}
infix operator *** {}
@available(*, unavailable, renamed: "add")
func ***(value: (), other: ()) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:_:)")
func ***(value: Int, other: Int) {} // expected-note {{here}}
prefix operator *** {}
@available(*, unavailable, renamed: "add")
prefix func ***(value: Int?) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:)")
prefix func ***(value: Int) {} // expected-note {{here}}
postfix operator *** {}
@available(*, unavailable, renamed: "add")
postfix func ***(value: Int?) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:)")
postfix func ***(value: Int) {} // expected-note {{here}}
func testOperators() {
add(0, 1) // expected-error {{'add' has been renamed to '+'}} {{none}}
() *** () // expected-error {{'***' has been renamed to 'add'}} {{none}}
0 *** 1 // expected-error {{'***' has been replaced by instance method 'Int.foo(_:)'}} {{none}}
***nil // expected-error {{'***' has been renamed to 'add'}} {{none}}
***0 // expected-error {{'***' has been replaced by instance method 'Int.foo()'}} {{none}}
nil*** // expected-error {{'***' has been renamed to 'add'}} {{none}}
0*** // expected-error {{'***' has been replaced by instance method 'Int.foo()'}} {{none}}
}
extension Int {
@available(*, unavailable, renamed: "init(other:)")
@discardableResult
static func factory(other: Int) -> Int { return other } // expected-note 2 {{here}}
@available(*, unavailable, renamed: "Int.init(other:)")
@discardableResult
static func factory2(other: Int) -> Int { return other } // expected-note 2 {{here}}
static func testFactoryMethods() {
factory(other: 1) // expected-error {{'factory(other:)' has been replaced by 'init(other:)'}} {{none}}
factory2(other: 1) // expected-error {{'factory2(other:)' has been replaced by 'Int.init(other:)'}} {{5-13=Int}}
}
}
func testFactoryMethods() {
Int.factory(other: 1) // expected-error {{'factory(other:)' has been replaced by 'init(other:)'}} {{6-14=}}
Int.factory2(other: 1) // expected-error {{'factory2(other:)' has been replaced by 'Int.init(other:)'}} {{3-15=Int}}
}
class Base {
@available(*, unavailable)
func bad() {} // expected-note {{here}}
@available(*, unavailable, message: "it was smelly")
func smelly() {} // expected-note {{here}}
@available(*, unavailable, renamed: "new")
func old() {} // expected-note {{here}}
@available(*, unavailable, renamed: "new", message: "it was smelly")
func oldAndSmelly() {} // expected-note {{here}}
@available(*, unavailable)
var badProp: Int { return 0 } // expected-note {{here}}
@available(*, unavailable, message: "it was smelly")
var smellyProp: Int { return 0 } // expected-note {{here}}
@available(*, unavailable, renamed: "new")
var oldProp: Int { return 0 } // expected-note {{here}}
@available(*, unavailable, renamed: "new", message: "it was smelly")
var oldAndSmellyProp: Int { return 0 } // expected-note {{here}}
@available(*, unavailable, renamed: "init")
func nowAnInitializer() {} // expected-note {{here}}
@available(*, unavailable, renamed: "init()")
func nowAnInitializer2() {} // expected-note {{here}}
@available(*, unavailable, renamed: "foo")
init(nowAFunction: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "foo(_:)")
init(nowAFunction2: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableArgNames(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableArgRenamed(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments()")
func unavailableNoArgs() {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:)")
func unavailableSame(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableUnnamed(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:)")
func unavailableUnnamedSame(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:)")
func unavailableNewlyUnnamed(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)")
func unavailableMultiSame(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:another:)")
func unavailableMultiUnnamed(_ a: Int, _ b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)")
func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)")
func unavailableMultiNewlyUnnamed(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "init(shinyNewName:)")
init(unavailableArgNames: Int) {} // expected-note{{here}}
@available(*, unavailable, renamed: "init(a:)")
init(_ unavailableUnnamed: Int) {} // expected-note{{here}}
@available(*, unavailable, renamed: "init(_:)")
init(unavailableNewlyUnnamed: Int) {} // expected-note{{here}}
@available(*, unavailable, renamed: "init(a:b:)")
init(_ unavailableMultiUnnamed: Int, _ b: Int) {} // expected-note{{here}}
@available(*, unavailable, renamed: "init(_:_:)")
init(unavailableMultiNewlyUnnamed a: Int, b: Int) {} // expected-note{{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(x:)")
func unavailableTooFew(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(x:b:)")
func unavailableTooMany(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(x:)")
func unavailableNoArgsTooMany() {} // expected-note {{here}}
@available(*, unavailable, renamed: "Base.shinyLabeledArguments()")
func unavailableHasType() {} // expected-note {{here}}
}
class Sub : Base {
override func bad() {} // expected-error {{cannot override 'bad' which has been marked unavailable}} {{none}}
override func smelly() {} // expected-error {{cannot override 'smelly' which has been marked unavailable: it was smelly}} {{none}}
override func old() {} // expected-error {{'old()' has been renamed to 'new'}} {{17-20=new}}
override func oldAndSmelly() {} // expected-error {{'oldAndSmelly()' has been renamed to 'new': it was smelly}} {{17-29=new}}
override var badProp: Int { return 0 } // expected-error {{cannot override 'badProp' which has been marked unavailable}} {{none}}
override var smellyProp: Int { return 0 } // expected-error {{cannot override 'smellyProp' which has been marked unavailable: it was smelly}} {{none}}
override var oldProp: Int { return 0 } // expected-error {{'oldProp' has been renamed to 'new'}} {{16-23=new}}
override var oldAndSmellyProp: Int { return 0 } // expected-error {{'oldAndSmellyProp' has been renamed to 'new': it was smelly}} {{16-32=new}}
override func nowAnInitializer() {} // expected-error {{'nowAnInitializer()' has been replaced by 'init'}} {{none}}
override func nowAnInitializer2() {} // expected-error {{'nowAnInitializer2()' has been replaced by 'init()'}} {{none}}
override init(nowAFunction: Int) {} // expected-error {{'init(nowAFunction:)' has been renamed to 'foo'}} {{none}}
override init(nowAFunction2: Int) {} // expected-error {{'init(nowAFunction2:)' has been renamed to 'foo(_:)'}} {{none}}
override func unavailableArgNames(a: Int) {} // expected-error {{'unavailableArgNames(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{17-36=shinyLabeledArguments}} {{37-37=example }}
override func unavailableArgRenamed(a param: Int) {} // expected-error {{'unavailableArgRenamed(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{17-38=shinyLabeledArguments}} {{39-40=example}}
override func unavailableNoArgs() {} // expected-error {{'unavailableNoArgs()' has been renamed to 'shinyLabeledArguments()'}} {{17-34=shinyLabeledArguments}}
override func unavailableSame(a: Int) {} // expected-error {{'unavailableSame(a:)' has been renamed to 'shinyLabeledArguments(a:)'}} {{17-32=shinyLabeledArguments}}
override func unavailableUnnamed(_ a: Int) {} // expected-error {{'unavailableUnnamed' has been renamed to 'shinyLabeledArguments(example:)'}} {{17-35=shinyLabeledArguments}} {{36-37=example}}
override func unavailableUnnamedSame(_ a: Int) {} // expected-error {{'unavailableUnnamedSame' has been renamed to 'shinyLabeledArguments(_:)'}} {{17-39=shinyLabeledArguments}}
override func unavailableNewlyUnnamed(a: Int) {} // expected-error {{'unavailableNewlyUnnamed(a:)' has been renamed to 'shinyLabeledArguments(_:)'}} {{17-40=shinyLabeledArguments}} {{41-41=_ }}
override func unavailableMultiSame(a: Int, b: Int) {} // expected-error {{'unavailableMultiSame(a:b:)' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{17-37=shinyLabeledArguments}}
override func unavailableMultiUnnamed(_ a: Int, _ b: Int) {} // expected-error {{'unavailableMultiUnnamed' has been renamed to 'shinyLabeledArguments(example:another:)'}} {{17-40=shinyLabeledArguments}} {{41-42=example}} {{51-52=another}}
override func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) {} // expected-error {{'unavailableMultiUnnamedSame' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{17-44=shinyLabeledArguments}}
override func unavailableMultiNewlyUnnamed(a: Int, b: Int) {} // expected-error {{'unavailableMultiNewlyUnnamed(a:b:)' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{17-45=shinyLabeledArguments}} {{46-46=_ }} {{54-54=_ }}
override init(unavailableArgNames: Int) {} // expected-error {{'init(unavailableArgNames:)' has been renamed to 'init(shinyNewName:)'}} {{17-17=shinyNewName }}
override init(_ unavailableUnnamed: Int) {} // expected-error {{'init' has been renamed to 'init(a:)'}} {{17-18=a}}
override init(unavailableNewlyUnnamed: Int) {} // expected-error {{'init(unavailableNewlyUnnamed:)' has been renamed to 'init(_:)'}} {{17-17=_ }}
override init(_ unavailableMultiUnnamed: Int, _ b: Int) {} // expected-error {{'init' has been renamed to 'init(a:b:)'}} {{17-18=a}} {{49-51=}}
override init(unavailableMultiNewlyUnnamed a: Int, b: Int) {} // expected-error {{'init(unavailableMultiNewlyUnnamed:b:)' has been renamed to 'init(_:_:)'}} {{17-45=_}} {{54-54=_ }}
override func unavailableTooFew(a: Int, b: Int) {} // expected-error {{'unavailableTooFew(a:b:)' has been renamed to 'shinyLabeledArguments(x:)'}} {{none}}
override func unavailableTooMany(a: Int) {} // expected-error {{'unavailableTooMany(a:)' has been renamed to 'shinyLabeledArguments(x:b:)'}} {{none}}
override func unavailableNoArgsTooMany() {} // expected-error {{'unavailableNoArgsTooMany()' has been renamed to 'shinyLabeledArguments(x:)'}} {{none}}
override func unavailableHasType() {} // expected-error {{'unavailableHasType()' has been replaced by 'Base.shinyLabeledArguments()'}} {{none}}
}
|
apache-2.0
|
b7270640d8bad7f815747e7581a730d9
| 63.319527 | 303 | 0.710557 | 4.087619 | false | false | false | false |
mshhmzh/firefox-ios
|
Extensions/ShareTo/ShareViewController.swift
|
3
|
11319
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import Storage
struct ShareDestination {
let code: String
let name: String
let image: String
}
// TODO: See if we can do this with an Enum instead. Previous attempts failed because for example NSSet does not take (string) enum values.
let ShareDestinationBookmarks: String = "Bookmarks"
let ShareDestinationReadingList: String = "ReadingList"
let ShareDestinations = [
ShareDestination(code: ShareDestinationReadingList, name: NSLocalizedString("Add to Reading List", tableName: "ShareTo", comment: "On/off toggle to select adding this url to your reading list"), image: "AddToReadingList"),
ShareDestination(code: ShareDestinationBookmarks, name: NSLocalizedString("Add to Bookmarks", tableName: "ShareTo", comment: "On/off toggle to select adding this url to your bookmarks"), image: "AddToBookmarks")
]
protocol ShareControllerDelegate {
func shareControllerDidCancel(shareController: ShareDialogController) -> Void
func shareController(shareController: ShareDialogController, didShareItem item: ShareItem, toDestinations destinations: NSSet) -> Void
}
private struct ShareDialogControllerUX {
static let CornerRadius: CGFloat = 4 // Corner radius of the dialog
static let NavigationBarTintColor = UIColor(rgb: 0xf37c00) // Tint color changes the text color in the navigation bar
static let NavigationBarCancelButtonFont = UIFont.systemFontOfSize(UIFont.buttonFontSize()) // System default
static let NavigationBarAddButtonFont = UIFont.boldSystemFontOfSize(UIFont.buttonFontSize()) // System default
static let NavigationBarIconSize = 38 // Width and height of the icon
static let NavigationBarBottomPadding = 12
@available(iOSApplicationExtension 8.2, *)
static let ItemTitleFontMedium = UIFont.systemFontOfSize(15, weight: UIFontWeightMedium)
static let ItemTitleFont = UIFont.systemFontOfSize(15)
static let ItemTitleMaxNumberOfLines = 2
static let ItemTitleLeftPadding = 44
static let ItemTitleRightPadding = 44
static let ItemTitleBottomPadding = 12
static let ItemLinkFont = UIFont.systemFontOfSize(12)
static let ItemLinkMaxNumberOfLines = 3
static let ItemLinkLeftPadding = 44
static let ItemLinkRightPadding = 44
static let ItemLinkBottomPadding = 14
static let DividerColor = UIColor.lightGrayColor() // Divider between the item and the table with destinations
static let DividerHeight = 0.5
static let TableRowHeight: CGFloat = 44 // System default
static let TableRowFont = UIFont.systemFontOfSize(14)
static let TableRowFontMinScale: CGFloat = 0.8
static let TableRowTintColor = UIColor(red:0.427, green:0.800, blue:0.102, alpha:1.0) // Green tint for the checkmark
static let TableRowTextColor = UIColor(rgb: 0x555555)
static let TableHeight = 88 // Height of 2 standard 44px cells
}
class ShareDialogController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var delegate: ShareControllerDelegate!
var item: ShareItem!
var initialShareDestinations: NSSet = NSSet(object: ShareDestinationBookmarks)
var selectedShareDestinations: NSMutableSet = NSMutableSet()
var navBar: UINavigationBar!
var navItem: UINavigationItem!
override func viewDidLoad() {
super.viewDidLoad()
selectedShareDestinations = NSMutableSet(set: initialShareDestinations)
self.view.backgroundColor = UIColor.whiteColor()
self.view.layer.cornerRadius = ShareDialogControllerUX.CornerRadius
self.view.clipsToBounds = true
// Setup the NavigationBar
navBar = UINavigationBar()
navBar.translatesAutoresizingMaskIntoConstraints = false
navBar.tintColor = ShareDialogControllerUX.NavigationBarTintColor
navBar.translucent = false
self.view.addSubview(navBar)
// Setup the NavigationItem
navItem = UINavigationItem()
navItem.leftBarButtonItem = UIBarButtonItem(
title: Strings.ShareToCancelButton,
style: .Plain,
target: self,
action: #selector(ShareDialogController.cancel)
)
navItem.leftBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: ShareDialogControllerUX.NavigationBarCancelButtonFont], forState: UIControlState.Normal)
navItem.leftBarButtonItem?.accessibilityIdentifier = "ShareDialogController.navigationItem.leftBarButtonItem"
navItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Add", tableName: "ShareTo", comment: "Add button in the share dialog"), style: UIBarButtonItemStyle.Done, target: self, action: #selector(ShareDialogController.add))
navItem.rightBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: ShareDialogControllerUX.NavigationBarAddButtonFont], forState: UIControlState.Normal)
let logo = UIImageView(frame: CGRect(x: 0, y: 0, width: ShareDialogControllerUX.NavigationBarIconSize, height: ShareDialogControllerUX.NavigationBarIconSize))
logo.image = UIImage(named: "Icon-Small")
logo.contentMode = UIViewContentMode.ScaleAspectFit // TODO Can go away if icon is provided in correct size
navItem.titleView = logo
navBar.pushNavigationItem(navItem, animated: false)
// Setup the title view
let titleView = UILabel()
titleView.translatesAutoresizingMaskIntoConstraints = false
titleView.numberOfLines = ShareDialogControllerUX.ItemTitleMaxNumberOfLines
titleView.lineBreakMode = NSLineBreakMode.ByTruncatingTail
titleView.text = item.title
titleView.font = ShareDialogControllerUX.ItemTitleFontMedium
view.addSubview(titleView)
// Setup the link view
let linkView = UILabel()
linkView.translatesAutoresizingMaskIntoConstraints = false
linkView.numberOfLines = ShareDialogControllerUX.ItemLinkMaxNumberOfLines
linkView.lineBreakMode = NSLineBreakMode.ByTruncatingTail
linkView.text = item.url
linkView.font = ShareDialogControllerUX.ItemLinkFont
view.addSubview(linkView)
// Setup the icon
let iconView = UIImageView()
iconView.translatesAutoresizingMaskIntoConstraints = false
iconView.image = UIImage(named: "defaultFavicon")
view.addSubview(iconView)
// Setup the divider
let dividerView = UIView()
dividerView.translatesAutoresizingMaskIntoConstraints = false
dividerView.backgroundColor = ShareDialogControllerUX.DividerColor
view.addSubview(dividerView)
// Setup the table with destinations
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.separatorInset = UIEdgeInsetsZero
tableView.layoutMargins = UIEdgeInsetsZero
tableView.userInteractionEnabled = true
tableView.delegate = self
tableView.allowsSelection = true
tableView.dataSource = self
tableView.scrollEnabled = false
view.addSubview(tableView)
// Setup constraints
let views = [
"nav": navBar,
"title": titleView,
"link": linkView,
"icon": iconView,
"divider": dividerView,
"table": tableView
]
// TODO See Bug 1102516 - Use Snappy to define share extension layout constraints
let constraints = [
"H:|[nav]|",
"V:|[nav]",
"H:|-\(ShareDialogControllerUX.ItemTitleLeftPadding)-[title]-\(ShareDialogControllerUX.ItemTitleRightPadding)-|",
"V:[nav]-\(ShareDialogControllerUX.NavigationBarBottomPadding)-[title]",
"H:|-\(ShareDialogControllerUX.ItemLinkLeftPadding)-[link]-\(ShareDialogControllerUX.ItemLinkLeftPadding)-|",
"V:[title]-\(ShareDialogControllerUX.ItemTitleBottomPadding)-[link]",
"H:|[divider]|",
"V:[divider(\(ShareDialogControllerUX.DividerHeight))]",
"V:[link]-\(ShareDialogControllerUX.ItemLinkBottomPadding)-[divider]",
"H:|[table]|",
"V:[divider][table]",
"V:[table(\(ShareDialogControllerUX.TableHeight))]|"
]
for constraint in constraints {
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(constraint, options: NSLayoutFormatOptions(), metrics: nil, views: views))
}
}
// UITabBarItem Actions that map to our delegate methods
func cancel() {
delegate?.shareControllerDidCancel(self)
}
func add() {
delegate?.shareController(self, didShareItem: item, toDestinations: NSSet(set: selectedShareDestinations))
}
// UITableView Delegate and DataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ShareDestinations.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return ShareDialogControllerUX.TableRowHeight
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.textColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.darkGrayColor() : ShareDialogControllerUX.TableRowTextColor
cell.textLabel?.font = ShareDialogControllerUX.TableRowFont
cell.accessoryType = selectedShareDestinations.containsObject(ShareDestinations[indexPath.row].code) ? UITableViewCellAccessoryType.Checkmark : UITableViewCellAccessoryType.None
cell.tintColor = ShareDialogControllerUX.TableRowTintColor
cell.layoutMargins = UIEdgeInsetsZero
cell.textLabel?.text = ShareDestinations[indexPath.row].name
cell.textLabel?.adjustsFontSizeToFitWidth = true
cell.textLabel?.minimumScaleFactor = ShareDialogControllerUX.TableRowFontMinScale
cell.imageView?.image = UIImage(named: ShareDestinations[indexPath.row].image)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
let code = ShareDestinations[indexPath.row].code
if selectedShareDestinations.containsObject(code) {
selectedShareDestinations.removeObject(code)
} else {
selectedShareDestinations.addObject(code)
}
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
navItem.rightBarButtonItem?.enabled = (selectedShareDestinations.count != 0)
}
}
|
mpl-2.0
|
4b6cc0884c1efdb2c5f97574cfb3fdab
| 44.825911 | 244 | 0.703066 | 6.0368 | false | false | false | false |
michaelcordero/CoreDataStructures
|
Tests/CoreDataStructuresTests/QueueTestCase.swift
|
1
|
2599
|
//
// QueueTestCase.swift
// CoreDataStructures_Tests
//
// Created by Michael Cordero on 1/2/21.
//
import XCTest
@testable import CoreDataStructures
class QueueTestCase: XCTestCase {
// MARK: - Test Object
let xQueue: Queue<Float> = Queue<Float>()
// MARK: - XCTestCase
override func setUp() {
super.setUp()
xQueue.add(1.0)
xQueue.add(2.0)
xQueue.add(3.0)
// 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()
}
// MARK: - Functional Tests
func testAdd() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
print("Current values: \(xQueue.values())")
let testElement: Float = 4.0
xQueue.add(testElement)
XCTAssert(xQueue.values().contains(testElement))
print("Updated values: \(xQueue.values())")
}
func testSize() {
print("Current values: \(xQueue.values())")
let originalSize: Int = xQueue.values().count
let testElement: Float = 5.0
xQueue.add(testElement)
print("Updated values: \(xQueue.values())")
let newSize: Int = xQueue.values().count
XCTAssertEqual(originalSize+1, newSize)
}
func testRemove() {
print("Current values: \(xQueue.values())")
let testElement: Float = xQueue.values()[0]
let actualElement: Float? = xQueue.remove()
XCTAssertEqual(testElement, actualElement)
XCTAssertTrue(!xQueue.values().contains(testElement))
print("Updated values: \(xQueue.values())")
}
func testElement() {
print("Current values: \(xQueue.values())")
let testElement: Float = xQueue.values()[0]
let actualElement: Float? = xQueue.element()
XCTAssertEqual(testElement, actualElement)
print("Updated values: \(xQueue.values())")
}
func testClear() {
print("Current values: \(xQueue.values())")
xQueue.clear()
XCTAssertTrue(xQueue.values().isEmpty)
print("Updated values: \(xQueue.values())")
}
func testPerformanceExample() {
// This is an example of a performance test case.
// self.measure {
// // Put the code you want to measure the time of here.
// }
}
}
|
mit
|
46a0be0164fd636597d20594295c3c8c
| 30.313253 | 111 | 0.604848 | 4.295868 | false | true | false | false |
Osnobel/GDGameExtensions
|
GDGameExtensions/GDAds/GDAdBannerAdmob.swift
|
1
|
3964
|
//
// GDAdBannerAdmob.swift
// GDAds
//
// Created by Bell on 16/5/26.
// Copyright © 2016年 GoshDo <http://goshdo.sinaapp.com>. All rights reserved.
//
import GoogleMobileAds
class GDAdBannerAdmob: GDAdBannerBase, GADBannerViewDelegate {
weak var rootViewController: UIViewController?
var adUnitID: String = ""
private var _statusCode: UInt64 = 0
private var _weight: UInt64 = 0
override init() {
super.init()
self.bannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(GDAdBannerAdmob.changeSize), name: UIApplicationDidChangeStatusBarOrientationNotification, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func create(superview: UIView) {
guard let rootViewController = self.rootViewController else {
print("Invalid RootViewController for GADBannerView")
return
}
if let bannerView = self.bannerView as? GADBannerView {
bannerView.delegate = self
superview.addSubview(bannerView)
bannerView.hidden = true
bannerView.adUnitID = self.adUnitID
bannerView.rootViewController = rootViewController
let request = GADRequest()
request.testDevices = [kGADSimulatorID]
bannerView.loadRequest(request)
self.changeSize()
print("[GDAdBannerAdmob]#create.")
}
super.create(superview)
}
override func destroy() {
super.destroy()
if let bannerView = self.bannerView as? GADBannerView {
bannerView.delegate = nil
bannerView.removeFromSuperview()
self.visible = false
print("[GDAdBannerAdmob]#destroy.")
}
}
override var weight: UInt64 {
get {
print("[GDAdBannerAdmob]#weight=\(self._weight), status_code=\(self._statusCode).")
return self._weight * self._statusCode
}
set {
self._weight = newValue
}
}
@objc private func changeSize() {
guard let bannerView = self.bannerView as? GADBannerView else { return }
if UIApplication.sharedApplication().statusBarOrientation.isPortrait {
bannerView.adSize = kGADAdSizeSmartBannerPortrait
} else {
bannerView.adSize = kGADAdSizeSmartBannerLandscape
}
self.delegate?.bannerBaseSizeDidChanged?(bannerView.frame.size)
}
//MARK: GADBannerViewDelegate methods
// 当 loadRequest: 成功时发送
func adViewDidReceiveAd(bannerView: GADBannerView!) {
self._statusCode = 1
self.delegate?.bannerBaseDidReceiveAd?(self)
}
// 当 loadRequest: 失败时发送
func adView(bannerView: GADBannerView!, didFailToReceiveAdWithError error: GADRequestError!) {
self._statusCode = 0
self.delegate?.bannerBase?(self, didFailToReceiveAdWithError: error)
}
// 在系统响应用户触摸发送者的操作而即将向其展示全屏广告用户界面时发送
func adViewWillPresentScreen(bannerView: GADBannerView!) {
self.delegate?.bannerBaseWillPresentScreen?(self)
}
// 在用户关闭发送者的全屏用户界面前发送
func adViewWillDismissScreen(bannerView: GADBannerView!) {
self.delegate?.bannerBaseWillDismissScreen?(self)
}
// 当用户已退出发送者的全屏用户界面时发送
func adViewDidDismissScreen(bannerView: GADBannerView!) {
self.delegate?.bannerBaseDidDismissScreen?(self)
}
// 在应用因为用户触摸 Click-to-App-Store 或 Click-to-iTunes 横幅广告而转至后台或终止运行前发送
func adViewWillLeaveApplication(bannerView: GADBannerView!) {
self.delegate?.bannerBaseWillLeaveApplication?(self)
}
}
|
mit
|
755f381c59d7773ed5af81f2716c1395
| 34.657143 | 186 | 0.659364 | 4.798718 | false | false | false | false |
ngageoint/fog-machine
|
Demo/FogViewshed/FogViewshed/Utility/HGTRegions.swift
|
1
|
1759
|
import Foundation
class HGTRegions {
let REGION_AFRICA = "Africa"
let REGION_AUSTRALIA = "Australia"
let REGION_EURASIA = "Eurasia"
let REGION_ISLANDS = "Islands"
let REGION_NORTH_AMERICA = "North_America"
let REGION_SOUTH_AMERICA = "South_America"
var filePrefixToRegion:[String:String] = [String:String]()
init() {
var resourceURL:NSURL = NSURL(string: NSBundle.mainBundle().resourcePath!)!
do {
let hgtRegionsFile:NSURL = try (NSFileManager.defaultManager().contentsOfDirectoryAtURL(resourceURL, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions()).filter{ $0.lastPathComponent == "HGTRegions.txt" }).first!
if let aStreamReader = StreamReader(path: hgtRegionsFile.path!) {
defer {
aStreamReader.close()
}
while let line = aStreamReader.nextLine() {
let prefixAndRegion:[String] = line.componentsSeparatedByString(",")
filePrefixToRegion[prefixAndRegion[0]] = prefixAndRegion[1]
}
}
} catch let error as NSError {
NSLog("Error reading file: \(error.localizedDescription)")
}
}
func getRegion(filename:String) -> String {
let dot:Character = "."
if let idx = filename.characters.indexOf(dot) {
let pos = filename.startIndex.distanceTo(idx)
let prefix:String = filename.substringWithRange(filename.startIndex ..< filename.startIndex.advancedBy(pos))
if let region:String = filePrefixToRegion[prefix] {
return region
}
} else {
NSLog("Bad filename")
}
return ""
}
}
|
mit
|
b1811e59edafaa0aa44b9b1fffcf17ec
| 35.645833 | 246 | 0.606595 | 4.556995 | false | false | false | false |
Desgard/Calendouer-iOS
|
Calendouer/Pods/SwipeableTabBarController/SwipeableTabBarController/Classes/SwipeAnimationType.swift
|
1
|
2969
|
//
// SwipeAnimationType.swift
// Pods
//
// Created by Marcos Griselli on 2/1/17.
//
//
import UIKit
public protocol SwipeAnimationTypeProtocol {
func addTo(containerView: UIView, fromView: UIView, toView: UIView)
func prepare(fromView from: UIView?, toView to: UIView?, direction: Bool)
func animation(fromView from: UIView?, toView to: UIView?, direction: Bool)
}
/// Different types of interactive animations.
///
/// - overlap: Previously selected tab will stay in place while the new tab slides in.
/// - sideBySide: Both tabs move side by side as the animation takes place.
/// - push: Replicates iOS default push animation.
public enum SwipeAnimationType: SwipeAnimationTypeProtocol {
case overlap
case sideBySide
case push
/// Setup the views hirearchy for different animations types.
///
/// - Parameters:
/// - containerView: View that will contain the tabs views that will perform the animation
/// - fromView: Previously selected tab view.
/// - toView: New selected tab view.
public func addTo(containerView: UIView, fromView: UIView, toView: UIView) {
switch self {
case .push:
containerView.addSubview(toView)
containerView.addSubview(fromView)
default:
containerView.addSubview(fromView)
containerView.addSubview(toView)
}
}
/// Setup the views position prior to the animation start.
///
/// - Parameters:
/// - from: Previously selected tab view.
/// - to: New selected tab view.
/// - direction: Direction in which the views will animate.
public func prepare(fromView from: UIView?, toView to: UIView?, direction: Bool) {
let screenWidth = UIScreen.main.bounds.size.width
switch self {
case .overlap:
to?.frame.origin.x = direction ? -screenWidth : screenWidth
case .sideBySide:
from?.frame.origin.x = 0
to?.frame.origin.x = direction ? -screenWidth : screenWidth
case .push:
let scaledWidth = screenWidth/6
to?.frame.origin.x = direction ? -scaledWidth : scaledWidth
from?.frame.origin.x = 0
}
}
/// The animation to take place.
///
/// - Parameters:
/// - from: Previously selected tab view.
/// - to: New selected tab view.
/// - direction: Direction in which the views will animate.
public func animation(fromView from: UIView?, toView to: UIView?, direction: Bool) {
let screenWidth = UIScreen.main.bounds.size.width
switch self {
case .overlap:
to?.frame.origin.x = 0
case .sideBySide:
from?.frame.origin.x = direction ? screenWidth : -screenWidth
to?.frame.origin.x = 0
case .push:
to?.frame.origin.x = 0
from?.frame.origin.x = direction ? screenWidth : -screenWidth
}
}
}
|
mit
|
ead16418d7a5ce4ff966d10d540e8691
| 33.126437 | 96 | 0.623442 | 4.464662 | false | false | false | false |
wesj/Deferred
|
Deferred/ReadWriteLock.swift
|
1
|
4583
|
//
// ReadWriteLock.swift
// ReadWriteLock
//
// Created by John Gallagher on 7/17/14.
// Copyright (c) 2014 Big Nerd Ranch. All rights reserved.
//
import Foundation
public protocol ReadWriteLock: class {
func withReadLock<T>(block: () -> T) -> T
func withWriteLock<T>(block: () -> T) -> T
}
public final class GCDReadWriteLock: ReadWriteLock {
private let queue = dispatch_queue_create("GCDReadWriteLock", DISPATCH_QUEUE_CONCURRENT)
public init() {}
public func withReadLock<T>(block: () -> T) -> T {
var result: T!
dispatch_sync(queue) {
result = block()
}
return result
}
public func withWriteLock<T>(block: () -> T) -> T {
var result: T!
dispatch_barrier_sync(queue) {
result = block()
}
return result
}
}
public final class SpinLock: ReadWriteLock {
private var lock: UnsafeMutablePointer<Int32>
public init() {
lock = UnsafeMutablePointer.alloc(1)
lock.memory = OS_SPINLOCK_INIT
}
deinit {
lock.dealloc(1)
}
public func withReadLock<T>(block: () -> T) -> T {
OSSpinLockLock(lock)
let result = block()
OSSpinLockUnlock(lock)
return result
}
public func withWriteLock<T>(block: () -> T) -> T {
OSSpinLockLock(lock)
let result = block()
OSSpinLockUnlock(lock)
return result
}
}
/// Test comment 2
public final class CASSpinLock: ReadWriteLock {
private struct Masks {
static let WRITER_BIT: Int32 = 0x40000000
static let WRITER_WAITING_BIT: Int32 = 0x20000000
static let MASK_WRITER_BITS = WRITER_BIT | WRITER_WAITING_BIT
static let MASK_READER_BITS = ~MASK_WRITER_BITS
}
private var _state: UnsafeMutablePointer<Int32>
public init() {
_state = UnsafeMutablePointer.alloc(1)
_state.memory = 0
}
deinit {
_state.dealloc(1)
}
public func withWriteLock<T>(block: () -> T) -> T {
// spin until we acquire write lock
do {
let state = _state.memory
// if there are no readers and no one holds the write lock, try to grab the write lock immediately
if (state == 0 || state == Masks.WRITER_WAITING_BIT) &&
OSAtomicCompareAndSwap32Barrier(state, Masks.WRITER_BIT, _state) {
break
}
// If we get here, someone is reading or writing. Set the WRITER_WAITING_BIT if
// it isn't already to block any new readers, then wait a bit before
// trying again. Ignore CAS failure - we'll just try again next iteration
if state & Masks.WRITER_WAITING_BIT == 0 {
OSAtomicCompareAndSwap32Barrier(state, state | Masks.WRITER_WAITING_BIT, _state)
}
} while true
// write lock acquired - run block
let result = block()
// unlock
do {
let state = _state.memory
// clear everything except (possibly) WRITER_WAITING_BIT, which will only be set
// if another writer is already here and waiting (which will keep out readers)
if OSAtomicCompareAndSwap32Barrier(state, state & Masks.WRITER_WAITING_BIT, _state) {
break
}
} while true
return result
}
public func withReadLock<T>(block: () -> T) -> T {
// spin until we acquire read lock
do {
let state = _state.memory
// if there is no writer and no writer waiting, try to increment reader count
if (state & Masks.MASK_WRITER_BITS) == 0 &&
OSAtomicCompareAndSwap32Barrier(state, state + 1, _state) {
break
}
} while true
// read lock acquired - run block
let result = block()
// decrement reader count
do {
let state = _state.memory
// sanity check that we have a positive reader count before decrementing it
assert((state & Masks.MASK_READER_BITS) > 0, "unlocking read lock - invalid reader count")
// desired new state: 1 fewer reader, preserving whether or not there is a writer waiting
let newState = ((state & Masks.MASK_READER_BITS) - 1) |
(state & Masks.WRITER_WAITING_BIT)
if OSAtomicCompareAndSwap32Barrier(state, newState, _state) {
break
}
} while true
return result
}
}
|
mit
|
e9595d4f0fa22878b97f0b496bb4bc24
| 28.766234 | 110 | 0.573642 | 4.344076 | false | false | false | false |
yyny1789/KrMediumKit
|
Source/UI/PullToRefresh/UIScrollView+Refresher.swift
|
1
|
2841
|
//
// UIScrollView+Refresher.swift
// Client
//
// Created by aidenluo on 12/5/15.
// Copyright © 2015 36Kr. All rights reserved.
//
import Foundation
import UIKit
private var RefresherAssociatedObjectKey: UInt8 = 0
private var LoadmoreAssociatedObjectKey: UInt8 = 0
public extension UIScrollView {
public var refresher: Refresher? {
get {
return objc_getAssociatedObject(self, &RefresherAssociatedObjectKey) as? Refresher
}
set {
objc_setAssociatedObject(self, &RefresherAssociatedObjectKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
public var loadmore: Loadmore? {
get {
return objc_getAssociatedObject(self, &LoadmoreAssociatedObjectKey) as? Loadmore
}
set {
objc_setAssociatedObject(self, &LoadmoreAssociatedObjectKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
public func setupPullToRefresh(_ refresh: Refresher = Refresher(), action: VoidClosureType?) {
self.refresher = refresh
self.refresher?.scrollView = self
self.refresher?.action = action
self.refresher?.addScrollViewObserving()
updateScrollViewConentInset()
}
public func removePullToRefresh() {
self.refresher?.removeScrollViewObserving()
self.refresher = nil
}
public func beiginRefresh() {
self.refresher?.startRefreshing()
}
public func endRefresh() {
self.refresher?.endRefreshing()
}
/**
添加Loadmore最好是拉取到数据后,判断是否有后续数据再决定是否添加,而不是初始化
*/
public func setupLoadmore(_ loadmore: Loadmore = Loadmore(), action: VoidClosureType?) {
self.loadmore = loadmore
self.loadmore?.scrollView = self
self.loadmore?.action = action
self.loadmore?.addScrollViewObserving()
updateScrollViewConentInset()
}
public func removeLoadmore() {
self.loadmore?.removeScrollViewObserving()
self.loadmore = nil
}
public func endLoadmore(hasMore more: Bool = true) {
self.loadmore?.endLoadingmore(more)
}
public func errorLoadingmore() {
self.loadmore?.errorLoadingmore()
}
public func resetNoMoreData() {
self.loadmore?.view.isHidden = false
self.loadmore?.resetLoadmoreState()
}
public func hideLoadmore() {
self.loadmore?.view.isHidden = true
}
fileprivate func updateScrollViewConentInset() {
if self.refresher?.state == .initial {
self.refresher?.scrollViewDefaultInsets = contentInset
}
if self.loadmore?.state == .initial {
self.loadmore?.scrollViewDefaultInsets = contentInset
}
}
}
|
mit
|
2cc22d447fc6471037e95765d446d5c5
| 27.854167 | 119 | 0.640433 | 4.540984 | false | false | false | false |
zmian/xcore.swift
|
Sources/Xcore/Swift/Components/Observer.swift
|
1
|
4102
|
//
// Xcore
// Copyright © 2017 Xcore
// MIT license, see LICENSE file for details
//
import Foundation
open class Observers {
/// A list of all observers.
private var observers = [Observer]()
public init() {
// Must have a public init for client code to initialize this class.
}
// MARK: - Observer API
/// Register an observer.
open func observe<T>(owner: T, _ handler: @escaping () -> Void) where T: AnyObject, T: Equatable {
if let existingObserverIndex = observers.firstIndex(where: { $0 == owner }) {
observers[existingObserverIndex].handler = handler
} else {
observers.append(Observer(owner: owner, handler: handler))
}
}
/// Remove given observers.
open func remove<T>(_ owner: T) where T: AnyObject, T: Equatable {
guard let index = observers.firstIndex(where: { $0 == owner }) else {
return
}
observers.remove(at: index)
}
/// Remove all observers.
open func removeAll() {
observers.removeAll(keepingCapacity: false)
}
/// Removes all observers where the `owner` is deallocated.
open func flatten() {
for (index, observer) in observers.enumerated().reversed() where observer.owner == nil {
observers.remove(at: index)
}
}
open var count: Int {
flatten()
return observers.count
}
open var isEmpty: Bool {
flatten()
return observers.isEmpty
}
// MARK: - Notify API
/// A boolean value to determine whether the notifications should be sent.
/// This flag is checked before firing any notification calls to the registered
/// observers. The default value is `true`.
open var isNotificationEnabled = true
/// Invokes each registered observer if `oldValue` is different than `newValue`.
open func notifyIfNeeded<T>(_ oldValue: T, newValue: T) where T: Equatable {
guard oldValue != newValue else { return }
notify()
}
/// Invokes each registered observer if `oldValue` is different than `newValue`.
open func notifyIfNeeded<T>(_ oldValue: T?, newValue: T?) where T: Equatable {
guard oldValue != newValue else { return }
notify()
}
/// Invokes each registered observer if `oldValue` is different than `newValue`.
open func notifyIfNeeded<T>(_ oldValue: [T], newValue: [T]) where T: Equatable {
guard oldValue != newValue else { return }
notify()
}
/// Invokes each registered observer.
open func notify() {
flatten()
guard isNotificationEnabled else { return }
observers.forEach { $0.handler?() }
}
}
// MARK: - Observer
private final class Observer {
fileprivate let equals: (AnyObject) -> Bool
weak var owner: AnyObject?
var handler: (() -> Void)?
init<T>(owner: T, handler: @escaping () -> Void) where T: AnyObject, T: Equatable {
self.owner = owner
self.handler = handler
self.equals = { [weak owner] otherOwner in
guard let owner = owner else {
return false
}
return otherOwner as? T == owner
}
}
}
// MARK: - Observer: Equatable
extension Observer: Equatable {
static func ==(lhs: Observer, rhs: Observer) -> Bool {
guard lhs.owner != nil, let rhsOwner = rhs.owner else {
return false
}
return lhs.equals(rhsOwner)
}
static func == <T>(lhs: T, rhs: Observer) -> Bool where T: AnyObject, T: Equatable {
rhs.equals(lhs)
}
static func == <T>(lhs: Observer, rhs: T) -> Bool where T: AnyObject, T: Equatable {
lhs.equals(rhs)
}
static func == <T>(lhs: T?, rhs: Observer) -> Bool where T: AnyObject, T: Equatable {
guard let lhs = lhs else {
return false
}
return rhs.equals(lhs)
}
}
private func == <T>(lhs: Observer?, rhs: T) -> Bool where T: AnyObject, T: Equatable {
guard let lhs = lhs else {
return false
}
return lhs.equals(rhs)
}
|
mit
|
ac0a104292cddb0afa07e7c3174db5c0
| 27.089041 | 102 | 0.597171 | 4.372068 | false | false | false | false |
aschwaighofer/swift
|
test/stdlib/Accelerate_vDSPFourierTransform.swift
|
2
|
32206
|
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: rdar50301438
// REQUIRES: objc_interop
// UNSUPPORTED: OS=watchos
import StdlibUnittest
import Accelerate
var Accelerate_vDSPFourierTransformTests = TestSuite("Accelerate_vDSPFourierTransform")
//===----------------------------------------------------------------------===//
//
// vDSP discrete Fourier transform tests; single-precision
//
//===----------------------------------------------------------------------===//
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) {
let n = 2048
let tau: Float = .pi * 2
let frequencies: [Float] = [1, 5, 25, 30, 75, 100,
300, 500, 512, 1023]
let inputReal: [Float] = (0 ..< n).map { index in
frequencies.reduce(0) { accumulator, frequency in
let normalizedIndex = Float(index) / Float(n)
return accumulator + sin(normalizedIndex * frequency * tau)
}
}
let inputImag: [Float] = (0 ..< n).map { index in
frequencies.reduce(0) { accumulator, frequency in
let normalizedIndex = Float(index) / Float(n)
return accumulator + sin(normalizedIndex * 1/frequency * tau)
}
}
Accelerate_vDSPFourierTransformTests.test("vDSP/SinglePrecisionForwardComplexComplex") {
let fwdDFT = vDSP.DFT(count: n,
direction: .forward,
transformType: .complexComplex,
ofType: Float.self)!
var outputReal = [Float](repeating: 0, count: n)
var outputImag = [Float](repeating: 0, count: n)
fwdDFT.transform(inputReal: inputReal,
inputImaginary: inputImag,
outputReal: &outputReal,
outputImaginary: &outputImag)
// legacy...
let legacySetup = vDSP_DFT_zop_CreateSetup(nil,
vDSP_Length(n),
.FORWARD)!
var legacyOutputReal = [Float](repeating: -1, count: n)
var legacyOutputImag = [Float](repeating: -1, count: n)
vDSP_DFT_Execute(legacySetup,
inputReal,
inputImag,
&legacyOutputReal,
&legacyOutputImag)
expectTrue(outputReal.elementsEqual(legacyOutputReal))
expectTrue(outputImag.elementsEqual(legacyOutputImag))
let returnedResult = fwdDFT.transform(inputReal: inputReal,
inputImaginary: inputImag)
expectTrue(outputReal.elementsEqual(returnedResult.real))
expectTrue(outputImag.elementsEqual(returnedResult.imaginary))
}
Accelerate_vDSPFourierTransformTests.test("vDSP/SinglePrecisionInverseComplexComplex") {
let fwdDFT = vDSP.DFT(count: n,
direction: .inverse,
transformType: .complexComplex,
ofType: Float.self)!
var outputReal = [Float](repeating: 0, count: n)
var outputImag = [Float](repeating: 0, count: n)
fwdDFT.transform(inputReal: inputReal,
inputImaginary: inputImag,
outputReal: &outputReal,
outputImaginary: &outputImag)
// legacy...
let legacySetup = vDSP_DFT_zop_CreateSetup(nil,
vDSP_Length(n),
.INVERSE)!
var legacyOutputReal = [Float](repeating: -1, count: n)
var legacyOutputImag = [Float](repeating: -1, count: n)
vDSP_DFT_Execute(legacySetup,
inputReal,
inputImag,
&legacyOutputReal,
&legacyOutputImag)
expectTrue(outputReal.elementsEqual(legacyOutputReal))
expectTrue(outputImag.elementsEqual(legacyOutputImag))
let returnedResult = fwdDFT.transform(inputReal: inputReal,
inputImaginary: inputImag)
expectTrue(outputReal.elementsEqual(returnedResult.real))
expectTrue(outputImag.elementsEqual(returnedResult.imaginary))
}
Accelerate_vDSPFourierTransformTests.test("vDSP/SinglePrecisionForwardComplexReal") {
let fwdDFT = vDSP.DFT(count: n,
direction: .forward,
transformType: .complexReal,
ofType: Float.self)!
var outputReal = [Float](repeating: 0, count: n / 2)
var outputImag = [Float](repeating: 0, count: n / 2)
fwdDFT.transform(inputReal: inputReal,
inputImaginary: inputImag,
outputReal: &outputReal,
outputImaginary: &outputImag)
// legacy...
let legacySetup = vDSP_DFT_zrop_CreateSetup(nil,
vDSP_Length(n),
.FORWARD)!
var legacyOutputReal = [Float](repeating: -1, count: n / 2)
var legacyOutputImag = [Float](repeating: -1, count: n / 2)
vDSP_DFT_Execute(legacySetup,
inputReal,
inputImag,
&legacyOutputReal,
&legacyOutputImag)
expectTrue(outputReal.elementsEqual(legacyOutputReal))
expectTrue(outputImag.elementsEqual(legacyOutputImag))
let returnedResult = fwdDFT.transform(inputReal: inputReal,
inputImaginary: inputImag)
expectTrue(outputReal.elementsEqual(returnedResult.real))
expectTrue(outputImag.elementsEqual(returnedResult.imaginary))
}
Accelerate_vDSPFourierTransformTests.test("vDSP/SinglePrecisionInverseComplexReal") {
let fwdDFT = vDSP.DFT(count: n,
direction: .inverse,
transformType: .complexReal,
ofType: Float.self)!
var outputReal = [Float](repeating: 0, count: n / 2)
var outputImag = [Float](repeating: 0, count: n / 2)
fwdDFT.transform(inputReal: inputReal,
inputImaginary: inputImag,
outputReal: &outputReal,
outputImaginary: &outputImag)
// legacy...
let legacySetup = vDSP_DFT_zrop_CreateSetup(nil,
vDSP_Length(n),
.INVERSE)!
var legacyOutputReal = [Float](repeating: -1, count: n / 2)
var legacyOutputImag = [Float](repeating: -1, count: n / 2)
vDSP_DFT_Execute(legacySetup,
inputReal,
inputImag,
&legacyOutputReal,
&legacyOutputImag)
expectTrue(outputReal.elementsEqual(legacyOutputReal))
expectTrue(outputImag.elementsEqual(legacyOutputImag))
let returnedResult = fwdDFT.transform(inputReal: inputReal,
inputImaginary: inputImag)
expectTrue(outputReal.elementsEqual(returnedResult.real))
expectTrue(outputImag.elementsEqual(returnedResult.imaginary))
}
}
//===----------------------------------------------------------------------===//
//
// vDSP discrete Fourier transform tests; double-precision
//
//===----------------------------------------------------------------------===//
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) {
let n = 2048
let tau: Double = .pi * 2
let frequencies: [Double] = [1, 5, 25, 30, 75, 100,
300, 500, 512, 1023]
let inputReal: [Double] = (0 ..< n).map { index in
frequencies.reduce(0) { accumulator, frequency in
let normalizedIndex = Double(index) / Double(n)
return accumulator + sin(normalizedIndex * frequency * tau)
}
}
let inputImag: [Double] = (0 ..< n).map { index in
frequencies.reduce(0) { accumulator, frequency in
let normalizedIndex = Double(index) / Double(n)
return accumulator + sin(normalizedIndex * 1/frequency * tau)
}
}
Accelerate_vDSPFourierTransformTests.test("vDSP/DoublePrecisionForwardComplexComplex") {
let fwdDFT = vDSP.DFT(count: n,
direction: .forward,
transformType: .complexComplex,
ofType: Double.self)!
var outputReal = [Double](repeating: 0, count: n)
var outputImag = [Double](repeating: 0, count: n)
fwdDFT.transform(inputReal: inputReal,
inputImaginary: inputImag,
outputReal: &outputReal,
outputImaginary: &outputImag)
// legacy...
let legacySetup = vDSP_DFT_zop_CreateSetupD(nil,
vDSP_Length(n),
.FORWARD)!
var legacyOutputReal = [Double](repeating: -1, count: n)
var legacyOutputImag = [Double](repeating: -1, count: n)
vDSP_DFT_ExecuteD(legacySetup,
inputReal,
inputImag,
&legacyOutputReal,
&legacyOutputImag)
expectTrue(outputReal.elementsEqual(legacyOutputReal))
expectTrue(outputImag.elementsEqual(legacyOutputImag))
let returnedResult = fwdDFT.transform(inputReal: inputReal,
inputImaginary: inputImag)
expectTrue(outputReal.elementsEqual(returnedResult.real))
expectTrue(outputImag.elementsEqual(returnedResult.imaginary))
}
Accelerate_vDSPFourierTransformTests.test("vDSP/DoublePrecisionInverseComplexComplex") {
let fwdDFT = vDSP.DFT(count: n,
direction: .inverse,
transformType: .complexComplex,
ofType: Double.self)!
var outputReal = [Double](repeating: 0, count: n)
var outputImag = [Double](repeating: 0, count: n)
fwdDFT.transform(inputReal: inputReal,
inputImaginary: inputImag,
outputReal: &outputReal,
outputImaginary: &outputImag)
// legacy...
let legacySetup = vDSP_DFT_zop_CreateSetupD(nil,
vDSP_Length(n),
.INVERSE)!
var legacyOutputReal = [Double](repeating: -1, count: n)
var legacyOutputImag = [Double](repeating: -1, count: n)
vDSP_DFT_ExecuteD(legacySetup,
inputReal,
inputImag,
&legacyOutputReal,
&legacyOutputImag)
expectTrue(outputReal.elementsEqual(legacyOutputReal))
expectTrue(outputImag.elementsEqual(legacyOutputImag))
let returnedResult = fwdDFT.transform(inputReal: inputReal,
inputImaginary: inputImag)
expectTrue(outputReal.elementsEqual(returnedResult.real))
expectTrue(outputImag.elementsEqual(returnedResult.imaginary))
}
Accelerate_vDSPFourierTransformTests.test("vDSP/DoublePrecisionForwardComplexReal") {
let fwdDFT = vDSP.DFT(count: n,
direction: .forward,
transformType: .complexReal,
ofType: Double.self)!
var outputReal = [Double](repeating: 0, count: n / 2)
var outputImag = [Double](repeating: 0, count: n / 2)
fwdDFT.transform(inputReal: inputReal,
inputImaginary: inputImag,
outputReal: &outputReal,
outputImaginary: &outputImag)
// legacy...
let legacySetup = vDSP_DFT_zrop_CreateSetupD(nil,
vDSP_Length(n),
.FORWARD)!
var legacyOutputReal = [Double](repeating: -1, count: n / 2)
var legacyOutputImag = [Double](repeating: -1, count: n / 2)
vDSP_DFT_ExecuteD(legacySetup,
inputReal,
inputImag,
&legacyOutputReal,
&legacyOutputImag)
expectTrue(outputReal.elementsEqual(legacyOutputReal))
expectTrue(outputImag.elementsEqual(legacyOutputImag))
let returnedResult = fwdDFT.transform(inputReal: inputReal,
inputImaginary: inputImag)
expectTrue(outputReal.elementsEqual(returnedResult.real))
expectTrue(outputImag.elementsEqual(returnedResult.imaginary))
}
Accelerate_vDSPFourierTransformTests.test("vDSP/DoublePrecisionInverseComplexReal") {
let fwdDFT = vDSP.DFT(count: n,
direction: .inverse,
transformType: .complexReal,
ofType: Double.self)!
var outputReal = [Double](repeating: 0, count: n / 2)
var outputImag = [Double](repeating: 0, count: n / 2)
fwdDFT.transform(inputReal: inputReal,
inputImaginary: inputImag,
outputReal: &outputReal,
outputImaginary: &outputImag)
// legacy...
let legacySetup = vDSP_DFT_zrop_CreateSetupD(nil,
vDSP_Length(n),
.INVERSE)!
var legacyOutputReal = [Double](repeating: -1, count: n / 2)
var legacyOutputImag = [Double](repeating: -1, count: n / 2)
vDSP_DFT_ExecuteD(legacySetup,
inputReal,
inputImag,
&legacyOutputReal,
&legacyOutputImag)
expectTrue(outputReal.elementsEqual(legacyOutputReal))
expectTrue(outputImag.elementsEqual(legacyOutputImag))
let returnedResult = fwdDFT.transform(inputReal: inputReal,
inputImaginary: inputImag)
expectTrue(outputReal.elementsEqual(returnedResult.real))
expectTrue(outputImag.elementsEqual(returnedResult.imaginary))
}
}
//===----------------------------------------------------------------------===//
//
// vDSP Fast Fourier Transform Tests
//
//===----------------------------------------------------------------------===//
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) {
Accelerate_vDSPFourierTransformTests.test("vDSP/2DSinglePrecision") {
let width = 256
let height = 256
let pixelCount = width * height
let n = pixelCount / 2
let pixels: [Float] = (0 ..< pixelCount).map { i in
return abs(sin(Float(i) * 0.001 * 2))
}
var sourceImageReal = [Float](repeating: 0, count: n)
var sourceImageImaginary = [Float](repeating: 0, count: n)
sourceImageReal.withUnsafeMutableBufferPointer { sourceImageRealPtr in
sourceImageImaginary.withUnsafeMutableBufferPointer { sourceImageImaginaryPtr in
var sourceImage = DSPSplitComplex(realp: sourceImageRealPtr.baseAddress!,
imagp: sourceImageImaginaryPtr.baseAddress!)
pixels.withUnsafeBytes{
vDSP_ctoz([DSPComplex]($0.bindMemory(to: DSPComplex.self)), 2,
&sourceImage, 1,
vDSP_Length(pixels.count / 2))
}
// Create FFT2D object
let fft2D = vDSP.FFT2D(width: 256,
height: 256,
ofType: DSPSplitComplex.self)!
// New style transform
var transformedImageReal = [Float](repeating: 0,
count: n)
var transformedImageImaginary = [Float](repeating: 0,
count: n)
transformedImageReal.withUnsafeMutableBufferPointer { transformedImageRealPtr in
transformedImageImaginary.withUnsafeMutableBufferPointer { transformedImageImaginaryPtr in
var transformedImage = DSPSplitComplex(
realp: transformedImageRealPtr.baseAddress!,
imagp: transformedImageImaginaryPtr.baseAddress!)
fft2D.transform(input: sourceImage,
output: &transformedImage,
direction: .forward)
}
}
// Legacy 2D FFT
let log2n = vDSP_Length(log2(Float(width * height)))
let legacySetup = vDSP_create_fftsetup(
log2n,
FFTRadix(kFFTRadix2))!
var legacyTransformedImageReal = [Float](repeating: -1,
count: n)
var legacyTransformedImageImaginary = [Float](repeating: -1,
count: n)
legacyTransformedImageReal.withUnsafeMutableBufferPointer { legacyTransformedImageRealPtr in
legacyTransformedImageImaginary.withUnsafeMutableBufferPointer { legacyTransformedImageImaginaryPtr in
var legacyTransformedImage = DSPSplitComplex(
realp: legacyTransformedImageRealPtr.baseAddress!,
imagp: legacyTransformedImageImaginaryPtr.baseAddress!)
vDSP_fft2d_zrop(legacySetup,
&sourceImage, 1, 0,
&legacyTransformedImage, 1, 0,
vDSP_Length(log2(Float(width))),
vDSP_Length(log2(Float(height))),
FFTDirection(kFFTDirection_Forward))
}
}
expectTrue(transformedImageReal.elementsEqual(legacyTransformedImageReal))
expectTrue(transformedImageImaginary.elementsEqual(legacyTransformedImageImaginary))
}
}
}
Accelerate_vDSPFourierTransformTests.test("vDSP/2DDoublePrecision") {
let width = 256
let height = 256
let pixelCount = width * height
let n = pixelCount / 2
let pixels: [Double] = (0 ..< pixelCount).map { i in
return abs(sin(Double(i) * 0.001 * 2))
}
var sourceImageReal = [Double](repeating: 0, count: n)
var sourceImageImaginary = [Double](repeating: 0, count: n)
sourceImageReal.withUnsafeMutableBufferPointer { sourceImageRealPtr in
sourceImageImaginary.withUnsafeMutableBufferPointer { sourceImageImaginaryPtr in
var sourceImage = DSPDoubleSplitComplex(realp: sourceImageRealPtr.baseAddress!,
imagp: sourceImageImaginaryPtr.baseAddress!)
pixels.withUnsafeBytes{
vDSP_ctozD([DSPDoubleComplex]($0.bindMemory(to: DSPDoubleComplex.self)), 2,
&sourceImage, 1,
vDSP_Length(pixels.count / 2))
}
// Create FFT2D object
let fft2D = vDSP.FFT2D(width: 256,
height: 256,
ofType: DSPDoubleSplitComplex.self)!
// New style transform
var transformedImageReal = [Double](repeating: 0,
count: n)
var transformedImageImaginary = [Double](repeating: 0,
count: n)
transformedImageReal.withUnsafeMutableBufferPointer { transformedImageRealPtr in
transformedImageImaginary.withUnsafeMutableBufferPointer { transformedImageImaginaryPtr in
var transformedImage = DSPDoubleSplitComplex(
realp: transformedImageRealPtr.baseAddress!,
imagp: transformedImageImaginaryPtr.baseAddress!)
fft2D.transform(input: sourceImage,
output: &transformedImage,
direction: .forward)
}
}
// Legacy 2D FFT
let log2n = vDSP_Length(log2(Float(width * height)))
let legacySetup = vDSP_create_fftsetupD(
log2n,
FFTRadix(kFFTRadix2))!
var legacyTransformedImageReal = [Double](repeating: -1,
count: n)
var legacyTransformedImageImaginary = [Double](repeating: -1,
count: n)
legacyTransformedImageReal.withUnsafeMutableBufferPointer { legacyTransformedImageRealPtr in
legacyTransformedImageImaginary.withUnsafeMutableBufferPointer { legacyTransformedImageImaginaryPtr in
var legacyTransformedImage = DSPDoubleSplitComplex(
realp: legacyTransformedImageRealPtr.baseAddress!,
imagp: legacyTransformedImageImaginaryPtr.baseAddress!)
vDSP_fft2d_zropD(legacySetup,
&sourceImage, 1, 0,
&legacyTransformedImage, 1, 0,
vDSP_Length(log2(Float(width))),
vDSP_Length(log2(Float(height))),
FFTDirection(kFFTDirection_Forward))
}
}
expectTrue(transformedImageReal.elementsEqual(legacyTransformedImageReal))
expectTrue(transformedImageImaginary.elementsEqual(legacyTransformedImageImaginary))
}
}
}
Accelerate_vDSPFourierTransformTests.test("vDSP/1DSinglePrecision") {
let n = vDSP_Length(2048)
let frequencies: [Float] = [1, 5, 25, 30, 75, 100,
300, 500, 512, 1023]
let tau: Float = .pi * 2
let signal: [Float] = (0 ... n).map { index in
frequencies.reduce(0) { accumulator, frequency in
let normalizedIndex = Float(index) / Float(n)
return accumulator + sin(normalizedIndex * frequency * tau)
}
}
let halfN = Int(n / 2)
var forwardInputReal = [Float](repeating: 0, count: halfN)
var forwardInputImag = [Float](repeating: 0, count: halfN)
forwardInputReal.withUnsafeMutableBufferPointer { forwardInputRealPtr in
forwardInputImag.withUnsafeMutableBufferPointer { forwardInputImagPtr in
var forwardInput = DSPSplitComplex(realp: forwardInputRealPtr.baseAddress!,
imagp: forwardInputImagPtr.baseAddress!)
signal.withUnsafeBytes{
vDSP_ctoz([DSPComplex]($0.bindMemory(to: DSPComplex.self)), 2,
&forwardInput, 1,
vDSP_Length(signal.count / 2))
}
let log2n = vDSP_Length(log2(Float(n)))
// New API
guard let fft = vDSP.FFT(log2n: log2n,
radix: .radix2,
ofType: DSPSplitComplex.self) else {
fatalError("Can't create FFT.")
}
var outputReal = [Float](repeating: 0, count: halfN)
var outputImag = [Float](repeating: 0, count: halfN)
outputReal.withUnsafeMutableBufferPointer { outputRealPtr in
outputImag.withUnsafeMutableBufferPointer { outputImagPtr in
var forwardOutput = DSPSplitComplex(realp: outputRealPtr.baseAddress!,
imagp: outputImagPtr.baseAddress!)
fft.transform(input: forwardInput,
output: &forwardOutput,
direction: .forward)
}
}
// Legacy Style
let legacySetup = vDSP_create_fftsetup(log2n,
FFTRadix(kFFTRadix2))!
var legacyOutputReal = [Float](repeating: -1, count: halfN)
var legacyOutputImag = [Float](repeating: -1, count: halfN)
legacyOutputReal.withUnsafeMutableBufferPointer { legacyOutputRealPtr in
legacyOutputImag.withUnsafeMutableBufferPointer { legacyOutputImagPtr in
var legacyForwardOutput = DSPSplitComplex(realp: legacyOutputRealPtr.baseAddress!,
imagp: legacyOutputImagPtr.baseAddress!)
vDSP_fft_zrop(legacySetup,
&forwardInput, 1,
&legacyForwardOutput, 1,
log2n,
FFTDirection(kFFTDirection_Forward))
}
}
expectTrue(outputReal.elementsEqual(legacyOutputReal))
expectTrue(outputImag.elementsEqual(legacyOutputImag))
}
}
}
Accelerate_vDSPFourierTransformTests.test("vDSP/1DDoublePrecision") {
let n = vDSP_Length(2048)
let frequencies: [Double] = [1, 5, 25, 30, 75, 100,
300, 500, 512, 1023]
let tau: Double = .pi * 2
let signal: [Double] = (0 ... n).map { index in
frequencies.reduce(0) { accumulator, frequency in
let normalizedIndex = Double(index) / Double(n)
return accumulator + sin(normalizedIndex * frequency * tau)
}
}
let halfN = Int(n / 2)
var forwardInputReal = [Double](repeating: 0, count: halfN)
var forwardInputImag = [Double](repeating: 0, count: halfN)
forwardInputReal.withUnsafeMutableBufferPointer { forwardInputRealPtr in
forwardInputImag.withUnsafeMutableBufferPointer { forwardInputImagPtr in
var forwardInput = DSPDoubleSplitComplex(realp: forwardInputRealPtr.baseAddress!,
imagp: forwardInputImagPtr.baseAddress!)
signal.withUnsafeBytes{
vDSP_ctozD([DSPDoubleComplex]($0.bindMemory(to: DSPDoubleComplex.self)), 2,
&forwardInput, 1,
vDSP_Length(signal.count / 2))
}
let log2n = vDSP_Length(log2(Float(n)))
// New API
guard let fft = vDSP.FFT(log2n: log2n,
radix: .radix2,
ofType: DSPDoubleSplitComplex.self) else {
fatalError("Can't create FFT.")
}
var outputReal = [Double](repeating: 0, count: halfN)
var outputImag = [Double](repeating: 0, count: halfN)
outputReal.withUnsafeMutableBufferPointer { outputRealPtr in
outputImag.withUnsafeMutableBufferPointer { outputImagPtr in
var forwardOutput = DSPDoubleSplitComplex(realp: outputRealPtr.baseAddress!,
imagp: outputImagPtr.baseAddress!)
fft.transform(input: forwardInput,
output: &forwardOutput,
direction: .forward)
}
}
// Legacy Style
let legacySetup = vDSP_create_fftsetupD(log2n,
FFTRadix(kFFTRadix2))!
var legacyOutputReal = [Double](repeating: -1, count: halfN)
var legacyOutputImag = [Double](repeating: -1, count: halfN)
legacyOutputReal.withUnsafeMutableBufferPointer { legacyOutputRealPtr in
legacyOutputImag.withUnsafeMutableBufferPointer { legacyOutputImagPtr in
var legacyForwardOutput = DSPDoubleSplitComplex(realp: legacyOutputRealPtr.baseAddress!,
imagp: legacyOutputImagPtr.baseAddress!)
vDSP_fft_zropD(legacySetup,
&forwardInput, 1,
&legacyForwardOutput, 1,
log2n,
FFTDirection(kFFTDirection_Forward))
}
}
expectTrue(outputReal.elementsEqual(legacyOutputReal))
expectTrue(outputImag.elementsEqual(legacyOutputImag))
}
}
}
}
runAllTests()
|
apache-2.0
|
5d078b5db9d67457a2ec9a5872054275
| 43.422069 | 122 | 0.476992 | 6.708186 | false | false | false | false |
bparish628/iFarm-Health
|
iOS/iFarm-Health/Pods/Charts/Source/Charts/Data/Implementations/Standard/CombinedChartData.swift
|
4
|
7436
|
//
// CombinedChartData.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
open class CombinedChartData: BarLineScatterCandleBubbleChartData
{
fileprivate var _lineData: LineChartData!
fileprivate var _barData: BarChartData!
fileprivate var _scatterData: ScatterChartData!
fileprivate var _candleData: CandleChartData!
fileprivate var _bubbleData: BubbleChartData!
public override init()
{
super.init()
}
public override init(dataSets: [IChartDataSet]?)
{
super.init(dataSets: dataSets)
}
@objc open var lineData: LineChartData!
{
get
{
return _lineData
}
set
{
_lineData = newValue
notifyDataChanged()
}
}
@objc open var barData: BarChartData!
{
get
{
return _barData
}
set
{
_barData = newValue
notifyDataChanged()
}
}
@objc open var scatterData: ScatterChartData!
{
get
{
return _scatterData
}
set
{
_scatterData = newValue
notifyDataChanged()
}
}
@objc open var candleData: CandleChartData!
{
get
{
return _candleData
}
set
{
_candleData = newValue
notifyDataChanged()
}
}
@objc open var bubbleData: BubbleChartData!
{
get
{
return _bubbleData
}
set
{
_bubbleData = newValue
notifyDataChanged()
}
}
open override func calcMinMax()
{
_dataSets.removeAll()
_yMax = -Double.greatestFiniteMagnitude
_yMin = Double.greatestFiniteMagnitude
_xMax = -Double.greatestFiniteMagnitude
_xMin = Double.greatestFiniteMagnitude
_leftAxisMax = -Double.greatestFiniteMagnitude
_leftAxisMin = Double.greatestFiniteMagnitude
_rightAxisMax = -Double.greatestFiniteMagnitude
_rightAxisMin = Double.greatestFiniteMagnitude
let allData = self.allData
for data in allData
{
data.calcMinMax()
let sets = data.dataSets
_dataSets.append(contentsOf: sets)
if data.yMax > _yMax
{
_yMax = data.yMax
}
if data.yMin < _yMin
{
_yMin = data.yMin
}
if data.xMax > _xMax
{
_xMax = data.xMax
}
if data.xMin < _xMin
{
_xMin = data.xMin
}
if data.yMax > _leftAxisMax
{
_leftAxisMax = data.yMax
}
if data.yMin < _leftAxisMin
{
_leftAxisMin = data.yMin
}
if data.yMax > _rightAxisMax
{
_rightAxisMax = data.yMax
}
if data.yMin < _rightAxisMin
{
_rightAxisMin = data.yMin
}
}
}
/// - returns: All data objects in row: line-bar-scatter-candle-bubble if not null.
@objc open var allData: [ChartData]
{
var data = [ChartData]()
if lineData !== nil
{
data.append(lineData)
}
if barData !== nil
{
data.append(barData)
}
if scatterData !== nil
{
data.append(scatterData)
}
if candleData !== nil
{
data.append(candleData)
}
if bubbleData !== nil
{
data.append(bubbleData)
}
return data
}
@objc open func dataByIndex(_ index: Int) -> ChartData
{
return allData[index]
}
open func dataIndex(_ data: ChartData) -> Int?
{
return allData.index(of: data)
}
open override func removeDataSet(_ dataSet: IChartDataSet!) -> Bool
{
let datas = allData
var success = false
for data in datas
{
success = data.removeDataSet(dataSet)
if success
{
break
}
}
return success
}
open override func removeDataSetByIndex(_ index: Int) -> Bool
{
print("removeDataSet(index) not supported for CombinedData", terminator: "\n")
return false
}
open override func removeEntry(_ entry: ChartDataEntry, dataSetIndex: Int) -> Bool
{
print("removeEntry(entry, dataSetIndex) not supported for CombinedData", terminator: "\n")
return false
}
open override func removeEntry(xValue: Double, dataSetIndex: Int) -> Bool
{
print("removeEntry(xValue, dataSetIndex) not supported for CombinedData", terminator: "\n")
return false
}
open override func notifyDataChanged()
{
if _lineData !== nil
{
_lineData.notifyDataChanged()
}
if _barData !== nil
{
_barData.notifyDataChanged()
}
if _scatterData !== nil
{
_scatterData.notifyDataChanged()
}
if _candleData !== nil
{
_candleData.notifyDataChanged()
}
if _bubbleData !== nil
{
_bubbleData.notifyDataChanged()
}
super.notifyDataChanged() // recalculate everything
}
/// Get the Entry for a corresponding highlight object
///
/// - parameter highlight:
/// - returns: The entry that is highlighted
open override func entryForHighlight(_ highlight: Highlight) -> ChartDataEntry?
{
if highlight.dataIndex >= allData.count
{
return nil
}
let data = dataByIndex(highlight.dataIndex)
if highlight.dataSetIndex >= data.dataSetCount
{
return nil
}
// The value of the highlighted entry could be NaN - if we are not interested in highlighting a specific value.
let entries = data.getDataSetByIndex(highlight.dataSetIndex).entriesForXValue(highlight.x)
for e in entries
{
if e.y == highlight.y || highlight.y.isNaN
{
return e
}
}
return nil
}
/// Get dataset for highlight
///
/// - Parameter highlight: current highlight
/// - Returns: dataset related to highlight
@objc open func getDataSetByHighlight(_ highlight: Highlight) -> IChartDataSet!
{
if highlight.dataIndex >= allData.count
{
return nil
}
let data = dataByIndex(highlight.dataIndex)
if highlight.dataSetIndex >= data.dataSetCount
{
return nil
}
return data.dataSets[highlight.dataSetIndex]
}
}
|
apache-2.0
|
bd06c4f903194201fdcfdd38886e9950
| 22.681529 | 119 | 0.500538 | 5.582583 | false | false | false | false |
RMizin/PigeonMessenger-project
|
FalconMessenger/Settings/Menu/Appearance/AppearanceTextSizeTableViewCell.swift
|
1
|
1489
|
//
// AppearanceTextSizeTableViewCell.swift
// FalconMessenger
//
// Created by Roman Mizin on 3/30/19.
// Copyright © 2019 Roman Mizin. All rights reserved.
//
import UIKit
class AppearanceTextSizeTableViewCell: UITableViewCell {
var sliderView: UIIncrementSliderView!
fileprivate let userDefaultsManager = UserDefaultsManager()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .default, reuseIdentifier: reuseIdentifier)
backgroundColor = .clear
selectionStyle = .none
let currentValue = userDefaultsManager.currentFloatObjectState(for: userDefaultsManager.chatLogDefaultFontSizeID)
sliderView = UIIncrementSliderView(values: DefaultMessageTextFontSize.allFontSizes(), currentValue: currentValue)
sliderView.translatesAutoresizingMaskIntoConstraints = false
addSubview(sliderView)
sliderView.topAnchor.constraint(equalTo: topAnchor).isActive = true
if #available(iOS 11.0, *) {
sliderView.leftAnchor.constraint(equalTo: safeAreaLayoutGuide.leftAnchor).isActive = true
sliderView.rightAnchor.constraint(equalTo: safeAreaLayoutGuide.rightAnchor).isActive = true
} else {
sliderView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
sliderView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
}
sliderView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
gpl-3.0
|
9165e37da8540758ce1604488a98295a
| 37.153846 | 115 | 0.796371 | 4.441791 | false | false | false | false |
huangboju/Moots
|
Examples/UIScrollViewDemo/UIScrollViewDemo/Controllers/Sku/Model/GoodsModel.swift
|
1
|
6072
|
//
// GoodsModel.swift
// UIScrollViewDemo
//
// Created by 黄渊 on 2022/10/28.
// Copyright © 2022 伯驹 黄. All rights reserved.
//
import Foundation
struct Variant: Codable, Hashable {
let id: String
let name: String
let value: String
enum CodingKeys: String, CodingKey {
case id
case name
case value
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
id = try values.decodeIfPresent(String.self, forKey: .id) ?? ""
name = try values.decodeIfPresent(String.self, forKey: .name) ?? ""
value = try values.decodeIfPresent(String.self, forKey: .value) ?? ""
}
init(id: String = "", name: String = "", value: String = "") {
self.id = id
self.name = name
self.value = value
}
static func == (lhs: Variant, rhs: Variant) -> Bool {
return lhs.id == rhs.id &&
rhs.name == lhs.name &&
rhs.value == lhs.value
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
hasher.combine(name)
hasher.combine(value)
}
}
struct Variants: Codable {
let id: String
let name: String
let values: [String]
enum CodingKeys: String, CodingKey {
case id
case name
case values
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decodeIfPresent(String.self, forKey: .id) ?? ""
name = try container.decodeIfPresent(String.self, forKey: .name) ?? ""
values = try container.decodeIfPresent([String].self, forKey: .values) ?? []
}
}
class SpuExtension: Codable {
let activityFlag: String
enum CodingKeys: String, CodingKey {
case activityFlag
}
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
activityFlag = try values.decodeIfPresent(String.self, forKey: .activityFlag) ?? "0"
}
init() {
activityFlag = "0"
}
var dict: [String: Any] {
[CodingKeys.activityFlag.rawValue: activityFlag]
}
var isActivity: Bool {
return activityFlag == "1" ? true : false
}
}
class SkuGoods: Codable, Hashable {
enum Status: Int, Codable {
case normal = 1
// 售罄
case sellOut = 2
// 下架
case notSale = 3
}
let id: String
let image: String
let status: Status
let mainImage: String
let name: String
let price: String
let variants: [Variant]
let `extension`: SpuExtension
let title: String
public private(set) lazy var variantSet: Set<Variant> = {
return Set(variants)
}()
var isActivity: Bool {
`extension`.isActivity
}
enum CodingKeys: String, CodingKey {
case id
case image
case status = "item_status"
case mainImage = "main_image"
case name
case price
case variants
case `extension` = "extension"
case title
}
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
id = try values.decodeIfPresent(String.self, forKey: .id) ?? ""
image = try values.decodeIfPresent(String.self, forKey: .image) ?? ""
status = try values.decodeIfPresent(Status.self, forKey: .status) ?? .normal
mainImage = try values.decodeIfPresent(String.self, forKey: .mainImage) ?? ""
name = try values.decodeIfPresent(String.self, forKey: .name) ?? ""
price = try values.decodeIfPresent(String.self, forKey: .price) ?? ""
variants = try values.decodeIfPresent([Variant].self, forKey: .variants) ?? []
`extension` = try values.decodeIfPresent(SpuExtension.self, forKey: .extension) ?? SpuExtension()
title = try values.decodeIfPresent(String.self, forKey: .title) ?? ""
}
init() {
id = ""
image = ""
status = .normal
mainImage = ""
name = ""
price = ""
variants = []
`extension` = SpuExtension()
title = ""
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
hasher.combine(variants)
}
static func == (lhs: SkuGoods, rhs: SkuGoods) -> Bool {
lhs.id == rhs.id && lhs.variants == rhs.variants
}
}
extension SkuGoods: CustomStringConvertible {
var description: String {
name
}
}
class GoodsAllVariant: Codable {
let goodsList: [SkuGoods]
let variants: [Variants]
let spuId: String
enum CodingKeys: String, CodingKey {
case goodsList = "content"
case variants = "sku_list"
case spuId = "spu_id"
}
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
goodsList = try values.decodeIfPresent([SkuGoods].self, forKey: .goodsList) ?? []
variants = try values.decodeIfPresent([Variants].self, forKey: .variants) ?? []
spuId = try values.decodeIfPresent(String.self, forKey: .spuId) ?? ""
}
init() {
goodsList = []
variants = []
spuId = ""
}
}
class GoodsModel: Codable {
let goodsAllVariant: GoodsAllVariant
enum CodingKeys: String, CodingKey {
case goodsAllVariant = "goods_all_variant"
}
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
goodsAllVariant = try values.decodeIfPresent(GoodsAllVariant.self, forKey: .goodsAllVariant) ?? GoodsAllVariant()
}
public var goodsList: [SkuGoods] {
goodsAllVariant.goodsList
}
public var variants: [Variants] {
goodsAllVariant.variants
}
public private(set) lazy var goodsMap: [String: SkuGoods] = {
var result: [String: SkuGoods] = [:]
goodsList.forEach { result[$0.id] = $0 }
return result
}()
}
|
mit
|
36a4905ec468e1f2304cbf31cd7369c1
| 25.090517 | 121 | 0.599703 | 4.114888 | false | false | false | false |
huangboju/Moots
|
Examples/Lumia/Lumia/Frame/Segue.swift
|
1
|
3205
|
//
// Segue.swift
// Lumia
//
// Created by xiAo_Ju on 2019/12/31.
// Copyright © 2019 黄伯驹. All rights reserved.
//
import UIKit
import SafariServices
extension UIViewController {
public func show<C: UIViewController>(_ segue: Segue, animated: Bool = true, handle: ((C) -> Void)? = nil) {
let vc: UIViewController
switch segue {
case let .controller(c):
vc = c
case let .segue(c):
vc = c.init()
case let .modal(c):
vc = c.init()
if let c = vc as? C {
handle?(c)
}
vc.modalPresentationStyle = .fullScreen
showDetailViewController(vc, sender: nil)
return
case let .web(url):
showDetailViewController(SFSafariViewController(url: URL(string: url)!), sender: nil)
return
case let .scheme(s):
guard let url = URL(string: s.scheme) else { return }
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
return
case let .storyboard(id):
let storyboard = UIStoryboard(name: "Main", bundle: nil)
vc = storyboard.instantiateViewController(withIdentifier: id)
default:
return
}
if let c = vc as? C {
handle?(c)
}
vc.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(vc, animated: animated)
}
}
public enum Segue {
case none
// 用SegueRow,把创建对象延迟到跳转时
case segue(UIViewController.Type)
case modal(UIViewController.Type)
case controller(UIViewController)
case web(String)
case scheme(Scheme)
case storyboard(String)
}
extension Segue: CustomStringConvertible {
public var description: String {
switch self {
case .none:
return "none"
case let .segue(dest):
return "\(dest)"
case let .controller(vc):
return vc.description
case let .web(str):
return "\(str)"
case let .scheme(s):
return "\(s.scheme)"
case let .modal(dest):
return "\(dest)"
case let .storyboard(id):
return id
}
}
}
// https://github.com/cyanzhong/app-tutorials/blob/master/schemes.md
// http://www.jianshu.com/p/bb3f42fdbc31
public enum Scheme {
case plain(String)
case tel(String)
case wifi
case appStore
case mail(String)
case notification
var scheme: String {
let scheme: String
switch self {
case let .plain(s):
scheme = s
case let .tel(s):
scheme = "tel://" + s
case .wifi:
scheme = "App-Prefs:root=WIFI"
case .appStore:
scheme = "itms-apps://itunes.apple.com/cn/app/id\(1111)?mt=8"
case let .mail(s):
scheme = "mailto://\(s)"
case .notification:
scheme = "App-Prefs:root=NOTIFICATIONS_ID"
}
return scheme
}
}
|
mit
|
453cc008c8b6f7d9e5b63eaf32cb2733
| 26.824561 | 112 | 0.546028 | 4.309783 | false | false | false | false |
kylef/Stencil
|
Tests/StencilTests/ContextSpec.swift
|
1
|
2466
|
import Spectre
@testable import Stencil
import XCTest
final class ContextTests: XCTestCase {
func testContextSubscripting() {
describe("Context Subscripting") {
var context = Context()
$0.before {
context = Context(dictionary: ["name": "Kyle"])
}
$0.it("allows you to get a value via subscripting") {
try expect(context["name"] as? String) == "Kyle"
}
$0.it("allows you to set a value via subscripting") {
context["name"] = "Katie"
try expect(context["name"] as? String) == "Katie"
}
$0.it("allows you to remove a value via subscripting") {
context["name"] = nil
try expect(context["name"]).to.beNil()
}
$0.it("allows you to retrieve a value from a parent") {
try context.push {
try expect(context["name"] as? String) == "Kyle"
}
}
$0.it("allows you to override a parent's value") {
try context.push {
context["name"] = "Katie"
try expect(context["name"] as? String) == "Katie"
}
}
}
}
func testContextRestoration() {
describe("Context Restoration") {
var context = Context()
$0.before {
context = Context(dictionary: ["name": "Kyle"])
}
$0.it("allows you to pop to restore previous state") {
context.push {
context["name"] = "Katie"
}
try expect(context["name"] as? String) == "Kyle"
}
$0.it("allows you to remove a parent's value in a level") {
try context.push {
context["name"] = nil
try expect(context["name"]).to.beNil()
}
try expect(context["name"] as? String) == "Kyle"
}
$0.it("allows you to push a dictionary and run a closure then restoring previous state") {
var didRun = false
try context.push(dictionary: ["name": "Katie"]) {
didRun = true
try expect(context["name"] as? String) == "Katie"
}
try expect(didRun).to.beTrue()
try expect(context["name"] as? String) == "Kyle"
}
$0.it("allows you to flatten the context contents") {
try context.push(dictionary: ["test": "abc"]) {
let flattened = context.flatten()
try expect(flattened.count) == 2
try expect(flattened["name"] as? String) == "Kyle"
try expect(flattened["test"] as? String) == "abc"
}
}
}
}
}
|
bsd-2-clause
|
49e3709f085983360cead663cba85cbf
| 26.098901 | 96 | 0.545418 | 3.908082 | false | true | false | false |
WenchaoD/FSPagerView
|
FSPageViewExample-Swift/FSPagerViewExample/TransformerExampleViewController.swift
|
1
|
5033
|
//
// TransformerExampleViewController.swift
// FSPagerViewExample
//
// Created by Wenchao Ding on 09/01/2017.
// Copyright © 2017 Wenchao Ding. All rights reserved.
//
import UIKit
class TransformerExampleViewController: UIViewController,FSPagerViewDataSource,FSPagerViewDelegate, UITableViewDataSource,UITableViewDelegate {
fileprivate let imageNames = ["1.jpg","2.jpg","3.jpg","4.jpg","5.jpg","6.jpg","7.jpg"]
fileprivate let transformerNames = ["cross fading", "zoom out", "depth", "linear", "overlap", "ferris wheel", "inverted ferris wheel", "coverflow", "cubic"]
fileprivate let transformerTypes: [FSPagerViewTransformerType] = [.crossFading,
.zoomOut,
.depth,
.linear,
.overlap,
.ferrisWheel,
.invertedFerrisWheel,
.coverFlow,
.cubic]
fileprivate var typeIndex = 0 {
didSet {
let type = self.transformerTypes[typeIndex]
self.pagerView.transformer = FSPagerViewTransformer(type:type)
switch type {
case .crossFading, .zoomOut, .depth:
self.pagerView.itemSize = FSPagerView.automaticSize
self.pagerView.decelerationDistance = 1
case .linear, .overlap:
let transform = CGAffineTransform(scaleX: 0.6, y: 0.75)
self.pagerView.itemSize = self.pagerView.frame.size.applying(transform)
self.pagerView.decelerationDistance = FSPagerView.automaticDistance
case .ferrisWheel, .invertedFerrisWheel:
self.pagerView.itemSize = CGSize(width: 180, height: 140)
self.pagerView.decelerationDistance = FSPagerView.automaticDistance
case .coverFlow:
self.pagerView.itemSize = CGSize(width: 220, height: 170)
self.pagerView.decelerationDistance = FSPagerView.automaticDistance
case .cubic:
let transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
self.pagerView.itemSize = self.pagerView.frame.size.applying(transform)
self.pagerView.decelerationDistance = 1
}
}
}
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var pagerView: FSPagerView! {
didSet {
self.pagerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "cell")
self.typeIndex = 0
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let index = self.typeIndex
self.typeIndex = index // Manually trigger didSet
}
// MARK:- UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
@available(iOS 2.0, *)
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.transformerNames.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
cell.textLabel?.text = self.transformerNames[indexPath.row]
cell.accessoryType = indexPath.row == self.typeIndex ? .checkmark : .none
return cell
}
// MARK:- UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
self.typeIndex = indexPath.row
if let visibleRows = tableView.indexPathsForVisibleRows {
tableView.reloadRows(at: visibleRows, with: .automatic)
}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Transformers"
}
// MARK:- FSPagerViewDataSource
public func numberOfItems(in pagerView: FSPagerView) -> Int {
return imageNames.count
}
public func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)
cell.imageView?.image = UIImage(named: self.imageNames[index])
cell.imageView?.contentMode = .scaleAspectFill
cell.imageView?.clipsToBounds = true
return cell
}
func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
pagerView.deselectItem(at: index, animated: true)
pagerView.scrollToItem(at: index, animated: true)
}
}
|
mit
|
95e6e7f9879861746ea7543a3d2edcc5
| 42.756522 | 160 | 0.584261 | 5.511501 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.