repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
HassanEskandari/Eureka | Source/Rows/PickerInlineRow.swift | 6 | 3213 | // PickerInlineRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
open class PickerInlineCell<T: Equatable> : Cell<T>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func setup() {
super.setup()
accessoryType = .none
editingAccessoryType = .none
}
open override func update() {
super.update()
selectionStyle = row.isDisabled ? .none : .default
}
open override func didSelect() {
super.didSelect()
row.deselect()
}
}
// MARK: PickerInlineRow
open class _PickerInlineRow<T> : Row<PickerInlineCell<T>>, NoValueDisplayTextConformance where T: Equatable {
public typealias InlineRow = PickerRow<T>
open var options = [T]()
open var noValueDisplayText: String?
required public init(tag: String?) {
super.init(tag: tag)
}
}
/// A generic inline row where the user can pick an option from a picker view which shows and hides itself automatically
public final class PickerInlineRow<T> : _PickerInlineRow<T>, RowType, InlineRowType where T: Equatable {
required public init(tag: String?) {
super.init(tag: tag)
onExpandInlineRow { cell, row, _ in
let color = cell.detailTextLabel?.textColor
row.onCollapseInlineRow { cell, _, _ in
cell.detailTextLabel?.textColor = color
}
cell.detailTextLabel?.textColor = cell.tintColor
}
}
public override func customDidSelect() {
super.customDidSelect()
if !isDisabled {
toggleInlineRow()
}
}
public func setupInlineRow(_ inlineRow: InlineRow) {
inlineRow.options = self.options
inlineRow.displayValueFor = self.displayValueFor
inlineRow.cell.height = { UITableViewAutomaticDimension }
}
}
| mit | 6cbc6de280dcbf079687c4a0e3664cfb | 33.548387 | 120 | 0.687208 | 4.767062 | false | false | false | false |
jhwayne/Brew | DNApp/Spring/SpringTextView.swift | 1 | 1639 | //
// SpringTextView.swift
// SpringApp
//
// Created by James Tang on 15/1/15.
// Copyright (c) 2015 Meng To. All rights reserved.
//
import UIKit
public class SpringTextView: UITextView, Springable {
@IBInspectable public var autostart: Bool = false
@IBInspectable public var autohide: Bool = false
@IBInspectable public var animation: String = ""
@IBInspectable public var force: CGFloat = 1
@IBInspectable public var delay: CGFloat = 0
@IBInspectable public var duration: CGFloat = 0.7
@IBInspectable public var damping: CGFloat = 0.7
@IBInspectable public var velocity: CGFloat = 0.7
@IBInspectable public var x: CGFloat = 0
@IBInspectable public var y: CGFloat = 0
@IBInspectable public var scaleX: CGFloat = 1
@IBInspectable public var scaleY: CGFloat = 1
@IBInspectable public var rotate: CGFloat = 0
@IBInspectable public var curve: String = ""
public var opacity: CGFloat = 1
public var animateFrom: Bool = false
lazy private var spring : Spring = Spring(self)
override public func awakeFromNib() {
super.awakeFromNib()
self.spring.customAwakeFromNib()
}
override public func didMoveToWindow() {
super.didMoveToWindow()
self.spring.customDidMoveToWindow()
}
public func animate() {
self.spring.animate()
}
public func animateNext(completion: () -> ()) {
self.spring.animateNext(completion)
}
public func animateTo() {
self.spring.animateTo()
}
public func animateToNext(completion: () -> ()) {
self.spring.animateToNext(completion)
}
} | mit | 4f6988503ecd3d19ba02eaa66b948101 | 27.77193 | 53 | 0.670531 | 4.552778 | false | false | false | false |
pixyzehn/SnowFalling | SnowFalling/SnowFallingView.swift | 1 | 4294 | //
// SnowFallingView.swift
// SnowFalling
//
// Created by pixyzehn on 2/11/15.
// Copyright (c) 2015 pixyzehn. All rights reserved.
//
import UIKit
public let kDefaultFlakeFileName = "snowflake"
public let kDefaultFlakesCount = 200
public let kDefaultFlakeWidth: Float = 40.0
public let kDefaultFlakeHeight: Float = 46.0
public let kDefaultMinimumSize: Float = 0.4
public let kDefaultMaximumSize: Float = 0.8
public let kDefaultAnimationDurationMin: Float = 6.0
public let kDefaultAnimationDurationMax: Float = 12.0
public class SnowFallingView: UIView {
public var flakesCount: Int?
public var flakeFileName: String?
public var flakeWidth: Float?
public var flakeHeight: Float?
public var flakeMinimumSize: Float?
public var flakeMaximumSize: Float?
public var animationDurationMin: Float?
public var animationDurationMax: Float?
public var flakesArray: [UIImageView]?
override public init(frame: CGRect) {
super.init(frame: frame)
clipsToBounds = true
self.flakeFileName = kDefaultFlakeFileName
self.flakesCount = kDefaultFlakesCount
self.flakeWidth = kDefaultFlakeWidth
self.flakeHeight = kDefaultFlakeHeight
self.flakeMinimumSize = kDefaultMinimumSize
self.flakeMaximumSize = kDefaultMaximumSize
self.animationDurationMin = kDefaultAnimationDurationMin
self.animationDurationMax = kDefaultAnimationDurationMax
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public func createFlakes() {
flakesArray = [UIImageView]()
var flakeImage: UIImage = UIImage(named: flakeFileName!)!
for var i: Int = 0; i < flakesCount!; i++ {
var vz: Float = 1.0 * Float(rand()) / Float(RAND_MAX)
vz = vz < flakeMinimumSize! ? flakeMinimumSize! : vz
vz = vz > flakeMaximumSize! ? flakeMaximumSize! : vz
var vw = flakeWidth! * vz
var vh = flakeHeight! * vz
var vx = Float(frame.size.width) * Float(rand()) / Float(RAND_MAX)
var vy = Float(frame.size.height) * 1.5 * Float(rand()) / Float(RAND_MAX)
vy += Float(frame.size.height)
vx -= vw
var imageFrame = CGRectMake(CGFloat(vx), CGFloat(vy), CGFloat(vw), CGFloat(vh))
var imageView: UIImageView = UIImageView(image: flakeImage)
imageView.frame = imageFrame
imageView.userInteractionEnabled = false
flakesArray?.append(imageView)
addSubview(imageView)
}
}
public func startSnow() {
if flakesArray? == nil {
createFlakes()
}
backgroundColor = UIColor.clearColor()
var rotAnimation: CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.y")
rotAnimation.repeatCount = Float.infinity
rotAnimation.autoreverses = false
rotAnimation.toValue = 6.28318531
var theAnimation: CABasicAnimation = CABasicAnimation(keyPath: "transform.translation.y")
theAnimation.repeatCount = Float.infinity
theAnimation.autoreverses = false
for v: UIImageView in flakesArray! {
var p: CGPoint = v.center
let startypos = p.y
let endypos = frame.size.height
p.y = endypos
v.center = p
var timeInterval: Float = (animationDurationMax! - animationDurationMin!) * Float(rand()) / Float(RAND_MAX)
theAnimation.duration = CFTimeInterval(timeInterval + animationDurationMin!)
theAnimation.fromValue = -startypos
v.layer.addAnimation(theAnimation, forKey: "transform.translation.y")
rotAnimation.duration = CFTimeInterval(timeInterval)
v.layer.addAnimation(rotAnimation, forKey: "transform.rotation.y")
}
}
public func stopSnow() {
for v: UIImageView in flakesArray! {
v.layer.removeAllAnimations()
}
flakesArray = nil
}
deinit {
}
}
| mit | b4b7291c8ac5f4698784eb15844f3d0b | 35.700855 | 119 | 0.615044 | 4.57295 | false | false | false | false |
LoopKit/LoopKit | LoopKitUI/Views/ChartTableViewCell.swift | 1 | 1747 | //
// ChartTableViewCell.swift
// Naterade
//
// Created by Nathan Racklyeft on 2/19/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import UIKit
public final class ChartTableViewCell: UITableViewCell {
@IBOutlet weak var chartContentView: ChartContainerView!
@IBOutlet weak var titleLabel: UILabel?
@IBOutlet weak var subtitleLabel: UILabel?
@IBOutlet weak var rightArrowHint: UIImageView? {
didSet {
rightArrowHint?.isHidden = !doesNavigate
}
}
public var doesNavigate: Bool = true {
didSet {
rightArrowHint?.isHidden = !doesNavigate
}
}
public override func prepareForReuse() {
super.prepareForReuse()
doesNavigate = true
chartContentView.chartGenerator = nil
}
public func reloadChart() {
chartContentView.reloadChart()
}
public func setChartGenerator(generator: ((CGRect) -> UIView?)?) {
chartContentView.chartGenerator = generator
}
public func setTitleLabelText(label: String?) {
titleLabel?.text = label
}
public func removeTitleLabelText() {
titleLabel?.text?.removeAll()
}
public func setSubtitleLabel(label: String?) {
subtitleLabel?.text = label
}
public func removeSubtitleLabelText() {
subtitleLabel?.text?.removeAll()
}
public func setTitleTextColor(color: UIColor) {
titleLabel?.textColor = color
}
public func setSubtitleTextColor(color: UIColor) {
subtitleLabel?.textColor = color
}
public func setAlpha(alpha: CGFloat) {
titleLabel?.alpha = alpha
subtitleLabel?.alpha = alpha
}
}
| mit | 2d43534b3a5d4d12daeee7772c1d3e68 | 22.594595 | 70 | 0.631157 | 5.017241 | false | false | false | false |
gottesmm/swift | test/Generics/invalid.swift | 5 | 2680 | // RUN: %target-typecheck-verify-swift
func bet() where A : B {} // expected-error {{'where' clause cannot be attached to a non-generic declaration}}
typealias gimel where A : B // expected-error {{'where' clause cannot be attached to a non-generic declaration}}
// expected-error@-1 {{expected '=' in typealias declaration}}
class dalet where A : B {} // expected-error {{'where' clause cannot be attached to a non-generic declaration}}
protocol he where A : B { // expected-error {{'where' clause cannot be attached to a protocol declaration}}
associatedtype vav where A : B // expected-error {{'where' clause cannot be attached to an associated type declaration}}
}
struct Lunch<T> {
struct Dinner<U> {
var leftovers: T
var transformation: (T) -> U
}
}
class Deli<Spices> {
class Pepperoni {}
struct Sausage {}
}
struct Pizzas<Spices> {
class NewYork {
}
class DeepDish {
}
}
class HotDog {
}
struct Pepper {}
struct ChiliFlakes {}
func eatDinnerConcrete(d: Pizzas<ChiliFlakes>.NewYork,
t: Deli<ChiliFlakes>.Pepperoni) {
}
func eatDinnerConcrete(d: Pizzas<Pepper>.DeepDish,
t: Deli<Pepper>.Pepperoni) {
}
func badDiagnostic1() {
_ = Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDog>( // expected-error {{expression type 'Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDog>' is ambiguous without more context}}
leftovers: Pizzas<ChiliFlakes>.NewYork(),
transformation: { _ in HotDog() })
}
func badDiagnostic2() {
let firstCourse = Pizzas<ChiliFlakes>.NewYork()
var dinner = Lunch<Pizzas<ChiliFlakes>.NewYork>.Dinner<HotDog>(
leftovers: firstCourse,
transformation: { _ in HotDog() })
let topping = Deli<Pepper>.Pepperoni()
eatDinnerConcrete(d: firstCourse, t: topping)
// expected-error@-1 {{cannot invoke 'eatDinnerConcrete' with an argument list of type '(d: Pizzas<ChiliFlakes>.NewYork, t: Deli<Pepper>.Pepperoni)'}}
// expected-note@-2 {{overloads for 'eatDinnerConcrete' exist with these partially matching parameter lists: (d: Pizzas<ChiliFlakes>.NewYork, t: Deli<ChiliFlakes>.Pepperoni), (d: Pizzas<Pepper>.DeepDish, t: Deli<Pepper>.Pepperoni)}}
}
// Real error is that we cannot infer the generic parameter from context
func takesAny(_ a: Any) {}
func badDiagnostic3() {
takesAny(Deli.self) // expected-error {{argument type 'Deli<_>.Type' does not conform to expected type 'Any'}}
}
// Crash with missing nested type inside concrete type
class OuterGeneric<T> {
class InnerGeneric<U> where U:OuterGeneric<T.NoSuchType> {
// expected-error@-1 {{'NoSuchType' is not a member type of 'T'}}
func method() {
_ = method
}
}
}
| apache-2.0 | f12fbe254db7acc60a2be9b9b15d394f | 28.450549 | 234 | 0.689925 | 3.867244 | false | false | false | false |
Fenrikur/ef-app_ios | EurofurenceTests/Presenter Tests/Dealers/Presenter Tests/WhenBindingDealerSearchResultGroupHeading_DealersPresenterShould.swift | 1 | 820 | @testable import Eurofurence
import EurofurenceModel
import XCTest
class WhenBindingDealerSearchResultGroupHeading_DealersPresenterShould: XCTestCase {
func testBindTheGroupHeadingOntoTheComponent() {
let groups = [DealersGroupViewModel].random
let randomGroup = groups.randomElement()
let expected = randomGroup.element.title
let searchViewModel = CapturingDealersSearchViewModel(dealerGroups: groups)
let interactor = FakeDealersInteractor(searchViewModel: searchViewModel)
let context = DealersPresenterTestBuilder().with(interactor).build()
context.simulateSceneDidLoad()
let component = context.makeAndBindComponentHeader(forSearchResultGroupAt: randomGroup.index)
XCTAssertEqual(expected, component.capturedDealersGroupTitle)
}
}
| mit | d234e0c5c1d0ed28e3e367512ee89a81 | 40 | 101 | 0.77561 | 5.857143 | false | true | false | false |
qbalsdon/br.cd | brcd/Pods/RSBarcodes_Swift/Source/RSCode93Generator.swift | 1 | 3849 | //
// RSCode93Generator.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/11/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
// http://www.barcodeisland.com/code93.phtml
public class RSCode93Generator: RSAbstractCodeGenerator, RSCheckDigitGenerator {
let CODE93_ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%abcd*"
let CODE93_PLACEHOLDER_STRING = "abcd";
let CODE93_CHARACTER_ENCODINGS = [
"100010100",
"101001000",
"101000100",
"101000010",
"100101000",
"100100100",
"100100010",
"101010000",
"100010010",
"100001010",
"110101000",
"110100100",
"110100010",
"110010100",
"110010010",
"110001010",
"101101000",
"101100100",
"101100010",
"100110100",
"100011010",
"101011000",
"101001100",
"101000110",
"100101100",
"100010110",
"110110100",
"110110010",
"110101100",
"110100110",
"110010110",
"110011010",
"101101100",
"101100110",
"100110110",
"100111010",
"100101110",
"111010100",
"111010010",
"111001010",
"101101110",
"101110110",
"110101110",
"100100110",
"111011010",
"111010110",
"100110010",
"101011110"
]
func encodeCharacterString(characterString:String) -> String {
return CODE93_CHARACTER_ENCODINGS[CODE93_ALPHABET_STRING.location(characterString)]
}
override public func isValid(contents: String) -> Bool {
if contents.length() > 0 && contents == contents.uppercaseString {
for i in 0..<contents.length() {
if CODE93_ALPHABET_STRING.location(contents[i]) == NSNotFound {
return false
}
if CODE93_PLACEHOLDER_STRING.location(contents[i]) != NSNotFound {
return false
}
}
return true
}
return false
}
override public func initiator() -> String {
return self.encodeCharacterString("*")
}
override public func terminator() -> String {
// With the termination bar: 1
return self.encodeCharacterString("*") + "1"
}
override public func barcode(contents: String) -> String {
var barcode = ""
for character in contents.characters {
barcode += self.encodeCharacterString(String(character))
}
let checkDigits = self.checkDigit(contents)
for character in checkDigits.characters {
barcode += self.encodeCharacterString(String(character))
}
return barcode
}
// MARK: RSCheckDigitGenerator
public func checkDigit(contents: String) -> String {
// Weighted sum += value * weight
// The first character
var sum = 0
for i in 0..<contents.length() {
let character = contents[contents.length() - i - 1]
let characterValue = CODE93_ALPHABET_STRING.location(character)
sum += characterValue * (i % 20 + 1)
}
var checkDigits = ""
checkDigits += CODE93_ALPHABET_STRING[sum % 47]
// The second character
sum = 0
let newContents = contents + checkDigits
for i in 0..<newContents.length() {
let character = newContents[newContents.length() - i - 1]
let characterValue = CODE93_ALPHABET_STRING.location(character)
sum += characterValue * (i % 15 + 1)
}
checkDigits += CODE93_ALPHABET_STRING[sum % 47]
return checkDigits
}
}
| mit | f1a413c04b024889f08867d00f439732 | 27.301471 | 91 | 0.546895 | 4.434332 | false | false | false | false |
JGiola/swift | test/Reflection/typeref_decoding_imported.swift | 2 | 5190 | // XFAIL: OS=windows-msvc
// SR-12893
// XFAIL: OS=openbsd
// RUN: %empty-directory(%t)
// RUN: %target-build-swift %S/Inputs/ImportedTypes.swift %S/Inputs/ImportedTypesOther.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -o %t/%target-library-name(TypesToReflect) -I %S/Inputs
// RUN: %target-swift-reflection-dump -binary-filename %t/%target-library-name(TypesToReflect) | %FileCheck %s --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-%target-cpu
// ... now, test single-frontend mode with multi-threaded LLVM emission:
// RUN: %empty-directory(%t)
// RUN: %target-build-swift %S/Inputs/ImportedTypes.swift %S/Inputs/ImportedTypesOther.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -o %t/%target-library-name(TypesToReflect) -I %S/Inputs -whole-module-optimization -num-threads 2
// RUN: %target-swift-reflection-dump -binary-filename %t/%target-library-name(TypesToReflect) | %FileCheck %s --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-%target-cpu
// UNSUPPORTED: CPU=arm64e
// UNSUPPORTED: OS=linux-android, OS=linux-androideabi
// CHECK-32: FIELDS:
// CHECK-32: =======
// CHECK-32: TypesToReflect.HasCTypes
// CHECK-32: ------------------------
// CHECK-32: mcs: __C.MyCStruct
// CHECK-32: (struct __C.MyCStruct)
// CHECK-32: mce: __C.MyCEnum
// CHECK-32: (struct __C.MyCEnum)
// CHECK-32: __C.MyCStruct
// CHECK-32: -------------
// CHECK-32: i: Swift.Int32
// CHECK-32: (struct Swift.Int32)
// CHECK-32: ip: Swift.Optional<Swift.UnsafeMutablePointer<Swift.Int32>>
// CHECK-32: (bound_generic_enum Swift.Optional
// CHECK-32: (bound_generic_struct Swift.UnsafeMutablePointer
// CHECK-32: (struct Swift.Int32)))
// CHECK-32: c: Swift.Int8
// CHECK-32: (struct Swift.Int8)
// CHECK-32: TypesToReflect.AlsoHasCTypes
// CHECK-32: ----------------------------
// CHECK-32: mcu: __C.MyCUnion
// CHECK-32: (struct __C.MyCUnion)
// CHECK-32: mcsbf: __C.MyCStructWithBitfields
// CHECK-32: (struct __C.MyCStructWithBitfields)
// CHECK-32: ASSOCIATED TYPES:
// CHECK-32: =================
// CHECK-32: BUILTIN TYPES:
// CHECK-32: ==============
// CHECK-32-LABEL: - __C.MyCStruct:
// CHECK-32: Size: 12
// CHECK-32: Alignment: 4
// CHECK-32: Stride: 12
// CHECK-32: NumExtraInhabitants: 0
// CHECK-32: BitwiseTakable: 1
// CHECK-32-LABEL: - __C.MyCEnum:
// CHECK-32: Size: 4
// CHECK-32: Alignment: 4
// CHECK-32: Stride: 4
// CHECK-32: NumExtraInhabitants: 0
// CHECK-32: BitwiseTakable: 1
// CHECK-32-LABEL: - __C.MyCUnion:
// CHECK-32: Size: 4
// CHECK-32: Alignment: 4
// CHECK-32: Stride: 4
// CHECK-32: NumExtraInhabitants: 0
// CHECK-32: BitwiseTakable: 1
// CHECK-i386-LABEL: - __C.MyCStructWithBitfields:
// CHECK-i386: Size: 4
// CHECK-i386: Alignment: 4
// CHECK-i386: Stride: 4
// CHECK-i386: NumExtraInhabitants: 0
// CHECK-i386: BitwiseTakable: 1
// CHECK-arm-LABEL: - __C.MyCStructWithBitfields:
// CHECK-arm: Size: 2
// CHECK-arm: Alignment: 1
// CHECK-arm: Stride: 2
// CHECK-arm: NumExtraInhabitants: 0
// CHECK-arm: BitwiseTakable: 1
// CHECK-arm64_32-LABEL: - __C.MyCStructWithBitfields:
// CHECK-arm64_32: Size: 2
// CHECK-arm64_32: Alignment: 1
// CHECK-arm64_32: Stride: 2
// CHECK-arm64_32: NumExtraInhabitants: 0
// CHECK-32: CAPTURE DESCRIPTORS:
// CHECK-32: ====================
// CHECK-64: FIELDS:
// CHECK-64: =======
// CHECK-64: TypesToReflect.HasCTypes
// CHECK-64: ------------------------
// CHECK-64: mcs: __C.MyCStruct
// CHECK-64: (struct __C.MyCStruct)
// CHECK-64: mce: __C.MyCEnum
// CHECK-64: (struct __C.MyCEnum)
// CHECK-64: mcu: __C.MyCUnion
// CHECK-64: (struct __C.MyCUnion)
// CHECK-64: __C.MyCStruct
// CHECK-64: -------------
// CHECK-64: i: Swift.Int32
// CHECK-64: (struct Swift.Int32)
// CHECK-64: ip: Swift.Optional<Swift.UnsafeMutablePointer<Swift.Int32>>
// CHECK-64: (bound_generic_enum Swift.Optional
// CHECK-64: (bound_generic_struct Swift.UnsafeMutablePointer
// CHECK-64: (struct Swift.Int32)))
// CHECK-64: c: Swift.Int8
// CHECK-64: (struct Swift.Int8)
// CHECK-64: TypesToReflect.AlsoHasCTypes
// CHECK-64: ----------------------------
// CHECK-64: mcu: __C.MyCUnion
// CHECK-64: (struct __C.MyCUnion)
// CHECK-64: mcsbf: __C.MyCStructWithBitfields
// CHECK-64: (struct __C.MyCStructWithBitfields)
// CHECK-64: ASSOCIATED TYPES:
// CHECK-64: =================
// CHECK-64: BUILTIN TYPES:
// CHECK-64: ==============
// CHECK-64-LABEL: - __C.MyCStruct:
// CHECK-64: Size: 24
// CHECK-64: Alignment: 8
// CHECK-64: Stride: 24
// CHECK-64: NumExtraInhabitants: 0
// CHECK-64: BitwiseTakable: 1
// CHECK-64-LABEL: - __C.MyCEnum:
// CHECK-64: Size: 4
// CHECK-64: Alignment: 4
// CHECK-64: Stride: 4
// CHECK-64: NumExtraInhabitants: 0
// CHECK-64: BitwiseTakable: 1
// CHECK-64-LABEL: - __C.MyCUnion:
// CHECK-64: Size: 8
// CHECK-64: Alignment: 8
// CHECK-64: Stride: 8
// CHECK-64: NumExtraInhabitants: 0
// CHECK-64: BitwiseTakable: 1
// CHECK-64-LABEL: - __C.MyCStructWithBitfields:
// CHECK-64: Size: 4
// CHECK-64: Alignment: 4
// CHECK-64: Stride: 4
// CHECK-64: NumExtraInhabitants: 0
// CHECK-64: BitwiseTakable: 1
// CHECK-64: CAPTURE DESCRIPTORS:
// CHECK-64: ====================
| apache-2.0 | a4d3ee522da72259a847def0b05870b7 | 28.827586 | 263 | 0.655106 | 3.052941 | false | false | false | false |
ontouchstart/swift3-playground | Learn to Code 1.playgroundbook/Contents/Chapters/Document7.playgroundchapter/Pages/Challenge4.playgroundpage/Sources/SetUp.swift | 1 | 2793 | //
// SetUp.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
import Foundation
// MARK: Globals
let width = Int(arc4random_uniform(4)) + 5
let height = Int(arc4random_uniform(4)) + 4
// we can't use this dressed world because the size of this world is random
// let world = loadGridWorld(named: "7.7")
let world = GridWorld(columns: 9, rows: 8)
public let actor = Actor()
public func playgroundPrologue() {
removeAllNodes()
placeRandomItems()
// Must be called in `playgroundPrologue()` to update with the current page contents.
registerAssessment(world, assessment: assessmentPoint)
//// ----
// Any items added or removed after this call will be animated.
finalizeWorldBuilding(for: world) {
realizeRandomItems()
}
//// ----
world.place(actor, facing: north, at: Coordinate(column: 0, row: 0))
}
// Called from LiveView.swift to initially set the LiveView.
public func presentWorld() {
setUpLiveViewWith(world)
}
// MARK: Epilogue
public func removeAllNodes() {
world.removeNodes(at: world.allPossibleCoordinates)
}
public func playgroundEpilogue() {
sendCommands(for: world)
}
func placeRandomItems() {
let block = Block()
let coordinates = world.coordinates(inColumns: 0...8, intersectingRows: 0...7)
for coordinate in coordinates {
world.place(RandomNode(resembling: block), at: coordinate)
}
}
func realizeRandomItems() {
for i in 1...(width-2) {
for j in 1...(height-2) {
world.placeWater(at: [Coordinate(column: i, row: j)])
}
}
for i in 0...(height-2) {
world.placeBlocks(at: [Coordinate(column: 0, row: i)])
}
for i in 0...(width-2) {
world.placeBlocks(at: [Coordinate(column: i, row: height - 1)])
world.placeBlocks(at: [Coordinate(column: i, row: height - 1)])
}
for i in 1...(height-1) {
world.placeBlocks(at: [Coordinate(column: width - 1, row: i)])
world.placeBlocks(at: [Coordinate(column: width - 1, row: i)])
world.placeBlocks(at: [Coordinate(column: width - 1, row: i)])
}
for i in 1...(width-1) {
world.placeBlocks(at: [Coordinate(column: i, row: 0)])
world.placeBlocks(at: [Coordinate(column: i, row: 0)])
world.placeBlocks(at: [Coordinate(column: i, row: 0)])
world.placeBlocks(at: [Coordinate(column: i, row: 0)])
}
world.place(Stair(), facing: south, at: Coordinate(column: 0, row: height - 2))
world.place(Stair(), facing: west, at: Coordinate(column: width - 2, row: height - 1))
world.place(Stair(), facing: north, at: Coordinate(column: width-1, row: 1))
world.place(nodeOfType: Switch.self, at: [Coordinate(column: 1, row: 0)])
}
| mit | eeadbe7c09025205645f7614eb91d992 | 26.653465 | 90 | 0.627999 | 3.539924 | false | false | false | false |
Ricky-Choi/AppUIKit | AppUIKit/View/AUIBarButtonItem.swift | 1 | 8070 | //
// AUIBarButtonItem.swift
// AppUIKit
//
// Created by ricky on 2016. 12. 5..
// Copyright © 2016년 appcid. All rights reserved.
//
import Cocoa
public enum AUIBarButtonSystemItem: Int, CustomStringConvertible {
case done
case cancel
case edit
case save
case add
case flexibleSpace
case fixedSpace
case compose
case reply
case action
case organize
case bookmarks
case search
case refresh
case stop
case camera
case trash
case play
case pause
case rewind
case fastForward
case undo
case redo
case pageCurl
var title: String? {
switch self {
case .done: return "Done"
case .cancel: return "Cancel"
case .edit: return "Edit"
case .save: return "Save"
case .undo: return "Undo"
case .redo: return "Redo"
default: return nil
}
}
public var description: String {
switch self {
case .done: return "Done"
case .cancel: return "Cancel"
case .edit: return "Edit"
case .save: return "Save"
case .add: return "Add"
case .flexibleSpace: return "Flexible Space"
case .fixedSpace: return "Fixed Space"
case .compose: return "Compose"
case .reply: return "Reply"
case .action: return "Action"
case .organize: return "Organize"
case .bookmarks: return "Bookmarks"
case .search: return "Search"
case .refresh: return "Refresh"
case .stop: return "Stop"
case .camera: return "Camera"
case .trash: return "Trash"
case .play: return "Play"
case .pause: return "Pause"
case .rewind: return "Rewind"
case .fastForward: return "Fast Forward"
case .undo: return "Undo"
case .redo: return "Redo"
case .pageCurl: return "Page Curl"
}
}
var image: NSImage? {
switch self {
case .done, .cancel, .edit, .save, .undo, .redo, .flexibleSpace, .fixedSpace, .pageCurl:
return nil
case .add: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonNew)
case .compose: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonCompose)
case .reply: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonReply)
case .action: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonAction)
case .organize: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonOrganize)
case .bookmarks: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonBookmarks)
case .search: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonSearch)
case .refresh: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonRefresh)
case .stop: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonStop)
case .camera: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonCamera)
case .trash: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonTrash)
case .play: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonPlay)
case .pause: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonPause)
case .rewind: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonRewind)
case .fastForward: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonFastForward)
}
}
var landscapeImage: NSImage? {
switch self {
case .done, .cancel, .edit, .save, .undo, .redo, .flexibleSpace, .fixedSpace, .pageCurl:
return nil
case .add: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonNewLandscape)
case .compose: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonComposeLandscape)
case .reply: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonReplyLandscape)
case .action: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonActionSmall)
case .organize: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonOrganizeLandscape)
case .bookmarks: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonBookmarksLandscape)
case .search: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonSearchLandscape)
case .refresh: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonRefreshLandscape)
case .stop: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonStopLandscape)
case .camera: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonCameraSmall)
case .trash: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonTrashLandscape)
case .play: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonPlayLandscape)
case .pause: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonPauseLandscape)
case .rewind: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonRewindLandscape)
case .fastForward: return Bundle(for: AUIBarButtonItem.self).image(forResource: .barButtonFastForwardLandscape)
}
}
var canAttachNavigationBar: Bool {
switch self {
case .done, .cancel, .edit, .save, .add, .compose, .reply, .action, .organize, .bookmarks, .search, .refresh, .stop, .camera, .trash, .play, .pause, .rewind, .fastForward, .undo, .redo:
return true
case .flexibleSpace, .fixedSpace, .pageCurl:
return false
}
}
var canAttachToolbar: Bool {
switch self {
case .done, .cancel, .edit, .save, .add, .compose, .reply, .action, .organize, .bookmarks, .search, .refresh, .stop, .camera, .trash, .play, .pause, .rewind, .fastForward, .undo, .redo, .flexibleSpace, .fixedSpace:
return true
case .pageCurl:
return false
}
}
var isSpace: Bool {
switch self {
case .flexibleSpace, .fixedSpace:
return true
case .done, .cancel, .edit, .save, .add, .compose, .reply, .action, .organize, .bookmarks, .search, .refresh, .stop, .camera, .trash, .play, .pause, .rewind, .fastForward, .undo, .redo, .pageCurl:
return false
}
}
}
public enum AUIBarButtonItemStyle: Int {
case plain
case done
}
open class AUIBarButtonItem: AUIBarItem {
convenience public init(barButtonSystemItem systemItem: AUIBarButtonSystemItem, target: Any?, action: Selector?) {
self.init()
if let image = systemItem.image {
self.image = image
}
if let landscapeImage = systemItem.landscapeImage {
self.landscapeImagePhone = landscapeImage
}
self.title = systemItem.title
self.target = target as AnyObject?
self.action = action
}
convenience public init(customView: NSView) {
self.init()
self.customView = customView
}
convenience public init(title: String?, image: NSImage? = nil, landscapeImagePhone: NSImage? = nil, style: AUIBarButtonItemStyle = .plain, target: Any?, action: Selector?) {
self.init()
self.title = title
self.image = image
self.landscapeImagePhone = landscapeImagePhone
self.style = style
self.target = target as AnyObject?
self.action = action
}
public weak var target: AnyObject?
public var action: Selector?
public private(set) var style: AUIBarButtonItemStyle = .plain
public var possibleTitles: Set<String>?
public private(set) var width: CGFloat = 0
public private(set) var customView: NSView?
public var tintColor: NSColor?
weak var button: AUIButton?
}
| mit | 49b5c69ac1d3555d9190cdb5dc3ea7fc | 39.949239 | 222 | 0.660593 | 4.332438 | false | false | false | false |
dave256/SwiftPlaygrounds | old-Structures.playground/Contents.swift | 1 | 2073 | //: ## Structures (value types and no inheritance)
struct Person {
var firstName: String
var lastName = ""
// no func in front of init
// if initialized all instance variables during declaration (as did with lastName above), a default initializer is automatically created
init(firstName: String, lastName:String) {
// use self if parameter has same name as instance variable, otherwisee
// self is unnecessary
self.firstName = firstName
self.lastName = lastName
}
// methods
// if a structure method, changes the instance variables, need to mark as mutating
mutating func change(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
}
//: CustomStringConvertible is a protocol
//: requires description property to be implemented which is used to produce a String representation
//: called when using print(aPerson) or String(describing: aPerson)
extension Person: CustomStringConvertible {
var description : String {
return "\(firstName) \(lastName)"
}
}
//: generally should implement Equatable protocol for struct types
//: do not need to write != as compiler translates a != b to !(a == b)
extension Person: Equatable {
// in newer versions of Swift, compiler generates code for you as long as each instance variable itself is equatable
// public static func ==(lhs: Person, rhs: Person) -> Bool {
// return lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName
// }
}
var me = Person(firstName: "Dave", lastName: "Reed")
//: uses description property to convert to a String
print(me)
me.change(firstName: "David", lastName: "Reed")
print(me)
//: because these are value types, dave and me refer to different data so changing one does not change the other
var dave = me
if dave == me {
print("dave == me")
}
dave.firstName = "Dave"
if dave != me {
print("after mutating, dave != me")
}
//: still has David as firstName
print(me)
me
//: has Dave as firstName
print(dave)
dave
| mit | 454918368c72b214e7fd4ebe800cf718 | 27.39726 | 140 | 0.688857 | 4.327766 | false | false | false | false |
tottakai/RxSwift | Tests/PerformanceTests/PerformanceTools.swift | 8 | 6215 | //
// PerformanceTools.swift
// Tests
//
// Created by Krunoslav Zaher on 9/27/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if os(Linux)
import Dispatch
#endif
fileprivate var mallocFunctions: [(@convention(c) (UnsafeMutablePointer<_malloc_zone_t>?, Int) -> UnsafeMutableRawPointer?)] = []
fileprivate var allocCalls: Int64 = 0
fileprivate var bytesAllocated: Int64 = 0
func call0(_ p: UnsafeMutablePointer<_malloc_zone_t>?, size: Int) -> UnsafeMutableRawPointer? {
OSAtomicIncrement64Barrier(&allocCalls)
OSAtomicAdd64Barrier(Int64(size), &bytesAllocated)
#if ALLOC_HOOK
allocation()
#endif
return mallocFunctions[0](p, size)
}
func call1(_ p: UnsafeMutablePointer<_malloc_zone_t>?, size: Int) -> UnsafeMutableRawPointer? {
OSAtomicIncrement64Barrier(&allocCalls)
OSAtomicAdd64Barrier(Int64(size), &bytesAllocated)
#if ALLOC_HOOK
allocation()
#endif
return mallocFunctions[1](p, size)
}
func call2(_ p: UnsafeMutablePointer<_malloc_zone_t>?, size: Int) -> UnsafeMutableRawPointer? {
OSAtomicIncrement64Barrier(&allocCalls)
OSAtomicAdd64Barrier(Int64(size), &bytesAllocated)
#if ALLOC_HOOK
allocation()
#endif
return mallocFunctions[2](p, size)
}
var proxies: [(@convention(c) (UnsafeMutablePointer<_malloc_zone_t>?, Int) -> UnsafeMutableRawPointer?)] = [call0, call1, call2]
func getMemoryInfo() -> (bytes: Int64, allocations: Int64) {
return (bytesAllocated, allocCalls)
}
fileprivate var registeredMallocHooks = false
func registerMallocHooks() {
if registeredMallocHooks {
return
}
registeredMallocHooks = true
var _zones: UnsafeMutablePointer<vm_address_t>?
var count: UInt32 = 0
// malloc_zone_print(nil, 1)
let res = malloc_get_all_zones(mach_task_self_, nil, &_zones, &count)
assert(res == 0)
_zones?.withMemoryRebound(to: UnsafeMutablePointer<malloc_zone_t>.self, capacity: Int(count), { zones in
assert(Int(count) <= proxies.count)
for i in 0 ..< Int(count) {
let zoneArray = zones.advanced(by: i)
let name = malloc_get_zone_name(zoneArray.pointee)
var zone = zoneArray.pointee.pointee
//print(String.fromCString(name))
assert(name != nil)
mallocFunctions.append(zone.malloc)
zone.malloc = proxies[i]
let protectSize = vm_size_t(MemoryLayout<malloc_zone_t>.size) * vm_size_t(count)
if true {
zoneArray.withMemoryRebound(to: vm_address_t.self, capacity: Int(protectSize), { addressPointer in
let res = vm_protect(mach_task_self_, addressPointer.pointee, protectSize, 0, PROT_READ | PROT_WRITE)
assert(res == 0)
})
}
zoneArray.pointee.pointee = zone
if true {
let res = vm_protect(mach_task_self_, _zones!.pointee, protectSize, 0, PROT_READ)
assert(res == 0)
}
}
})
}
// MARK: Benchmark tools
let NumberOfIterations = 10000
class A {
let _0 = 0
let _1 = 0
let _2 = 0
let _3 = 0
let _4 = 0
let _5 = 0
let _6 = 0
}
class B {
var a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]
}
let numberOfObjects = 1000000
let aliveAtTheEnd = numberOfObjects / 10
fileprivate var objects: [AnyObject] = []
func fragmentMemory() {
objects = [AnyObject](repeating: A(), count: aliveAtTheEnd)
for _ in 0 ..< numberOfObjects {
objects[Int(arc4random_uniform(UInt32(aliveAtTheEnd)))] = arc4random_uniform(2) == 0 ? A() : B()
}
}
func approxValuePerIteration(_ total: Int) -> UInt64 {
return UInt64(round(Double(total) / Double(NumberOfIterations)))
}
func approxValuePerIteration(_ total: UInt64) -> UInt64 {
return UInt64(round(Double(total) / Double(NumberOfIterations)))
}
func measureTime(_ work: () -> ()) -> UInt64 {
var timebaseInfo: mach_timebase_info = mach_timebase_info()
let res = mach_timebase_info(&timebaseInfo)
assert(res == 0)
let start = mach_absolute_time()
for _ in 0 ..< NumberOfIterations {
work()
}
let timeInNano = (mach_absolute_time() - start) * UInt64(timebaseInfo.numer) / UInt64(timebaseInfo.denom)
return approxValuePerIteration(timeInNano) / 1000
}
func measureMemoryUsage(work: () -> ()) -> (bytesAllocated: UInt64, allocations: UInt64) {
let (bytes, allocations) = getMemoryInfo()
for _ in 0 ..< NumberOfIterations {
work()
}
let (bytesAfter, allocationsAfter) = getMemoryInfo()
return (approxValuePerIteration(bytesAfter - bytes), approxValuePerIteration(allocationsAfter - allocations))
}
fileprivate var fragmentedMemory = false
func compareTwoImplementations(benchmarkTime: Bool, benchmarkMemory: Bool, first: () -> (), second: () -> ()) {
if !fragmentedMemory {
print("Fragmenting memory ...")
fragmentMemory()
print("Benchmarking ...")
fragmentedMemory = true
}
// first warm up to keep it fair
let time1: UInt64
let time2: UInt64
if benchmarkTime {
first()
second()
time1 = measureTime(first)
time2 = measureTime(second)
}
else {
time1 = 0
time2 = 0
}
let memory1: (bytesAllocated: UInt64, allocations: UInt64)
let memory2: (bytesAllocated: UInt64, allocations: UInt64)
if benchmarkMemory {
registerMallocHooks()
first()
second()
memory1 = measureMemoryUsage(work: first)
memory2 = measureMemoryUsage(work: second)
}
else {
memory1 = (0, 0)
memory2 = (0, 0)
}
// this is good enough
print(String(format: "#1 implementation %8d bytes %4d allocations %5d useconds", arguments: [
memory1.bytesAllocated,
memory1.allocations,
time1
]))
print(String(format: "#2 implementation %8d bytes %4d allocations %5d useconds", arguments: [
memory2.bytesAllocated,
memory2.allocations,
time2
]))
}
| mit | aa4c52e69acd8c8da8f1a713cc978b76 | 27.117647 | 129 | 0.628902 | 3.864428 | false | false | false | false |
JGiola/swift-corelibs-foundation | Foundation/RunLoop.swift | 2 | 5558 | // 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
//
import CoreFoundation
#if os(macOS) || os(iOS)
internal let kCFRunLoopEntry = CFRunLoopActivity.entry.rawValue
internal let kCFRunLoopBeforeTimers = CFRunLoopActivity.beforeTimers.rawValue
internal let kCFRunLoopBeforeSources = CFRunLoopActivity.beforeSources.rawValue
internal let kCFRunLoopBeforeWaiting = CFRunLoopActivity.beforeWaiting.rawValue
internal let kCFRunLoopAfterWaiting = CFRunLoopActivity.afterWaiting.rawValue
internal let kCFRunLoopExit = CFRunLoopActivity.exit.rawValue
internal let kCFRunLoopAllActivities = CFRunLoopActivity.allActivities.rawValue
#endif
public struct RunLoopMode : RawRepresentable, Equatable, Hashable {
public private(set) var rawValue: String
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public init(rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return rawValue.hashValue
}
public static func ==(_ lhs: RunLoopMode, _ rhs: RunLoopMode) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension RunLoopMode {
public static let defaultRunLoopMode = RunLoopMode("kCFRunLoopDefaultMode")
public static let commonModes = RunLoopMode("kCFRunLoopCommonModes")
// Use this instead of .rawValue._cfObject; this will allow CFRunLoop to use pointer equality internally.
fileprivate var _cfStringUniquingKnown: CFString {
if self == .defaultRunLoopMode {
return kCFRunLoopDefaultMode
} else if self == .commonModes {
return kCFRunLoopCommonModes
} else {
return rawValue._cfObject
}
}
}
internal func _NSRunLoopNew(_ cf: CFRunLoop) -> Unmanaged<AnyObject> {
let rl = Unmanaged<RunLoop>.passRetained(RunLoop(cfObject: cf))
return unsafeBitCast(rl, to: Unmanaged<AnyObject>.self) // this retain is balanced on the other side of the CF fence
}
open class RunLoop: NSObject {
internal var _cfRunLoop : CFRunLoop!
internal static var _mainRunLoop : RunLoop = {
return RunLoop(cfObject: CFRunLoopGetMain())
}()
internal init(cfObject : CFRunLoop) {
_cfRunLoop = cfObject
}
open class var current: RunLoop {
return _CFRunLoopGet2(CFRunLoopGetCurrent()) as! RunLoop
}
open class var main: RunLoop {
return _CFRunLoopGet2(CFRunLoopGetMain()) as! RunLoop
}
open var currentMode: RunLoopMode? {
if let mode = CFRunLoopCopyCurrentMode(_cfRunLoop) {
return RunLoopMode(mode._swiftObject)
} else {
return nil
}
}
open func getCFRunLoop() -> CFRunLoop {
return _cfRunLoop
}
open func add(_ timer: Timer, forMode mode: RunLoopMode) {
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer._cfObject, mode._cfStringUniquingKnown)
}
open func add(_ aPort: Port, forMode mode: RunLoopMode) {
NSUnimplemented()
}
open func remove(_ aPort: Port, forMode mode: RunLoopMode) {
NSUnimplemented()
}
open func limitDate(forMode mode: RunLoopMode) -> Date? {
if _cfRunLoop !== CFRunLoopGetCurrent() {
return nil
}
let modeArg = mode.rawValue._cfObject
CFRunLoopRunInMode(modeArg, -10.0, true) /* poll run loop to fire ready timers and performers, as used to be done here */
if _CFRunLoopFinished(_cfRunLoop, modeArg) {
return nil
}
let nextTimerFireAbsoluteTime = CFRunLoopGetNextTimerFireDate(CFRunLoopGetCurrent(), modeArg)
if (nextTimerFireAbsoluteTime == 0) {
return Date.distantFuture
}
return Date(timeIntervalSinceReferenceDate: nextTimerFireAbsoluteTime)
}
open func acceptInput(forMode mode: String, before limitDate: Date) {
if _cfRunLoop !== CFRunLoopGetCurrent() {
return
}
CFRunLoopRunInMode(mode._cfObject, limitDate.timeIntervalSinceReferenceDate - CFAbsoluteTimeGetCurrent(), true)
}
}
extension RunLoop {
public func run() {
while run(mode: .defaultRunLoopMode, before: Date.distantFuture) { }
}
public func run(until limitDate: Date) {
while run(mode: .defaultRunLoopMode, before: limitDate) && limitDate.timeIntervalSinceReferenceDate > CFAbsoluteTimeGetCurrent() { }
}
public func run(mode: RunLoopMode, before limitDate: Date) -> Bool {
if _cfRunLoop !== CFRunLoopGetCurrent() {
return false
}
let modeArg = mode._cfStringUniquingKnown
if _CFRunLoopFinished(_cfRunLoop, modeArg) {
return false
}
let limitTime = limitDate.timeIntervalSinceReferenceDate
let ti = limitTime - CFAbsoluteTimeGetCurrent()
CFRunLoopRunInMode(modeArg, ti, true)
return true
}
public func perform(inModes modes: [RunLoopMode], block: @escaping () -> Void) {
CFRunLoopPerformBlock(getCFRunLoop(), (modes.map { $0._cfStringUniquingKnown })._cfObject, block)
}
public func perform(_ block: @escaping () -> Void) {
perform(inModes: [.defaultRunLoopMode], block: block)
}
}
| apache-2.0 | 7e3a8afa31309f607970467fd58b5675 | 32.281437 | 140 | 0.670565 | 4.975828 | false | false | false | false |
slash-hq/slash | Sources/TLSSocket.swift | 1 | 4024 | //
// slash
//
// Copyright © 2016 slash Corp. All rights reserved.
//
import Foundation
#if os(OSX) || os(iOS)
enum TLSSocketError: Error {
case error(String)
}
class TLSSocket {
private var socket: Int32
private let sslContext: SSLContext
init(_ address: String, port: Int = 443) throws {
guard let context = SSLCreateContext(nil, .clientSide, .streamType) else {
throw TLSSocketError.error("SSLCreateContext returned null.")
}
self.sslContext = context
let socket = Darwin.socket(AF_INET, SOCK_STREAM, 0)
guard socket != -1 else {
throw TLSSocketError.error("Darwin.socket failed: \(errno)")
}
self.socket = socket
var addr = sockaddr_in()
addr.sin_len = __uint8_t(MemoryLayout<sockaddr_in>.size)
addr.sin_family = sa_family_t(AF_INET)
addr.sin_port = UInt16(port).bigEndian
guard inet_pton(AF_INET, address, &(addr.sin_addr)) == 1 else {
let _ = Darwin.close(self.socket)
throw TLSSocketError.error("inet_pton failed.")
}
if withUnsafePointer(to: &addr, {
Darwin.connect(socket, UnsafePointer<sockaddr>(OpaquePointer($0)), socklen_t(MemoryLayout<sockaddr_in>.size))
}) == -1 {
let _ = Darwin.close(self.socket)
throw TLSSocketError.error("Darwin.connect failed: \(errno)")
}
SSLSetIOFuncs(context, sslRead, sslWrite)
guard SSLSetConnection(context, &self.socket) == noErr else {
let _ = Darwin.close(self.socket)
throw TLSSocketError.error("SSLSetConnection failed.")
}
let handshakeResult = SSLHandshake(context)
guard handshakeResult == noErr else {
let _ = Darwin.close(self.socket)
throw TLSSocketError.error("SSLHandshake failed: \(handshakeResult)")
}
}
func close() {
SSLClose(self.sslContext)
let _ = Darwin.close(self.socket)
}
func writeData(_ data: [UInt8]) throws {
var processed = 0
let result = SSLWrite(self.sslContext, data, data.count, &processed)
guard result == noErr else {
throw TLSSocketError.error("SSLWrite failed: \(result)")
}
}
func readData() throws -> [UInt8] {
var processed = 0
var data = [UInt8](repeating: 0, count: 1024)
let result = SSLRead(self.sslContext, &data, data.count, &processed)
guard result == noErr else {
throw TLSSocketError.error("SSLRead failed: \(result)")
}
data.removeLast(data.count - processed)
return data
}
}
func sslRead(_ socketRef: SSLConnectionRef, _ data: UnsafeMutableRawPointer, _ length: UnsafeMutablePointer<Int>) -> OSStatus {
let socket = socketRef.load(as: Int32.self)
var n = 0
while n < length.pointee {
let result = read(socket, data + n, length.pointee - n)
if result <= 0 {
if result == Int(ENOENT) {
return errSSLClosedGraceful
}
if result == Int(ECONNRESET) {
return errSSLClosedAbort
}
return OSStatus(ioErr)
}
n += result
}
length.pointee = n
return noErr
}
func sslWrite(_ socketRef: SSLConnectionRef, _ data: UnsafeRawPointer, _ length: UnsafeMutablePointer<Int>) -> OSStatus {
let socket = socketRef.load(as: Int32.self)
var n = 0
while n < length.pointee {
let result = write(socket, data + n, length.pointee - n)
if result <= 0 {
if result == Int(EPIPE) {
return errSSLClosedAbort
}
if result == Int(ECONNRESET) {
return errSSLClosedAbort
}
return OSStatus(ioErr)
}
n += result
}
length.pointee = n
return noErr
}
#endif
| apache-2.0 | e49fdc54b533e2f807a90bdd52617b5f | 29.24812 | 127 | 0.566493 | 4.164596 | false | false | false | false |
yeahdongcn/RSBarcodes_Swift | RSBarcodesSample/RSBarcodesSample/BarcodeDisplayViewController.swift | 1 | 1469 | //
// BarcodeDisplayViewController.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 15/1/17.
//
// Updated by Jarvie8176 on 01/21/2016
//
// Copyright (c) 2015年 P.D.Q. All rights reserved.
//
import UIKit
import AVFoundation
import RSBarcodes
class BarcodeDisplayViewController: UIViewController {
@IBOutlet weak var imageDisplayed: UIImageView!
var contents: String = "https://github.com/yeahdongcn/"
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = contents
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: false)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let gen = RSUnifiedCodeGenerator.shared
gen.fillColor = UIColor.white
gen.strokeColor = UIColor.black
print ("generating image with barcode: " + contents)
if let image = gen.generateCode("Text Example", machineReadableCodeObjectType: AVMetadataObject.ObjectType.qr.rawValue, targetSize: CGSize(width: 1000, height: 1000)) {
debugPrint(image.size)
self.imageDisplayed.layer.borderWidth = 1
self.imageDisplayed.image = RSAbstractCodeGenerator.resizeImage(image, targetSize: self.imageDisplayed.bounds.size, contentMode: UIView.ContentMode.bottomRight)
}
}
}
| mit | ac770ed7adbc974b090827edd642f5f2 | 31.6 | 176 | 0.693933 | 4.809836 | false | false | false | false |
tluquet3/MonTennis | MonTennis/Palmares/ModifierTextController.swift | 1 | 2322 | //
// ModifierTextController.swift
// MonTennis
//
// Created by Thomas Luquet on 03/07/2015.
// Copyright (c) 2015 Thomas Luquet. All rights reserved.
//
import UIKit
class ModifierTextController: UITableViewController {
internal var textValue: String!
internal var textType: String!
@IBOutlet weak var textField: UITextField!
internal var match: Match!
internal var id: Int!
override func viewDidLoad() {
super.viewDidLoad()
textField.text = textValue
self.navigationItem.title = textType
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 1
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
if(segue.identifier == "saveMatchChanges"){
switch textType {
case "Nom":
if(match.resultat){
barCtrl.user.victoires[id].lastName = textField.text!
}else{
barCtrl.user.defaites[id].lastName = textField.text!
}
case "Prénom":
if(match.resultat){
barCtrl.user.victoires[id].firstName = textField.text!
}else{
barCtrl.user.defaites[id].firstName = textField.text!
}
default:
textType = "error"
}
barCtrl.clearCoreData()
barCtrl.fillCoreData()
}
}
}
| apache-2.0 | b5f566c096671a5fad24ea99a6f5d6bc | 28.379747 | 106 | 0.602327 | 5.02381 | false | false | false | false |
brokenhandsio/vapor-oauth | Tests/VaporOAuthTests/GrantTests/AuthorizationCodeTokenTests.swift | 1 | 21700 | import XCTest
import VaporOAuth
import Vapor
import Foundation
class AuthorizationCodeTokenTests: XCTestCase {
// MARK: - All Tests
static var allTests = [
("testLinuxTestSuiteIncludesAllTests", testLinuxTestSuiteIncludesAllTests),
("testThatResponseTypeMustBeSentInAuthCodeRequest", testCorrectErrorAndHeadersReceivedWhenNoGrantTypeSent),
("testCorrectErrorAndHeadersReceivedWhenIncorrectGrantTypeSet", testCorrectErrorAndHeadersReceivedWhenIncorrectGrantTypeSet),
("testCorrectErrorAndHeadersReceivedWhenNoCodeSent", testCorrectErrorAndHeadersReceivedWhenNoCodeSent),
("testCorrectErrorAndHeadersReceivedWhenNoRedirectURISent", testCorrectErrorAndHeadersReceivedWhenNoRedirectURISent),
("testCorrectErrorAndHeadersReceivedWhenNoClientIDSent", testCorrectErrorAndHeadersReceivedWhenNoClientIDSent),
("testCorrectErrorAndHeadersReceivedIfClientSecretNotSendAndIsExpected", testCorrectErrorAndHeadersReceivedIfClientSecretNotSendAndIsExpected),
("testCorrectErrorAndHeadersReceivedIfClientIDIsUnknown", testCorrectErrorAndHeadersReceivedIfClientIDIsUnknown),
("testCorrectErrorAndHeadersReceivedIfClientDoesNotAuthenticateCorrectly", testCorrectErrorAndHeadersReceivedIfClientDoesNotAuthenticateCorrectly),
("testErrorIfCodeDoesNotExist", testErrorIfCodeDoesNotExist),
("testCorrectErrorCodeAndHeadersReturnedIfCodeWasNotIssuedByClient", testCorrectErrorCodeAndHeadersReturnedIfCodeWasNotIssuedByClient),
("testCorrectErrorCodeWhenCodeIsExpired", testCorrectErrorCodeWhenCodeIsExpired),
("testCorrectErrorCodeWhenRedirectURIDoesNotMatchForCode", testCorrectErrorCodeWhenRedirectURIDoesNotMatchForCode),
("testThatCodeCantBeReused", testThatCodeIsMarkedAsUsedAndCantBeReused),
("testThatCorrectResponseReceivedWhenCorrectRequestSent", testThatCorrectResponseReceivedWhenCorrectRequestSent),
("testThatClientSecretNotNeededIfClientNotIssuedWithOne", testThatClientSecretNotNeededIfClientNotIssuedWithOne),
("testThatNoScopeReturnedIfNoneSetOnCode", testThatNoScopeReturnedIfNoneSetOnCode),
("testThatTokenHasCorrectUserID", testThatTokenHasCorrectUserID),
("testThatTokenHasCorrectClientID", testThatTokenHasCorrectClientID),
("testThatTokenHasCorrectScopeIfScopesSetOnCode", testThatTokenHasCorrectScopeIfScopesSetOnCode),
("testTokenHasExpiryTimeSetOnIt", testTokenHasExpiryTimeSetOnIt),
("testThatRefreshTokenHasCorrectClientIDSet", testThatRefreshTokenHasCorrectClientIDSet),
("testThatRefreshTokenHasCorrectUserIDSet", testThatRefreshTokenHasCorrectUserIDSet),
("testThatRefreshTokenHasNoScopesIfNoneRequested", testThatRefreshTokenHasNoScopesIfNoneRequested),
("testThatRefreshTokenHasCorrectScopesIfSet", testThatRefreshTokenHasCorrectScopesIfSet),
]
// MARK: - Properties
var drop: Droplet!
let fakeClientGetter = FakeClientGetter()
let fakeCodeManager = FakeCodeManager()
let fakeTokenManager = FakeTokenManager()
let testClientID = "1234567890"
let testClientSecret = "ABCDEFGHIJK"
let testClientRedirectURI = "https://api.brokenhands.io/callback"
let testCodeID = "12345ABCD"
let userID: Identifier = "the-user-id"
let scopes = ["email", "create"]
// MARK: - Overrides
override func setUp() {
drop = try! TestDataBuilder.getOAuthDroplet(codeManager: fakeCodeManager, tokenManager: fakeTokenManager, clientRetriever: fakeClientGetter)
let testClient = OAuthClient(clientID: testClientID, redirectURIs: [testClientRedirectURI], clientSecret: testClientSecret, allowedGrantType: .authorization)
fakeClientGetter.validClients[testClientID] = testClient
let testCode = OAuthCode(codeID: testCodeID, clientID: testClientID, redirectURI: testClientRedirectURI, userID: userID, expiryDate: Date().addingTimeInterval(60), scopes: scopes)
fakeCodeManager.codes[testCodeID] = testCode
}
// MARK: - Tests
// Courtesy of https://oleb.net/blog/2017/03/keeping-xctest-in-sync/
func testLinuxTestSuiteIncludesAllTests() {
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
let thisClass = type(of: self)
let linuxCount = thisClass.allTests.count
let darwinCount = Int(thisClass.defaultTestSuite.testCaseCount)
XCTAssertEqual(linuxCount, darwinCount, "\(darwinCount - linuxCount) tests are missing from allTests")
#endif
}
func testCorrectErrorAndHeadersReceivedWhenNoGrantTypeSent() throws {
let response = try getAuthCodeResponse(grantType: nil)
guard let responseJSON = response.json else {
XCTFail()
return
}
XCTAssertEqual(response.status, .badRequest)
XCTAssertEqual(responseJSON["error"]?.string, "invalid_request")
XCTAssertEqual(responseJSON["error_description"], "Request was missing the 'grant_type' parameter")
XCTAssertEqual(response.headers[.cacheControl], "no-store")
XCTAssertEqual(response.headers[.pragma], "no-cache")
}
func testCorrectErrorAndHeadersReceivedWhenIncorrectGrantTypeSet() throws {
let grantType = "some_unknown_type"
let response = try getAuthCodeResponse(grantType: grantType)
guard let responseJSON = response.json else {
XCTFail()
return
}
XCTAssertEqual(response.status, .badRequest)
XCTAssertEqual(responseJSON["error"]?.string, "unsupported_grant_type")
XCTAssertEqual(responseJSON["error_description"]?.string, "This server does not support the '\(grantType)' grant type")
XCTAssertEqual(response.headers[.cacheControl], "no-store")
XCTAssertEqual(response.headers[.pragma], "no-cache")
}
func testCorrectErrorAndHeadersReceivedWhenNoCodeSent() throws {
let response = try getAuthCodeResponse(code: nil)
guard let responseJSON = response.json else {
XCTFail()
return
}
XCTAssertEqual(response.status, .badRequest)
XCTAssertEqual(responseJSON["error"]?.string, "invalid_request")
XCTAssertEqual(responseJSON["error_description"], "Request was missing the 'code' parameter")
XCTAssertEqual(response.headers[.cacheControl], "no-store")
XCTAssertEqual(response.headers[.pragma], "no-cache")
}
func testCorrectErrorAndHeadersReceivedWhenNoRedirectURISent() throws {
let response = try getAuthCodeResponse(redirectURI: nil)
guard let responseJSON = response.json else {
XCTFail()
return
}
XCTAssertEqual(response.status, .badRequest)
XCTAssertEqual(responseJSON["error"]?.string, "invalid_request")
XCTAssertEqual(responseJSON["error_description"], "Request was missing the 'redirect_uri' parameter")
XCTAssertEqual(response.headers[.cacheControl], "no-store")
XCTAssertEqual(response.headers[.pragma], "no-cache")
}
func testCorrectErrorAndHeadersReceivedWhenNoClientIDSent() throws {
let response = try getAuthCodeResponse(clientID: nil)
guard let responseJSON = response.json else {
XCTFail()
return
}
XCTAssertEqual(response.status, .badRequest)
XCTAssertEqual(responseJSON["error"]?.string, "invalid_request")
XCTAssertEqual(responseJSON["error_description"], "Request was missing the 'client_id' parameter")
XCTAssertEqual(response.headers[.cacheControl], "no-store")
XCTAssertEqual(response.headers[.pragma], "no-cache")
}
func testCorrectErrorAndHeadersReceivedIfClientIDIsUnknown() throws {
let response = try getAuthCodeResponse(clientID: "UNKNOWN_CLIENT")
guard let responseJSON = response.json else {
XCTFail()
return
}
XCTAssertEqual(response.status, .unauthorized)
XCTAssertEqual(responseJSON["error"]?.string, "invalid_client")
XCTAssertEqual(responseJSON["error_description"], "Request had invalid client credentials")
XCTAssertEqual(response.headers[.cacheControl], "no-store")
XCTAssertEqual(response.headers[.pragma], "no-cache")
}
func testCorrectErrorAndHeadersReceivedIfClientSecretNotSendAndIsExpected() throws {
let clientID = "ABCDEF"
let clientWithSecret = OAuthClient(clientID: clientID, redirectURIs: ["https://api.brokenhands.io/callback"], clientSecret: "1234567890ABCD", allowedGrantType: .authorization)
fakeClientGetter.validClients[clientID] = clientWithSecret
let response = try getAuthCodeResponse(clientID: clientID, clientSecret: nil)
guard let responseJSON = response.json else {
XCTFail()
return
}
XCTAssertEqual(response.status, .unauthorized)
XCTAssertEqual(responseJSON["error"]?.string, "invalid_client")
XCTAssertEqual(responseJSON["error_description"], "Request had invalid client credentials")
XCTAssertEqual(response.headers[.cacheControl], "no-store")
XCTAssertEqual(response.headers[.pragma], "no-cache")
}
func testCorrectErrorAndHeadersReceivedIfClientDoesNotAuthenticateCorrectly() throws {
let clientID = "ABCDEF"
let clientWithSecret = OAuthClient(clientID: clientID, redirectURIs: ["https://api.brokenhands.io/callback"], clientSecret: "1234567890ABCD", allowedGrantType: .authorization)
fakeClientGetter.validClients[clientID] = clientWithSecret
let response = try getAuthCodeResponse(clientID: clientID, clientSecret: "incorrectPassword")
guard let responseJSON = response.json else {
XCTFail()
return
}
XCTAssertEqual(response.status, .unauthorized)
XCTAssertEqual(responseJSON["error"]?.string, "invalid_client")
XCTAssertEqual(responseJSON["error_description"], "Request had invalid client credentials")
XCTAssertEqual(response.headers[.cacheControl], "no-store")
XCTAssertEqual(response.headers[.pragma], "no-cache")
}
func testErrorIfCodeDoesNotExist() throws {
let response = try getAuthCodeResponse(code: "unkownCodeID")
guard let responseJSON = response.json else {
XCTFail()
return
}
XCTAssertEqual(response.status, .badRequest)
XCTAssertEqual(responseJSON["error"]?.string, "invalid_grant")
XCTAssertEqual(responseJSON["error_description"], "The code provided was invalid or expired, or the redirect URI did not match")
XCTAssertEqual(response.headers[.cacheControl], "no-store")
XCTAssertEqual(response.headers[.pragma], "no-cache")
}
func testCorrectErrorCodeAndHeadersReturnedIfCodeWasNotIssuedByClient() throws {
let codeID = "1234567"
let code = OAuthCode(codeID: codeID, clientID: testClientID, redirectURI: testClientRedirectURI, userID: "1", expiryDate: Date().addingTimeInterval(60), scopes: nil)
fakeCodeManager.codes[codeID] = code
let clientBID = "clientB"
let clientB = OAuthClient(clientID: clientBID, redirectURIs: [testClientRedirectURI], allowedGrantType: .authorization)
fakeClientGetter.validClients[clientBID] = clientB
let response = try getAuthCodeResponse(code: codeID, redirectURI: testClientRedirectURI, clientID: clientBID, clientSecret: nil)
guard let responseJSON = response.json else {
XCTFail()
return
}
XCTAssertEqual(response.status, .badRequest)
XCTAssertEqual(responseJSON["error"]?.string, "invalid_grant")
XCTAssertEqual(responseJSON["error_description"], "The code provided was invalid or expired, or the redirect URI did not match")
XCTAssertEqual(response.headers[.cacheControl], "no-store")
XCTAssertEqual(response.headers[.pragma], "no-cache")
}
func testCorrectErrorCodeWhenCodeIsExpired() throws {
let codeID = "1234567"
let code = OAuthCode(codeID: codeID, clientID: testClientID, redirectURI: testClientRedirectURI, userID: "1", expiryDate: Date().addingTimeInterval(-60), scopes: nil)
fakeCodeManager.codes[codeID] = code
let response = try getAuthCodeResponse(code: codeID)
guard let responseJSON = response.json else {
XCTFail()
return
}
XCTAssertEqual(response.status, .badRequest)
XCTAssertEqual(responseJSON["error"]?.string, "invalid_grant")
XCTAssertEqual(responseJSON["error_description"], "The code provided was invalid or expired, or the redirect URI did not match")
XCTAssertEqual(response.headers[.cacheControl], "no-store")
XCTAssertEqual(response.headers[.pragma], "no-cache")
}
func testCorrectErrorCodeWhenRedirectURIDoesNotMatchForCode() throws {
let response = try getAuthCodeResponse(redirectURI: "https://different.brokenhandsio.io/callback")
guard let responseJSON = response.json else {
XCTFail()
return
}
XCTAssertEqual(response.status, .badRequest)
XCTAssertEqual(responseJSON["error"]?.string, "invalid_grant")
XCTAssertEqual(responseJSON["error_description"], "The code provided was invalid or expired, or the redirect URI did not match")
XCTAssertEqual(response.headers[.cacheControl], "no-store")
XCTAssertEqual(response.headers[.pragma], "no-cache")
}
func testThatCodeIsMarkedAsUsedAndCantBeReused() throws {
_ = try getAuthCodeResponse(code: testCodeID)
let secondCodeResponse = try getAuthCodeResponse(code: testCodeID)
XCTAssertEqual(secondCodeResponse.status, .badRequest)
XCTAssertTrue(fakeCodeManager.usedCodes.contains(testCodeID))
}
func testThatCorrectResponseReceivedWhenCorrectRequestSent() throws {
let accessToken = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
let refreshToken = "01234567890"
fakeTokenManager.accessTokenToReturn = accessToken
fakeTokenManager.refreshTokenToReturn = refreshToken
let response = try getAuthCodeResponse()
guard let responseJSON = response.json else {
XCTFail()
return
}
XCTAssertEqual(response.status, .ok)
XCTAssertEqual(response.headers[.cacheControl], "no-store")
XCTAssertEqual(response.headers[.pragma], "no-cache")
XCTAssertEqual(responseJSON["token_type"]?.string, "bearer")
XCTAssertEqual(responseJSON["expires_in"]?.int, 3600)
XCTAssertEqual(responseJSON["access_token"]?.string, accessToken)
XCTAssertEqual(responseJSON["refresh_token"]?.string, refreshToken)
XCTAssertEqual(responseJSON["scope"]?.string, "email create")
guard let token = fakeTokenManager.getAccessToken(accessToken) else {
XCTFail()
return
}
XCTAssertEqual(token.scopes ?? [], scopes)
}
func testThatNoScopeReturnedIfNoneSetOnCode() throws {
let newCodeString = "NEW_CODE_STRING"
let newCode = OAuthCode(codeID: newCodeString, clientID: testClientID, redirectURI: testClientRedirectURI, userID: "1", expiryDate: Date().addingTimeInterval(60), scopes: nil)
fakeCodeManager.codes[newCodeString] = newCode
let response = try getAuthCodeResponse(code: newCodeString)
guard let responseJSON = response.json else {
XCTFail()
return
}
XCTAssertNil(responseJSON["scope"]?.string)
guard let accessToken = fakeTokenManager.getAccessToken(responseJSON["access_token"]?.string ?? "") else {
XCTFail()
return
}
XCTAssertNil(accessToken.scopes)
}
func testThatClientSecretNotNeededIfClientNotIssuedWithOne() throws {
let clientWithoutSecret = OAuthClient(clientID: testClientID, redirectURIs: ["https://api.brokenhands.io/callback"], clientSecret: nil, allowedGrantType: .authorization)
fakeClientGetter.validClients[testClientID] = clientWithoutSecret
let response = try getAuthCodeResponse(clientID: testClientID, clientSecret: nil)
XCTAssertEqual(response.status, .ok)
}
func testThatTokenHasCorrectUserID() throws {
let accessTokenString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
fakeTokenManager.accessTokenToReturn = accessTokenString
_ = try getAuthCodeResponse()
guard let accessToken = fakeTokenManager.getAccessToken(accessTokenString) else {
XCTFail()
return
}
XCTAssertEqual(accessToken.userID, userID)
}
func testThatTokenHasCorrectClientID() throws {
let accessTokenString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
fakeTokenManager.accessTokenToReturn = accessTokenString
_ = try getAuthCodeResponse()
guard let accessToken = fakeTokenManager.getAccessToken(accessTokenString) else {
XCTFail()
return
}
XCTAssertEqual(accessToken.clientID, testClientID)
}
func testThatTokenHasCorrectScopeIfScopesSetOnCode() throws {
let accessTokenString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
fakeTokenManager.accessTokenToReturn = accessTokenString
let newCodeString = "new-code-string"
let scopes = ["oneScope", "aDifferentScope"]
let newCode = OAuthCode(codeID: newCodeString, clientID: testClientID, redirectURI: testClientRedirectURI, userID: "user-id", expiryDate: Date().addingTimeInterval(60), scopes: scopes)
fakeCodeManager.codes[newCodeString] = newCode
_ = try getAuthCodeResponse(code: newCodeString)
guard let accessToken = fakeTokenManager.getAccessToken(accessTokenString) else {
XCTFail()
return
}
XCTAssertEqual(accessToken.scopes ?? [], scopes)
}
func testTokenHasExpiryTimeSetOnIt() throws {
let accessTokenString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
fakeTokenManager.accessTokenToReturn = accessTokenString
let currentTime = Date()
fakeTokenManager.currentTime = currentTime
_ = try getAuthCodeResponse()
guard let accessToken = fakeTokenManager.getAccessToken(accessTokenString) else {
XCTFail()
return
}
XCTAssertEqual(accessToken.expiryTime, currentTime.addingTimeInterval(3600))
}
func testThatRefreshTokenHasCorrectClientIDSet() throws {
let refreshTokenString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
fakeTokenManager.refreshTokenToReturn = refreshTokenString
_ = try getAuthCodeResponse()
guard let refreshToken = fakeTokenManager.getRefreshToken(refreshTokenString) else {
XCTFail()
return
}
XCTAssertEqual(refreshToken.clientID, testClientID)
}
func testThatRefreshTokenHasCorrectUserIDSet() throws {
let refreshTokenString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
fakeTokenManager.refreshTokenToReturn = refreshTokenString
_ = try getAuthCodeResponse()
guard let refreshToken = fakeTokenManager.getRefreshToken(refreshTokenString) else {
XCTFail()
return
}
XCTAssertEqual(refreshToken.userID, userID)
}
func testThatRefreshTokenHasNoScopesIfNoneRequested() throws {
let refreshTokenString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
fakeTokenManager.refreshTokenToReturn = refreshTokenString
let newCodeString = "new-code"
let newCode = OAuthCode(codeID: newCodeString, clientID: testClientID, redirectURI: testClientRedirectURI, userID: "user-ID", expiryDate: Date().addingTimeInterval(60), scopes: nil)
fakeCodeManager.codes[newCodeString] = newCode
_ = try getAuthCodeResponse(code: newCodeString)
guard let refreshToken = fakeTokenManager.getRefreshToken(refreshTokenString) else {
XCTFail()
return
}
XCTAssertNil(refreshToken.scopes)
}
func testThatRefreshTokenHasCorrectScopesIfSet() throws {
let refreshTokenString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
fakeTokenManager.refreshTokenToReturn = refreshTokenString
_ = try getAuthCodeResponse()
guard let refreshToken = fakeTokenManager.getRefreshToken(refreshTokenString) else {
XCTFail()
return
}
XCTAssertEqual(refreshToken.scopes ?? [], scopes)
}
// MARK: - Private
private func getAuthCodeResponse(grantType: String? = "authorization_code", code: String? = "12345ABCD", redirectURI: String? = "https://api.brokenhands.io/callback", clientID: String? = "1234567890", clientSecret: String? = "ABCDEFGHIJK") throws -> Response {
return try TestDataBuilder.getTokenRequestResponse(with: drop, grantType: grantType, clientID: clientID, clientSecret: clientSecret, redirectURI: redirectURI, code: code)
}
}
| mit | 4bd913076e60ea18db2f6c4b86b95027 | 44.780591 | 264 | 0.688894 | 5.272109 | false | true | false | false |
timsawtell/SwiftAppStarter | App/Controller/ViewControllers/DemoViewController.swift | 1 | 1697 | //
// DemoViewController.swift
// TSBoilerplateSwift
//
// Created by Tim Sawtell on 9/07/2014.
// Copyright (c) 2014 Sawtell Software. All rights reserved.
//
import UIKit
class DemoViewController: TSViewController {
@IBOutlet var tf1: UITextField?
@IBOutlet var tf2: UITextField?
@IBOutlet var tf3: UITextField?
override func viewDidLoad() {
if (tf1 != nil) { inputFields.addObject(tf1!) }
if (tf2 != nil) { inputFields.addObject(tf2!) }
if (tf3 != nil) { inputFields.addObject(tf3!) }
super.viewDidLoad()
}
override func wantsPullToRefresh() -> Bool {
return true
}
override func wantsPullToRefreshFooter() -> Bool {
return true
}
@IBAction func runCommandTouched(sender: AnyObject) {
// an example of how the VC receives an event and how the "business logic" is
// kept inside a Command. The singleton GlobalModel is updated (or not!) by the
// command and it's up to the VC to decide what to do in the command's commandCompletionBlock
let cmd = iTunesSearchCommand()
cmd.isbn = (self.tf3?.text)!;
cmd.commandCompletionBlock = { error in
if ( error != nil ) {
NSLog("Encountered an error: \(error?.localizedDescription)")
} else {
if let book = GlobalModel.person.bookshelf.books.last {
NSLog("Last Successful search result: \(book.title), by: \(book.author?.name)")
} else {
NSLog("No results");
}
}
}
GlobalCommandRunner.executeCommand(cmd)
}
}
| mit | e426a84e31d3b78a7d26313ca839317f | 31.634615 | 101 | 0.584561 | 4.489418 | false | false | false | false |
RocketJourney/RaceTracker | Source/RunSpanishSpeaker.swift | 1 | 2993 | //
// RunSpanishSpeaker.swift
// RJv1
//
// Created by Ernesto Cambuston on 5/2/15.
// Copyright (c) 2015 Ernesto Cambuston. All rights reserved.
//
import Foundation
class RunSpanishSpeaker : RunTrackerSpeechLanguageProvider {
private var _unitSystem = false
var unitSystem:Bool {
set(value) {
_unitSystem = value
if value {
units = "kilómetros"
unit = "kilómetro"
} else {
units = "millas"
unit = "milla"
}
}
get {
return _unitSystem
}
}
private var unit = ""
private var units = ""
private func distanceString(distance:DistanceStructure)->String {
let one = distance.firstUnit == 1 && distance.secondUnit < 10 ? (_unitSystem ? "un" : "una") : "uno"
var string = "distancia,.. \(distance.firstUnit == 1 ? one : "\(distance.firstUnit)") "
if distance.secondUnit < 10 {
if distance.firstUnit == 1 {
string += unit
} else {
string += units
}
} else {
string += "punto \(printFirst(distance.secondUnit)) \(units),"
}
string += ",... "
return string
}
private func printFirst(number:Int)->String {
let string = Array(arrayLiteral: "\(number)".characters)[0]
return String(string.first!)
}
private func timeString(time:TimeStructure)->String {
var string = " tiempo,.. "
if time.hours != 0 {
if time.hours == 1 {
string += "una hora, "
} else {
string += "\(time.hours) horas, "
}
}
if time.minutes == 1 {
string += " \(time.minutes) minuto"
} else {
string += " \(time.minutes) minutos"
}
string += ", con \(time.seconds) segundos,... "
return string
}
private func paceString(pace:PaceStructure)->String{
return " ritmo promedio: \(pace.firstUnit) , \(pace.secondUnit) por \(unit)"
}
func sayFeedback(time:TimeStructure, distance:DistanceStructure, pace:PaceStructure)->String {
var string = " " + distanceString(distance)
string += timeString(time)
string += paceString(pace)
return string + " "
}
func sayFeedbackDecremental(time:TimeStructure, distance:DistanceStructure, pace:PaceStructure)->String {
var string = " restan solo \(distance.firstUnit) punto \(distance.secondUnit) \(units),... "
string += timeString(time)
string += paceString(pace)
return string + " "
}
func sayMidpoint(time:TimeStructure, distance:DistanceStructure, pace:PaceStructure)->String {
return " mitad del camino,... " + sayFeedbackDecremental(time, distance: distance, pace: pace)
}
func sayGoalAchieved(time:TimeStructure, distance:DistanceStructure, pace:PaceStructure)->String {
return " meta alcanzada,... " + sayFeedback(time, distance: distance, pace: pace)
}
func sayLastSprint(time:TimeStructure, distance:DistanceStructure, pace:PaceStructure)->String {
return " casi terminamos... "
}
} | mit | 175e0ef55631a215f4517af8e10c81e0 | 31.172043 | 107 | 0.615513 | 3.829706 | false | false | false | false |
MxABC/oclearning | swiftLearning/Pods/ObjectMapper/ObjectMapper/Core/ToJSON.swift | 8 | 6044 | //
// ToJSON.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2014-10-13.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2015 Hearst
//
// 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 class Foundation.NSNumber
private func setValue(value: AnyObject, map: Map) {
setValue(value, key: map.currentKey!, checkForNestedKeys: map.keyIsNested, dictionary: &map.JSONDictionary)
}
private func setValue(value: AnyObject, key: String, checkForNestedKeys: Bool, inout dictionary: [String : AnyObject]) {
if checkForNestedKeys {
let keyComponents = ArraySlice(key.characters.split { $0 == "." })
setValue(value, forKeyPathComponents: keyComponents, dictionary: &dictionary)
} else {
dictionary[key] = value
}
}
private func setValue(value: AnyObject, forKeyPathComponents components: ArraySlice<String.CharacterView.SubSequence>, inout dictionary: [String : AnyObject]) {
if components.isEmpty {
return
}
let head = components.first!
if components.count == 1 {
dictionary[String(head)] = value
} else {
var child = dictionary[String(head)] as? [String : AnyObject]
if child == nil {
child = [:]
}
let tail = components.dropFirst()
setValue(value, forKeyPathComponents: tail, dictionary: &child!)
dictionary[String(head)] = child
}
}
internal final class ToJSON {
class func basicType<N>(field: N, map: Map) {
func _setValue(value: AnyObject) {
setValue(value, map: map)
}
if let x = field as? NSNumber { // basic types
_setValue(x)
} else if let x = field as? Bool {
_setValue(x)
} else if let x = field as? Int {
_setValue(x)
} else if let x = field as? Double {
_setValue(x)
} else if let x = field as? Float {
_setValue(x)
} else if let x = field as? String {
_setValue(x)
} else if let x = field as? Array<NSNumber> { // Arrays
_setValue(x)
} else if let x = field as? Array<Bool> {
_setValue(x)
} else if let x = field as? Array<Int> {
_setValue(x)
} else if let x = field as? Array<Double> {
_setValue(x)
} else if let x = field as? Array<Float> {
_setValue(x)
} else if let x = field as? Array<String> {
_setValue(x)
} else if let x = field as? Array<AnyObject> {
_setValue(x)
} else if let x = field as? Array<Dictionary<String, AnyObject>> {
_setValue(x)
} else if let x = field as? Dictionary<String, NSNumber> { // Dictionaries
_setValue(x)
} else if let x = field as? Dictionary<String, Bool> {
_setValue(x)
} else if let x = field as? Dictionary<String, Int> {
_setValue(x)
} else if let x = field as? Dictionary<String, Double> {
_setValue(x)
} else if let x = field as? Dictionary<String, Float> {
_setValue(x)
} else if let x = field as? Dictionary<String, String> {
_setValue(x)
} else if let x = field as? Dictionary<String, AnyObject> {
_setValue(x)
}
}
class func optionalBasicType<N>(field: N?, map: Map) {
if let field = field {
basicType(field, map: map)
}
}
class func object<N: Mappable>(field: N, map: Map) {
setValue(Mapper().toJSON(field), map: map)
}
class func optionalObject<N: Mappable>(field: N?, map: Map) {
if let field = field {
object(field, map: map)
}
}
class func objectArray<N: Mappable>(field: Array<N>, map: Map) {
let JSONObjects = Mapper().toJSONArray(field)
setValue(JSONObjects, map: map)
}
class func optionalObjectArray<N: Mappable>(field: Array<N>?, map: Map) {
if let field = field {
objectArray(field, map: map)
}
}
class func twoDimensionalObjectArray<N: Mappable>(field: Array<Array<N>>, map: Map) {
var array = [[[String : AnyObject]]]()
for innerArray in field {
let JSONObjects = Mapper().toJSONArray(innerArray)
array.append(JSONObjects)
}
setValue(array, map: map)
}
class func optionalTwoDimensionalObjectArray<N: Mappable>(field: Array<Array<N>>?, map: Map) {
if let field = field {
twoDimensionalObjectArray(field, map: map)
}
}
class func objectSet<N: Mappable where N: Hashable>(field: Set<N>, map: Map) {
let JSONObjects = Mapper().toJSONSet(field)
setValue(JSONObjects, map: map)
}
class func optionalObjectSet<N: Mappable where N: Hashable>(field: Set<N>?, map: Map) {
if let field = field {
objectSet(field, map: map)
}
}
class func objectDictionary<N: Mappable>(field: Dictionary<String, N>, map: Map) {
let JSONObjects = Mapper().toJSONDictionary(field)
setValue(JSONObjects, map: map)
}
class func optionalObjectDictionary<N: Mappable>(field: Dictionary<String, N>?, map: Map) {
if let field = field {
objectDictionary(field, map: map)
}
}
class func objectDictionaryOfArrays<N: Mappable>(field: Dictionary<String, [N]>, map: Map) {
let JSONObjects = Mapper().toJSONDictionaryOfArrays(field)
setValue(JSONObjects, map: map)
}
class func optionalObjectDictionaryOfArrays<N: Mappable>(field: Dictionary<String, [N]>?, map: Map) {
if let field = field {
objectDictionaryOfArrays(field, map: map)
}
}
}
| mit | ca72f9b3c2499ff47a98009c04e9498b | 29.836735 | 160 | 0.683819 | 3.397414 | false | false | false | false |
crossroadlabs/Swirl | Sources/Swirl/SQL.swift | 1 | 2000 | //===--- SQL.swift ------------------------------------------------------===//
//Copyright (c) 2017 Crossroad Labs s.r.o.
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//===----------------------------------------------------------------------===//
import Foundation
public struct SQL {
public let query:String
public let parameters:[Any?]
public init(query:String, parameters:[Any?]) {
self.query = query
self.parameters = parameters
}
}
extension SQL: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.init(query: value, parameters: [])
}
public init(unicodeScalarLiteral value: String) {
self.init(stringLiteral: value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(stringLiteral: value)
}
}
public func +(a:SQL, b:SQL) -> SQL {
return SQL(query: a.query + b.query, parameters: a.parameters + b.parameters)
}
public func +(a:SQL, b:String) -> SQL {
return SQL(query: a.query + b, parameters: a.parameters)
}
public func +(a:String, b:SQL) -> SQL {
return SQL(query: a + b.query, parameters: b.parameters)
}
public extension Sequence where Iterator.Element == SQL {
public func joined(separator: String = "") -> SQL {
let strings = self.map {$0.query}
let query = strings.joined(separator: separator)
let params = self.flatMap {$0.parameters}
return SQL(query: query, parameters: params)
}
}
| apache-2.0 | 5cd4f1cba51420f54d76b05f582181fd | 31.258065 | 81 | 0.631 | 4.237288 | false | false | false | false |
Roommate-App/roomy | roomy/Pods/IBAnimatable/Sources/Protocols/Designable/PlaceholderDesignable.swift | 2 | 2854 | //
// Created by Jake Lin on 11/19/15.
// Copyright © 2015 IBAnimatable. All rights reserved.
//
import UIKit
public protocol PlaceholderDesignable: class {
/**
`color` within `::-webkit-input-placeholder`, `::-moz-placeholder` or `:-ms-input-placeholder`
*/
var placeholderColor: UIColor? { get set }
var placeholderText: String? { get set }
}
public extension PlaceholderDesignable where Self: UITextField {
var placeholderText: String? { get { return "" } set {} }
public func configurePlaceholderColor() {
let text = placeholder ?? placeholderText
if let placeholderColor = placeholderColor, let placeholder = text {
attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [.foregroundColor: placeholderColor])
}
}
}
public extension PlaceholderDesignable where Self: UITextView {
public func configure(placeholderLabel: UILabel, placeholderLabelConstraints: inout [NSLayoutConstraint]) {
placeholderLabel.font = font
placeholderLabel.textColor = placeholderColor
placeholderLabel.textAlignment = textAlignment
placeholderLabel.text = placeholderText
placeholderLabel.numberOfLines = 0
placeholderLabel.backgroundColor = .clear
placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(placeholderLabel)
update(placeholderLabel, using: &placeholderLabelConstraints)
}
public func update(_ placeholderLabel: UILabel, using constraints: inout [NSLayoutConstraint]) {
var format = "H:|-(\(textContainerInset.left + textContainer.lineFragmentPadding))-[placeholder]"
var newConstraints = NSLayoutConstraint.constraints(withVisualFormat: format,
options: [], metrics: nil,
views: ["placeholder": placeholderLabel])
format = "V:|-(\(textContainerInset.top))-[placeholder]"
newConstraints += NSLayoutConstraint.constraints(withVisualFormat: format,
options: [], metrics: nil,
views: ["placeholder": placeholderLabel])
let constant = -(textContainerInset.left + textContainerInset.right + textContainer.lineFragmentPadding * 2.0)
newConstraints.append(NSLayoutConstraint(item: placeholderLabel,
attribute: .width,
relatedBy: .equal,
toItem: self,
attribute: .width,
multiplier: 1.0,
constant: constant))
removeConstraints(constraints)
addConstraints(newConstraints)
constraints = newConstraints
}
}
| mit | 32c2c404ba3e89fd8af025bb1b8fb3b1 | 41.58209 | 119 | 0.626358 | 6.425676 | false | false | false | false |
li1024316925/Swift-TimeMovie | Swift-TimeMovie/Swift-TimeMovie/LLQTabBarController.swift | 1 | 6392 | //
// LLQTabBarController.swift
// Swift-TimeMovie
//
// Created by DahaiZhang on 16/10/13.
// Copyright © 2016年 LLQ. All rights reserved.
//
import UIKit
func kTabBarWidth(object: UITabBarController) -> CGFloat {return object.tabBar.frame.size.width}
func kTabBarHeight(object: UITabBarController) -> CGFloat {return object.tabBar.frame.size.height}
func kButtonWidth(object: UITabBarController) -> CGFloat {return kTabBarWidth(object: object)/CGFloat((object.viewControllers?.count)!)}
class LLQTabBarController: UITabBarController {
var selectImgV:UIImageView? //存储选中图片
//按钮数组
lazy var tabBarButtons:[UIButton] = {
return []
}()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//检查是否有选中图片
let selectionIndicatorImage = tabBar.selectionIndicatorImage
//如果没有选中图片,什么都不做,如果有添加为选中图片
if selectionIndicatorImage == nil {
return
}
selectImgV = UIImageView(image: selectionIndicatorImage)
selectImgV?.frame = CGRect(x: CGFloat(selectedIndex)*kButtonWidth(object: self), y: 0, width: kButtonWidth(object: self), height: kTabBarHeight(object: self))
tabBar.insertSubview(selectImgV!, at: 0)
let selectButton = tabBarButtons[selectedIndex]
selectButton.isSelected = true
}
override func viewDidLoad() {
super.viewDidLoad()
}
//截取外部给本控制器控制器数组赋值的方法
override func setViewControllers(_ viewControllers: [UIViewController]?, animated: Bool) {
super.setViewControllers(viewControllers, animated: animated)
//移除所有原按钮
for subView in tabBar.subviews {
subView.removeFromSuperview()
}
//添加自定义的按钮
for i in 0..<viewControllers!.count {
let button = VerticalButton(frame: CGRect(x: CGFloat(i)*kButtonWidth(object: self), y: 0, width: kButtonWidth(object: self), height: kTabBarHeight(object: self)))
//取出控制器,获取其tabBar的默认、选中图片、标题
let subVC = viewControllers?[i]
let image = subVC?.tabBarItem.image
let selectImage = subVC?.tabBarItem.selectedImage
let title = subVC?.tabBarItem.title
//重新赋值给自定义的Button
button.setImage(image, for: UIControlState.normal)
button.setImage(selectImage, for: UIControlState.selected)
button.setTitle(title, for: UIControlState.normal)
//按钮添加点击事件
button.addTarget(self, action: #selector(selectedVC(button:)), for: UIControlEvents.touchUpInside)
button.tag = 100+i
print(button)
tabBar.addSubview(button)
tabBarButtons.append(button)
}
}
//MARK: ------ 按钮点击事件
func selectedVC(button: UIButton) -> Void {
//修改标签控制器的本身具有的 selectedIndex 完成切换功能
selectedIndex = button.tag - 100
//将除了选中的按钮全部改为非选中
for btn in tabBarButtons {
btn.isSelected = false
}
button.isSelected = true
//切换控制器选中图片的动画
//防止循环引用
weak var weakSelf = self
UIView.animate(withDuration: 0.3) {
weakSelf!.selectImgV?.frame = CGRect(x: CGFloat(weakSelf!.selectedIndex)*kButtonWidth(object: weakSelf!), y: (weakSelf!.selectImgV?.frame.origin.y)!, width: (weakSelf!.selectImgV?.frame.size.width)!, height: (weakSelf!.selectImgV?.frame.size.height)!)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//子类化一个按钮
class VerticalButton: UIButton {
var subLable:UILabel? //按钮标题
var subImageView:UIImageView? //按钮的图片视图
var normalImg:UIImage? //保存默认图片
var selectImg:UIImage? //保存选中图片
//重写带frame参数的init构造方法
override init(frame: CGRect) {
super.init(frame: frame)
//按钮标题
subLable = UILabel(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height*0.3))
subLable?.textAlignment = NSTextAlignment.center
subLable?.textColor = UIColor.white
subLable?.font = UIFont.systemFont(ofSize: 12)
self.addSubview(subLable!)
//按钮图片
subImageView = UIImageView(frame: CGRect(x: 0, y: (subLable?.frame.size.height)!, width: frame.size.width, height: frame.size.height*0.7))
subImageView?.contentMode = UIViewContentMode.center
self.addSubview(subImageView!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//截获按钮的点击状态的赋值方法,在点击状态发生改变的时候做一些操作
override var isSelected: Bool{
didSet{
if isSelected == true {
subImageView?.image = selectImg
}else if isSelected == false {
subImageView?.image = normalImg
}
}
}
//重写按钮添加图片的方法
override func setImage(_ image: UIImage?, for state: UIControlState) {
if state == UIControlState.normal {
//保存默认状态下的图片,并设置渲染模式为图片原始状态
normalImg = image?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
subImageView?.image = normalImg
}else if state == UIControlState.selected {
//保存选中状态下的图片
selectImg = image?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
}
}
//重写按钮添加标题的方法
override func setTitle(_ title: String?, for state: UIControlState) {
if state == UIControlState.normal {
subLable?.text = title
}
}
}
| apache-2.0 | b98203e7c288c7c3cd22cf04774d7560 | 31.965714 | 263 | 0.617091 | 4.596813 | false | false | false | false |
wisonlin/HackingDesigner | Pods/Kingfisher/Sources/Image.swift | 1 | 11011 | //
// Image.swift
// Kingfisher
//
// Created by Wei Wang on 16/1/6.
//
// Copyright (c) 2016 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(OSX)
import AppKit.NSImage
public typealias Image = NSImage
private var imagesKey: Void?
private var durationKey: Void?
#else
import UIKit.UIImage
import MobileCoreServices
public typealias Image = UIImage
#endif
import ImageIO
// MARK: - Image Properties
extension Image {
#if os(OSX)
var CGImage: CGImageRef! {
return CGImageForProposedRect(nil, context: nil, hints: nil)
}
var kf_scale: CGFloat {
return 1.0
}
private(set) var kf_images: [Image]? {
get {
return objc_getAssociatedObject(self, &imagesKey) as? [Image]
}
set {
objc_setAssociatedObject(self, &imagesKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
private(set) var kf_duration: NSTimeInterval {
get {
return objc_getAssociatedObject(self, &durationKey) as? NSTimeInterval ?? 0.0
}
set {
objc_setAssociatedObject(self, &durationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
#else
var kf_scale: CGFloat {
return scale
}
var kf_images: [Image]? {
return images
}
var kf_duration: NSTimeInterval {
return duration
}
#endif
}
// MARK: - Image Conversion
extension Image {
#if os(OSX)
static func kf_imageWithCGImage(cgImage: CGImageRef, scale: CGFloat, refImage: Image?) -> Image {
return Image(CGImage: cgImage, size: CGSize.zero)
}
/**
Normalize the image. This method does nothing in OS X.
- returns: The image itself.
*/
public func kf_normalizedImage() -> Image {
return self
}
static func kf_animatedImageWithImages(images: [Image], duration: NSTimeInterval) -> Image? {
return nil
}
#else
static func kf_imageWithCGImage(cgImage: CGImageRef, scale: CGFloat, refImage: Image?) -> Image {
if let refImage = refImage {
return Image(CGImage: cgImage, scale: scale, orientation: refImage.imageOrientation)
} else {
return Image(CGImage: cgImage, scale: scale, orientation: .Up)
}
}
/**
Normalize the image. This method will try to redraw an image with orientation and scale considered.
- returns: The normalized image with orientation set to up and correct scale.
*/
public func kf_normalizedImage() -> Image {
// prevent animated image (GIF) lose it's images
if images != nil {
return self
}
if imageOrientation == .Up {
return self
}
UIGraphicsBeginImageContextWithOptions(size, false, scale)
drawInRect(CGRect(origin: CGPoint.zero, size: size))
let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return normalizedImage
}
static func kf_animatedImageWithImages(images: [Image], duration: NSTimeInterval) -> Image? {
return Image.animatedImageWithImages(images, duration: duration)
}
#endif
}
// MARK: - PNG
func ImagePNGRepresentation(image: Image) -> NSData? {
#if os(OSX)
if let cgimage = image.CGImage {
let rep = NSBitmapImageRep(CGImage: cgimage)
return rep.representationUsingType(.NSPNGFileType, properties:[:])
}
return nil
#else
return UIImagePNGRepresentation(image)
#endif
}
// MARK: - JPEG
func ImageJPEGRepresentation(image: Image, _ compressionQuality: CGFloat) -> NSData? {
#if os(OSX)
let rep = NSBitmapImageRep(CGImage: image.CGImage)
return rep.representationUsingType(.NSJPEGFileType, properties: [NSImageCompressionFactor: compressionQuality])
#else
return UIImageJPEGRepresentation(image, compressionQuality)
#endif
}
// MARK: - GIF
func ImageGIFRepresentation(image: Image) -> NSData? {
return ImageGIFRepresentation(image, duration: 0.0, repeatCount: 0)
}
func ImageGIFRepresentation(image: Image, duration: NSTimeInterval, repeatCount: Int) -> NSData? {
guard let images = image.kf_images else {
return nil
}
let frameCount = images.count
let gifDuration = duration <= 0.0 ? image.kf_duration / Double(frameCount) : duration / Double(frameCount)
let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: gifDuration]]
let imageProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: repeatCount]]
let data = NSMutableData()
guard let destination = CGImageDestinationCreateWithData(data, kUTTypeGIF, frameCount, nil) else {
return nil
}
CGImageDestinationSetProperties(destination, imageProperties)
for image in images {
CGImageDestinationAddImage(destination, image.CGImage!, frameProperties)
}
return CGImageDestinationFinalize(destination) ? NSData(data: data) : nil
}
extension Image {
static func kf_animatedImageWithGIFData(gifData data: NSData) -> Image? {
return kf_animatedImageWithGIFData(gifData: data, scale: 1.0, duration: 0.0)
}
static func kf_animatedImageWithGIFData(gifData data: NSData, scale: CGFloat, duration: NSTimeInterval) -> Image? {
let options: NSDictionary = [kCGImageSourceShouldCache as String: NSNumber(bool: true), kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF]
guard let imageSource = CGImageSourceCreateWithData(data, options) else {
return nil
}
let frameCount = CGImageSourceGetCount(imageSource)
var images = [Image]()
var gifDuration = 0.0
for i in 0 ..< frameCount {
guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else {
return nil
}
if frameCount == 1 {
// Single frame
gifDuration = Double.infinity
} else {
// Animated GIF
guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil),
gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary,
frameDuration = (gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber) else
{
return nil
}
gifDuration += frameDuration.doubleValue
}
images.append(Image.kf_imageWithCGImage(imageRef, scale: scale, refImage: nil))
}
#if os(OSX)
if let image = Image(data: data) {
image.kf_images = images
image.kf_duration = gifDuration
return image
}
return nil
#else
return Image.kf_animatedImageWithImages(images, duration: duration <= 0.0 ? gifDuration : duration)
#endif
}
}
// MARK: - Create images from data
extension Image {
static func kf_imageWithData(data: NSData, scale: CGFloat) -> Image? {
var image: Image?
#if os(OSX)
switch data.kf_imageFormat {
case .JPEG: image = Image(data: data)
case .PNG: image = Image(data: data)
case .GIF: image = Image.kf_animatedImageWithGIFData(gifData: data, scale: scale, duration: 0.0)
case .Unknown: image = nil
}
#else
switch data.kf_imageFormat {
case .JPEG: image = Image(data: data, scale: scale)
case .PNG: image = Image(data: data, scale: scale)
case .GIF: image = Image.kf_animatedImageWithGIFData(gifData: data, scale: scale, duration: 0.0)
case .Unknown: image = nil
}
#endif
return image
}
}
// MARK: - Decode
extension Image {
func kf_decodedImage() -> Image? {
return self.kf_decodedImage(scale: kf_scale)
}
func kf_decodedImage(scale scale: CGFloat) -> Image? {
// prevent animated image (GIF) lose it's images
if kf_images != nil {
return self
}
let imageRef = self.CGImage
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue).rawValue
let context = CGBitmapContextCreate(nil, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef), 8, 0, colorSpace, bitmapInfo)
if let context = context {
let rect = CGRect(x: 0, y: 0, width: CGImageGetWidth(imageRef), height: CGImageGetHeight(imageRef))
CGContextDrawImage(context, rect, imageRef)
let decompressedImageRef = CGBitmapContextCreateImage(context)
return Image.kf_imageWithCGImage(decompressedImageRef!, scale: scale, refImage: self)
} else {
return nil
}
}
}
// MARK: - Image format
private let pngHeader: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
private let jpgHeaderSOI: [UInt8] = [0xFF, 0xD8]
private let jpgHeaderIF: [UInt8] = [0xFF]
private let gifHeader: [UInt8] = [0x47, 0x49, 0x46]
enum ImageFormat {
case Unknown, PNG, JPEG, GIF
}
extension NSData {
var kf_imageFormat: ImageFormat {
var buffer = [UInt8](count: 8, repeatedValue: 0)
self.getBytes(&buffer, length: 8)
if buffer == pngHeader {
return .PNG
} else if buffer[0] == jpgHeaderSOI[0] &&
buffer[1] == jpgHeaderSOI[1] &&
buffer[2] == jpgHeaderIF[0]
{
return .JPEG
} else if buffer[0] == gifHeader[0] &&
buffer[1] == gifHeader[1] &&
buffer[2] == gifHeader[2]
{
return .GIF
}
return .Unknown
}
}
| mit | 4fb2972097cc2cb98c939c58c3d8acdf | 32.165663 | 151 | 0.636636 | 4.584097 | false | false | false | false |
IvanVorobei/RateApp | SPRateApp - project/SPRateApp/sparrow/ui/views/views/SPAligmentView.swift | 1 | 8754 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
class SPAligmentView: UIView {
var minSpace: CGFloat = 0
var maxItemSideSize: CGFloat?
var spaceFactor: CGFloat = 0.07
var aliment: Aliment
required init?(coder aDecoder: NSCoder) {
self.aliment = .vertical
super.init(coder: aDecoder)
}
init(aliment: Aliment) {
self.aliment = aliment
super.init(frame: CGRect.zero)
}
override func layoutSubviews() {
super.layoutSubviews()
let countViews: CGFloat = CGFloat(self.subviews.count)
var itemWidth: CGFloat = 0
var itemHeight: CGFloat = 0
var space: CGFloat = 0
switch self.aliment {
case .horizontal:
itemHeight = self.frame.height
space = self.frame.width * self.spaceFactor
if space < self.minSpace {
space = self.minSpace
}
let spaceForButton = self.frame.width - (space * (countViews - 1))
itemHeight = spaceForButton / countViews
if self.maxItemSideSize != nil {
if (itemHeight > self.maxItemSideSize!) {
itemHeight = self.maxItemSideSize!
if countViews > 1 {
space = (self.frame.width - (itemHeight * countViews)) / (countViews - 1)
} else {
space = 0
}
}
}
case .vertical:
itemWidth = self.frame.width
space = self.frame.height * self.spaceFactor
if space < self.minSpace {
space = self.minSpace
}
let spaceForButton = self.frame.height - (space * (countViews - 1))
itemHeight = spaceForButton / countViews
if self.maxItemSideSize != nil {
if (itemHeight > self.maxItemSideSize!) {
itemHeight = self.maxItemSideSize!
if countViews > 1 {
space = (self.frame.height - (itemHeight * countViews)) / (countViews - 1)
} else {
space = 0
}
}
}
}
var xPoint: CGFloat = 0
var yPoint: CGFloat = 0
for (index, view) in self.subviews.enumerated() {
switch self.aliment {
case .horizontal:
xPoint = CGFloat(index) * (itemWidth + space)
case .vertical:
yPoint = CGFloat(index) * (itemHeight + space)
}
view.frame = CGRect.init(
x: xPoint, y: yPoint,
width: itemWidth,
height: itemHeight
)
}
}
enum Aliment {
case vertical
case horizontal
}
}
class SPCenteringAligmentView: SPAligmentView {
override func layoutSubviews() {
super.layoutSubviews()
if self.subviews.count == 0 {
return
}
var itemHeight: CGFloat = self.subviews[0].frame.height
var itemWidth: CGFloat = self.subviews[0].frame.width
let countViews: CGFloat = CGFloat(self.subviews.count)
if countViews < 3 {
switch self.aliment {
case .horizontal:
switch self.subviews.count {
case 1:
self.subviews[0].center.x = self.frame.width / 2
case 2:
let allFreeSpace = self.frame.width - (itemWidth * countViews)
var space = allFreeSpace / 2
if space < self.minSpace {
space = self.minSpace
itemWidth = (self.frame.width - (space * 2)) / 2
}
self.subviews[0].frame = CGRect.init(x: space / 2, y: self.subviews[0].frame.origin.y, width: itemWidth, height: self.subviews[0].frame.height)
self.subviews[1].frame = CGRect.init(x: space / 2 + itemWidth + space, y: self.subviews[1].frame.origin.y, width: itemWidth, height: self.subviews[1].frame.height)
default:
break
}
case .vertical:
switch self.subviews.count {
case 1:
self.subviews[0].center.y = self.frame.height / 2
case 2:
let allFreeSpace = self.frame.height - (itemHeight * countViews)
var space = allFreeSpace / 2
if space < self.minSpace {
space = self.minSpace
itemHeight = (self.frame.height - (space * 2)) / 2
}
self.subviews[0].frame = CGRect.init(x: self.subviews[0].frame.origin.x, y: space / 2, width: self.subviews[0].frame.width, height: itemHeight)
self.subviews[1].frame = CGRect.init(x: self.subviews[1].frame.origin.x, y: (space / 2) + itemHeight + space, width: self.subviews[1].frame.width, height: itemHeight)
default:
break
}
}
}
}
}
class SPDinamicAligmentView: UIView {
var aliment: Aliment
var itemSideSize: CGFloat = 50
var space: CGFloat = 10
var needSize: CGSize {
get {
self.layoutSubviews()
switch aliment {
case .horizontal:
return CGSize.init(width: ((self.subviews.last?.frame.origin.x) ?? 0) + ((self.subviews.last?.frame.width) ?? 0), height: (self.subviews.last?.frame.height) ?? 0)
case .vertical:
return CGSize.init(width: (self.subviews.last?.frame.width) ?? 0, height: (self.subviews.last?.frame.bottomYPosition) ?? 0)
}
}
}
required init?(coder aDecoder: NSCoder) {
self.aliment = .vertical
super.init(coder: aDecoder)
}
init(aliment: Aliment) {
self.aliment = aliment
super.init(frame: CGRect.zero)
}
override func layoutSubviews() {
super.layoutSubviews()
var xPoint: CGFloat = 0
var yPoint: CGFloat = 0
var itemWidth: CGFloat = 0
var itemHeight: CGFloat = 0
for (index, view) in self.subviews.enumerated() {
switch self.aliment {
case .horizontal:
xPoint = CGFloat(index) * (self.itemSideSize + space)
itemWidth = self.itemSideSize
itemHeight = self.frame.height
case .vertical:
yPoint = CGFloat(index) * (self.itemSideSize + space)
itemWidth = self.frame.width
itemHeight = self.itemSideSize
}
view.frame = CGRect.init(
x: xPoint, y: yPoint,
width: itemWidth,
height: itemHeight
)
}
var needSideSize: CGFloat = 0
let lastView = self.subviews.last
if lastView != nil {
switch self.aliment {
case .horizontal:
needSideSize = lastView!.frame.origin.x + lastView!.frame.width
self.setWidth(needSideSize)
break
case .vertical:
needSideSize = lastView!.frame.origin.y + lastView!.frame.height
self.setHeight(needSideSize)
break
}
}
}
enum Aliment {
case vertical
case horizontal
}
}
| mit | e430ddc550dcca8b792cf07d6f246533 | 35.623431 | 186 | 0.536845 | 4.670758 | false | false | false | false |
openHPI/xikolo-ios | iOS/Data/Model/Actions/Actions.swift | 1 | 4058 | //
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import UIKit
struct Action {
let title: String
let image: UIImage?
let handler: () -> Void
init(title: String, image: UIImage? = nil, handler: @escaping (() -> Void)) {
self.title = title
self.image = image
self.handler = handler
}
enum Image {
static var download: UIImage? {
if #available(iOS 13, *) {
return UIImage(systemName: "square.and.arrow.down")
} else {
return nil
}
}
static var aggregatedDownload: UIImage? {
if #available(iOS 13, *) {
return UIImage(systemName: "square.and.arrow.down.on.square")
} else {
return nil
}
}
static var stop: UIImage? {
if #available(iOS 13, *) {
return UIImage(systemName: "xmark.circle")
} else {
return nil
}
}
static var delete: UIImage? {
if #available(iOS 13, *) {
return UIImage(systemName: "trash")
} else {
return nil
}
}
static var share: UIImage? {
if #available(iOS 13, *) {
return UIImage(systemName: "square.and.arrow.up")
} else {
return nil
}
}
static var calendar: UIImage? {
if #available(iOS 13, *) {
return UIImage(systemName: "calendar")
} else {
return nil
}
}
static var helpdesk: UIImage? {
if #available(iOS 13, *) {
return UIImage(systemName: "questionmark.circle")
} else {
return nil
}
}
static var markAsRead: UIImage? {
if #available(iOS 13, *) {
return UIImage(systemName: "checkmark.circle")
} else {
return nil
}
}
static var open: UIImage? {
if #available(iOS 13, *) {
return UIImage(systemName: "arrow.right.circle")
} else {
return nil
}
}
static var unenroll: UIImage? {
if #available(iOS 13, *) {
return UIImage(systemName: "xmark.diamond")
} else {
return nil
}
}
static var markAsCompleted: UIImage? {
if #available(iOS 13, *) {
return UIImage(systemName: "checkmark.seal")
} else {
return nil
}
}
static var notification: UIImage? {
if #available(iOS 13, *) {
return UIImage(systemName: "app.badge")
} else {
return nil
}
}
// swiftlint:disable:next identifier_name
static var ok: UIImage? {
if #available(iOS 13, *) {
return UIImage(systemName: "checkmark")
} else {
return nil
}
}
static var cancel: UIImage? {
if #available(iOS 13, *) {
return UIImage(systemName: "xmark")
} else {
return nil
}
}
}
}
extension UIAlertAction {
convenience init(action: Action) {
self.init(title: action.title, style: .default) { _ in action.handler() }
}
}
@available(iOS 13.0, *)
extension UIAction {
convenience init(action: Action) {
self.init(title: action.title, image: action.image) { _ in action.handler() }
}
}
extension Array where Element == Action {
func asAlertActions() -> [UIAlertAction] {
return self.map(UIAlertAction.init(action:))
}
@available(iOS 13.0, *)
func asActions() -> [UIMenuElement] {
return self.map(UIAction.init(action:))
}
}
| gpl-3.0 | 5a52038527063c65f2f3fbda004580f2 | 23.737805 | 85 | 0.468326 | 4.663218 | false | false | false | false |
pierreg256/ticTacSprite | ticTacSprite/GameController.swift | 1 | 3300 | //
// GameController.swift
// ticTacSprite
//
// Created by Gilot, Pierre on 29/09/2015.
// Copyright © 2015 Pierre Gilot. All rights reserved.
//
import UIKit
import XCGLogger
import GameplayKit
class GameController: GameSceneDelegate {
private var board = BoardController()
private var minMax = GKMinmaxStrategist()
private var me = Player.X()
//private var currentUser = Player.X()
private let log = XCGLogger.defaultInstance()
private var scene:GameScene?
init() {
log.debug("Initializing GameController")
minMax.gameModel = board
minMax.maxLookAheadDepth = 3
}
//MARK: - GameScene Delegate methods
func gameScene(gameScene:GameScene, didSelectPosition:Position) {
log.info("Selecting cell:\(didSelectPosition.row), \(didSelectPosition.column)")
if me != board.activePlayer as! Player {
return
}
let (success, message) = board.addMove(didSelectPosition)
if success == true {
gameScene.presentBoardCellAt(didSelectPosition, forUser: (board.activePlayer as! Player).opponent, animated: true)
self.scene = gameScene
nextTurn()
} else {
log.warning(message)
}
}
private func nextTurn() {
switch board.status {
case .Playable:
if me != board.activePlayer as! Player {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) {
//TODO: Implement AI here
let move:Move = self.minMax.bestMoveForPlayer(self.board.activePlayer!) as! Move
self.log.debug("best move: \(move.pos), \(move.value)")
dispatch_async(dispatch_get_main_queue()) {
self.board.applyGameModelUpdate(move)
self.scene?.presentBoardCellAt(move.pos, forUser: (self.board.activePlayer as! Player).opponent, animated: true)
self.nextTurn()
}
}
}
case .Full:
showMessage("Nobody won... try again!")
default:
if board.isWinForPlayer(Player.X()) {
showMessage("The X's won... Hurray!")
} else {
showMessage("The O's won... Great!")
}
}
}
private func showMessage(message:String) -> Void {
let alert = UIAlertController(title: "Game Over!", message: message, preferredStyle: UIAlertControllerStyle.ActionSheet)
let okButton = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { (okSelected) -> Void in
self.log.debug("Ok Selected")
self.reset()
}
alert.addAction(okButton)
if var topController = UIApplication.sharedApplication().keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
topController.presentViewController(alert, animated: true, completion: nil)
// topController should now be your topmost view controller
}
}
private func reset() {
board.clear()
}
}
| mit | a30dcc4027f6e5a0370b83316639563a | 34.858696 | 136 | 0.591088 | 4.880178 | false | false | false | false |
aitorbf/Curso-Swift | Is It Prime/Is It Prime/ViewController.swift | 1 | 2010 | //
// ViewController.swift
// Is It Prime
//
// Created by Aitor Baragaño Fernández on 22/9/15.
// Copyright © 2015 Aitor Baragaño Fernández. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var number: UITextField!
@IBOutlet weak var resultLabel: UILabel!
@IBAction func buttonPressed(sender: AnyObject) {
let numberInt = Int(number.text!)
if numberInt != nil {
let unwrappedNumber = numberInt!
resultLabel.textColor = UIColor.blackColor()
var isPrime = true;
if unwrappedNumber == 1 {
isPrime = false
}
if unwrappedNumber != 2 && unwrappedNumber != 1 {
for var i = 2; i < unwrappedNumber; i++ {
if unwrappedNumber % i == 0 {
isPrime = false;
}
}
}
if isPrime == true {
resultLabel.text = "\(unwrappedNumber) is prime!"
} else {
resultLabel.text = "\(unwrappedNumber) is not prime!"
}
} else {
resultLabel.textColor = UIColor.redColor()
resultLabel.text = "Please enter a number in the box"
}
number.resignFirstResponder()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | e3a97e2c232b99c81502288680290bc0 | 24.0625 | 80 | 0.450374 | 6.246106 | false | false | false | false |
oxozle/oxkit-swift | Sources/Core/Localization.swift | 1 | 2429 | //
// Localization.swift
// OXKit
//
// Created by Dmitriy Azarov on 29/12/2016.
// Copyright © 2016 Oxozle. All rights reserved.
//
import Foundation
final class LocalizeTableKeysCache {
static let i = LocalizeTableKeysCache()
fileprivate var dict: [String: String]
fileprivate init() {
dict = [String: String]()
}
func getTable(_ key: String) -> String {
if let exist = dict[key] {
return exist
}
if let textRange = key.range(of: ".") {
let table = String(key[..<textRange.lowerBound])
dict[key] = table
return table
}
return ""
}
}
public extension String {
/// Localizae string
public func localized() -> String {
// let selectedLanguage = QRKit.application.language
// if let path = Bundle.main.path(forResource: selectedLanguage, ofType: "lproj"),
// let bundle = Bundle(path: path) {
// return NSLocalizedString(self,
// tableName: LocalizeTableKeysCache.i.getTable(self),
// bundle: bundle,
// value: self,
// comment: self)
// }
// return self
return NSLocalizedString(self,
tableName: LocalizeTableKeysCache.i.getTable(self),
bundle: Bundle.main,
value: self,
comment: self)
}
/// Localizae string with arguments
///
/// - parameter arguments: string format arguments
public func localizedFormat(_ arguments: CVarArg...) -> String {
let template = self.localized()
return String(format: template, arguments: arguments)
}
/// True if string starts with prefix
///
/// - parameter string: prefix
public func startsWith(_ string: String) -> Bool {
guard let range = range(of: string, options:[.anchored, .caseInsensitive]) else {
return false
}
return range.lowerBound == startIndex
}
/// True if string contains another string
///
/// - Parameter other: find string
public func contains(_ other: String) -> Bool {
return (self as NSString).contains(other)
}
}
| mit | 4a24b9dc0038a2cbb87d48d83b1a4e3a | 28.609756 | 90 | 0.525124 | 4.924949 | false | false | false | false |
jvivas/OraChallenge | OraChallenge/OraChallenge/ViewControllers/BaseViewController.swift | 1 | 2010 | //
// BaseViewController.swift
// OraChallenge
//
// Created by Jorge Vivas on 3/6/17.
// Copyright © 2017 JorgeVivas. All rights reserved.
//
import UIKit
import SwiftMessages
import EGGProgressHUD
class BaseViewController: UIViewController {
let progressHud = EGGProgressHUD()
override func viewDidLoad() {
super.viewDidLoad()
customHud()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func isValidText(text:String) -> Bool {
if text.characters.count == 0 {
return false
}
return true
}
func showErrorMessage(message: String) {
let view = MessageView.viewFromNib(layout: .TabView)
view.configureTheme(.error)
view.button?.isHidden = true
view.configureContent(title: "Error", body: message)
SwiftMessages.show(config: getMessageConfig(), view: view)
}
func showSuccessMessage(message: String) {
let view = MessageView.viewFromNib(layout: .TabView)
view.configureTheme(.success)
view.button?.isHidden = true
view.configureContent(title: "Success", body: message)
SwiftMessages.show(config: getMessageConfig(), view: view)
}
func getMessageConfig () -> SwiftMessages.Config {
var config = SwiftMessages.defaultConfig
config.presentationStyle = .bottom
config.presentationContext = .window(windowLevel: UIWindowLevelNormal)
return config
}
func customHud() {
progressHud.type = EGGProgressHUD.ProgressType.progressWithBG
progressHud.style = EGGProgressHUD.SpinnerStyle.white
progressHud.bgColor = UIColor.gray
}
func startLoader(message:String) {
progressHud.showInView(self.view)
}
func stopLoader() {
progressHud.hide()
}
}
| apache-2.0 | 2a0d321496ff45d5c54ee928ca98cc8d | 26.148649 | 78 | 0.650075 | 4.80622 | false | true | false | false |
ceozhu/lesson_ios_mvp | Pods/Genome/Genome/Source/SettableOperator.swift | 3 | 9594 | //
// Genome
//
// Created by Logan Wright
// Copyright © 2016 lowriDevs. All rights reserved.
//
// MIT
//
import PureJsonSerializer
// MARK: Casting
prefix operator <~ {}
// MARK: Settable Transform
// MARK: Extraction
extension Map {
// MARK: Transforms
public func extract<T, JsonInputType: JsonConvertibleType>(keyType: KeyType, transformer: JsonInputType throws -> T) throws -> T {
return try <~self[keyType].transformFromJson(transformer)
}
public func extract<T, JsonInputType: JsonConvertibleType>(keyType: KeyType, transformer: JsonInputType? throws -> T) throws -> T {
return try <~self[keyType].transformFromJson(transformer)
}
// MARK: Optional Extractions
public func extract<T : JsonConvertibleType>(keyType: KeyType) throws -> T? {
return try <~self[keyType]
}
public func extract<T : JsonConvertibleType>(keyType: KeyType) throws -> [T]? {
return try <~self[keyType]
}
public func extract<T : JsonConvertibleType>(keyType: KeyType) throws -> [[T]]? {
return try <~self[keyType]
}
public func extract<T : JsonConvertibleType>(keyType: KeyType) throws -> [String : T]? {
return try <~self[keyType]
}
public func extract<T : JsonConvertibleType>(keyType: KeyType) throws -> [String : [T]]? {
return try <~self[keyType]
}
public func extract<T : JsonConvertibleType>(keyType: KeyType) throws -> Set<T>? {
return try <~self[keyType]
}
// MARK: Non Optional Extractions
public func extract<T : JsonConvertibleType>(keyType: KeyType) throws -> T {
return try <~self[keyType]
}
public func extract<T : JsonConvertibleType>(keyType: KeyType) throws -> [T] {
return try <~self[keyType]
}
public func extract<T : JsonConvertibleType>(keyType: KeyType) throws -> [[T]] {
return try <~self[keyType]
}
public func extract<T : JsonConvertibleType>(keyType: KeyType) throws -> [String : T] {
return try <~self[keyType]
}
public func extract<T : JsonConvertibleType>(keyType: KeyType) throws -> [String : [T]] {
return try <~self[keyType]
}
public func extract<T : JsonConvertibleType>(keyType: KeyType) throws -> Set<T> {
return try <~self[keyType]
}
}
/// ****
public prefix func <~ <T: JsonConvertibleType>(map: Map) throws -> T? {
try enforceMapType(map, expectedType: .FromJson)
guard let _ = map.result else { return nil } // Ok for Optionals to return nil
return try <~map as T
}
public prefix func <~ <T: JsonConvertibleType>(map: Map) throws -> [T]? {
try enforceMapType(map, expectedType: .FromJson)
guard let _ = map.result else { return nil } // Ok for Optionals to return nil
return try <~map as [T]
}
public prefix func <~ <T: JsonConvertibleType>(map: Map) throws -> [[T]]? {
try enforceMapType(map, expectedType: .FromJson)
guard let _ = map.result else { return nil } // Ok for Optionals to return nil
return try <~map as [[T]]
}
public prefix func <~ <T: JsonConvertibleType>(map: Map) throws -> [String : T]? {
try enforceMapType(map, expectedType: .FromJson)
guard let _ = map.result else { return nil } // Ok for Optionals to return nil
return try <~map as [String : T]
}
public prefix func <~ <T: JsonConvertibleType>(map: Map) throws -> [String : [T]]? {
try enforceMapType(map, expectedType: .FromJson)
guard let _ = map.result else { return nil } // Ok for Optionals to return nil
return try <~map as [String : [T]]
}
public prefix func <~ <T: JsonConvertibleType>(map: Map) throws -> Set<T>? {
try enforceMapType(map, expectedType: .FromJson)
guard let _ = map.result else { return nil } // Ok for Optionals to return nil
return try <~map as Set<T>
}
// MARK: Non-Optional Casters
public prefix func <~ <T: JsonConvertibleType>(map: Map) throws -> T {
try enforceMapType(map, expectedType: .FromJson)
let result = try enforceResultExists(map, type: T.self)
do {
return try T.newInstance(result, context: map.context)
} catch {
let error = MappingError.UnableToMap(key: map.lastKey, error: error)
throw logError(error)
}
}
public prefix func <~ <T: JsonConvertibleType>(map: Map) throws -> [T] {
try enforceMapType(map, expectedType: .FromJson)
let result = try enforceResultExists(map, type: [T].self)
return try [T](js: result, context: map.context)
}
public prefix func <~ <T: JsonConvertibleType>(map: Map) throws -> [[T]] {
try enforceMapType(map, expectedType: .FromJson)
let result = try enforceResultExists(map, type: [[T]].self)
let array = result.arrayValue ?? [result]
// TODO: Better logic? If we just have an array, and not an array of arrays, auto convert to array of arrays here.
let possibleArrayOfArrays = array.flatMap { $0.arrayValue }
let isAlreadyAnArrayOfArrays = possibleArrayOfArrays.count == array.count
let arrayOfArrays: [[Json]] = isAlreadyAnArrayOfArrays ? possibleArrayOfArrays : [array]
return try arrayOfArrays.map { try [T](js: $0, context: map.context) }
}
public prefix func <~ <T: JsonConvertibleType>(map: Map) throws -> [String : T] {
try enforceMapType(map, expectedType: .FromJson)
let jsonDictionary = try expectJsonDictionaryWithMap(map, targetType: [String : T].self)
var mappedDictionary: [String : T] = [:]
for (key, value) in jsonDictionary {
let mappedValue = try T.newInstance(value, context: map.context)
mappedDictionary[key] = mappedValue
}
return mappedDictionary
}
public prefix func <~ <T: JsonConvertibleType>(map: Map) throws -> [String : [T]] {
try enforceMapType(map, expectedType: .FromJson)
let jsonDictionaryOfArrays = try expectJsonDictionaryOfArraysWithMap(map, targetType: [String : [T]].self)
var mappedDictionaryOfArrays: [String : [T]] = [:]
for (key, value) in jsonDictionaryOfArrays {
let mappedValue = try [T](js: value, context: map.context)
mappedDictionaryOfArrays[key] = mappedValue
}
return mappedDictionaryOfArrays
}
public prefix func <~ <T: JsonConvertibleType>(map: Map) throws -> Set<T> {
try enforceMapType(map, expectedType: .FromJson)
let result = try enforceResultExists(map, type: T.self)
let jsonArray = result.arrayValue ?? [result]
return Set<T>(try [T](js: Json.from(jsonArray), context: map.context))
}
// MARK: Transformables
public prefix func <~ <JsonInputType: JsonConvertibleType, T>(transformer: FromJsonTransformer<JsonInputType, T>) throws -> T {
try enforceMapType(transformer.map, expectedType: .FromJson)
return try transformer.transformValue(transformer.map.result)
}
// MARK: Enforcers
private func enforceMapType(map: Map, expectedType: Map.OperationType) throws {
if map.type != expectedType {
throw logError(MappingError.UnexpectedOperationType("Received mapping operation of type: \(map.type) expected: \(expectedType)"))
}
}
private func enforceResultExists<T>(map: Map, type: T.Type) throws -> Json {
if let result = map.result {
return result
} else {
let message = "Key: \(map.lastKey) TargetType: \(T.self)"
let error = SequenceError.FoundNil(message)
throw logError(error)
}
}
private func unexpectedResult<T, U>(result: Any, expected: T.Type, keyPath: KeyType, targetType: U.Type) -> ErrorType {
let message = "Found: \(result) Expected: \(T.self) KeyPath: \(keyPath) TargetType: \(U.self)"
let error = SequenceError.UnexpectedValue(message)
return error
}
private func expectJsonDictionaryWithMap<T>(map: Map, targetType: T.Type) throws -> [String : Json] {
let result = try enforceResultExists(map, type: T.self)
if let j = result.objectValue {
return j
} else {
let error = unexpectedResult(result, expected: [String : Json].self, keyPath: map.lastKey, targetType: T.self)
throw logError(error)
}
}
private func expectJsonDictionaryOfArraysWithMap<T>(map: Map, targetType: T.Type) throws -> [String : [Json]] {
let result = try enforceResultExists(map, type: T.self)
guard let object = result.objectValue else {
let error = unexpectedResult(result, expected: [String : AnyObject].self, keyPath: map.lastKey, targetType: T.self)
throw logError(error)
}
var mutable: [String : [Json]] = [:]
object.forEach { key, value in
let array = value.arrayValue ?? [value]
mutable[key] = array
}
return mutable
}
// MARK: Deprecations
prefix operator <~? {}
@available(*, deprecated=1.0.9, renamed="<~")
public prefix func <~? <T: JsonConvertibleType>(map: Map) throws -> T? {
return try <~map
}
@available(*, deprecated=1.0.9, renamed="<~")
public prefix func <~? <T: JsonConvertibleType>(map: Map) throws -> [T]? {
return try <~map
}
@available(*, deprecated=1.0.9, renamed="<~")
public prefix func <~? <T: JsonConvertibleType>(map: Map) throws -> [[T]]? {
return try <~map
}
@available(*, deprecated=1.0.9, renamed="<~")
public prefix func <~? <T: JsonConvertibleType>(map: Map) throws -> [String : T]? {
return try <~map
}
@available(*, deprecated=1.0.9, renamed="<~")
public prefix func <~? <T: JsonConvertibleType>(map: Map) throws -> [String : [T]]? {
return try <~map
}
@available(*, deprecated=1.0.9, renamed="<~")
public prefix func <~? <T: JsonConvertibleType>(map: Map) throws -> Set<T>? {
return try <~map
}
| apache-2.0 | 1f31b75cd616fb1a59931409c144ca23 | 34.010949 | 137 | 0.659231 | 3.890105 | false | false | false | false |
Romdeau4/16POOPS | iOS_app/Help's Kitchen/HostSeatingController.swift | 1 | 4281 | //
// HostSeatingController.swift
// Help's Kitchen
//
// Created by Stephen Ulmer on 2/15/17.
// Copyright © 2017 Stephen Ulmer. All rights reserved.
//
import UIKit
import Firebase
class HostSeatingController: CustomTableViewController {
let ref = FIRDatabase.database().reference(fromURL: "https://helps-kitchen.firebaseio.com/")
struct TableStatus {
var status : String!
var tables: [Table]!
}
var availableTables = TableStatus()
var seatedTables = TableStatus()
var tableArray = [TableStatus]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(CustomTableCell.self, forCellReuseIdentifier: "cell")
initTableStructs()
fetchTables()
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(handleLogout))
}
func handleLogout() {
do{
try FIRAuth.auth()?.signOut()
}catch let logoutError {
print(logoutError)
}
dismiss(animated: true, completion: nil)
}
func initTableStructs() {
availableTables.status = "Available"
seatedTables.status = "Seated"
availableTables.tables = [Table]()
seatedTables.tables = [Table]()
tableArray.append(availableTables)
tableArray.append(seatedTables)
}
func fetchTables() {
ref.child("tables").observeSingleEvent(of: .value , with: { (snapshot) in
print(snapshot)
for eachTable in snapshot.children {
let table = Table()
if let dict = (eachTable as! FIRDataSnapshot).value as? [String : AnyObject] {
table.name = dict["tableName"] as! String?
table.key = (eachTable as!FIRDataSnapshot).key
table.status = dict["tableStatus"] as! String?
if(table.status == "available"){
self.tableArray[0].tables.append(table)
}else if table.status == "seated"{
self.tableArray[1].tables.append(table)
}
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
})
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return tableArray.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return tableArray[section].status
}
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.tintColor = CustomColor.amber500
(view as! UITableViewHeaderFooterView).textLabel?.textColor = UIColor.black
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return tableArray[section].tables.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = tableArray[indexPath.section].tables[indexPath.row].name
cell.textLabel?.textColor = CustomColor.amber500
cell.backgroundColor = UIColor.black
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let assignToTableController = AssignToTableController()
assignToTableController.selectedTable = tableArray[indexPath.section].tables[indexPath.row]
let navController = UINavigationController(rootViewController: assignToTableController)
ref.child("misc").child("seatingQueue")
present(navController, animated: true, completion: nil)
}
}
| mit | 1c06c580ca31ba3cdb9769c35d3dfbcb | 32.968254 | 137 | 0.601636 | 5.251534 | false | false | false | false |
superpeteblaze/BikeyProvider | Code/Providers/CityProvider.swift | 1 | 7350 | //
// Created by Pete Smith
// http://www.petethedeveloper.com
//
//
// License
// Copyright © 2016-present Pete Smith
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import CoreLocation
/**
### CityProvider
Provides methods for fetching the nearest bike station cities,
based on the parameters passed (e.g Current locaion)
*/
public struct CityProvider {
/**
Get all available cities
- parameter location: The location used to calculate the nearest cities
- parameter success: Success closure
- parameter failure: Failure closure
*/
@discardableResult public static func city(near location: CLLocation,
withCompletion completion: @escaping (Result<City>) -> Void) -> URLSessionDataTask? {
let completion = { (result: Result<CityList>) in
switch result {
case .success(let cityList):
// Now calculate the nearest city based on user's location
let nearestCityAndDistance = cityList.cities.map({ ($0, distance(from: location, to: $0.location.coordinates)) }).min() {
$0.1 < $1.1
}
// Call our success closuse with with the nearest city if we have it or nil
if let city = nearestCityAndDistance?.0 {
completion(.success(city))
} else {
completion(.failure(CityError.noCityNearLocation))
}
case .failure(let error):
completion(.failure(error))
}
}
return CityProvider.allCities(withCompletion: completion)
}
/**
Get the nearest cities, bound by limit, based on the location passed
- parameter location: The location used to calculate the nearest cities
- parameter limit: The number of nearest cities to fetching
- parameter successClosure: Success closure
- parameter failureClosure: Failure closure
*/
@discardableResult public static func cities(near location: CLLocation, limit: Int,
withCompletion completion: @escaping (Result<CityList>) -> Void) -> URLSessionDataTask? {
let completion = { (result: Result<CityList>) in
switch result {
case .success(let cityList):
// Now calculate the nearest city based on user's location
let nearestCities = cityList.cities.map({ ($0, distance(from: location, to: $0.location.coordinates)) }).sorted(by: { $0.1 < $1.1 }).map() { return $0.0 }
// Return early with all sorted cities if the number of cities we want (our limit) is greater than the total number of cities
guard limit < nearestCities.count else {
let nearestCityList = CityList(cities: nearestCities)
completion(.success(nearestCityList))
return
}
let limitedCities = nearestCities[0..<limit]
let limitedCityList = CityList(cities: Array(limitedCities))
completion(.success(limitedCityList))
case .failure(let error):
completion(.failure(error))
}
}
return CityProvider.allCities(withCompletion: completion)
}
/**
Get the nearest cities, bound by limit, based on the location passed,
and within a certain radius
- parameter location: The location used to calculate the nearest cities
- parameter radius: The radius in metres
- parameter limit: The number of nearest cities to fetching
- parameter successClosure: Success closure
- parameter failureClosure: Failure closure
*/
@discardableResult public static func cities(near location: CLLocation,
within radius: Double, limit: Int,
withCompletion completion: @escaping (Result<CityList>) -> Void) -> URLSessionDataTask? {
let completion = { (result: Result<CityList>) in
switch result {
case .success(let cityList):
// Now calculate cities within the radius parameter
let citiesAndDistances = cityList.cities.map({ ($0, distance(from: location, to: $0.location.coordinates)) })
let citiesWithinRadius = citiesAndDistances.filter( { $0.1 < radius } ).map() { return $0.0 }
// Call our success closure
if citiesWithinRadius.count > 0 {
guard limit < citiesWithinRadius.count else {
let radiusCityList = CityList(cities: citiesWithinRadius)
completion(.success(radiusCityList))
return
}
let limitedCities = citiesWithinRadius[0..<limit]
let limitedCityList = CityList(cities: Array(limitedCities))
completion(.success(limitedCityList))
} else if let nearestCityAndDistance = citiesAndDistances.min( by: { $0.1 < $1.1 } ) {
let nearestCityList = CityList(cities: [nearestCityAndDistance.0])
completion(.success(nearestCityList))
} else {
completion(.failure(CityError.noCityNearLocation))
}
case .failure(let error):
completion(.failure(error))
}
}
return CityProvider.allCities(withCompletion: completion)
}
/**
Get all available bike station cities
- parameter successClosure: Success closure
- parameter failureClosure: Failure closure
*/
@discardableResult public static func allCities(withCompletion completion: @escaping (Result<CityList>) -> Void) -> URLSessionDataTask? {
let url = Constants.API.baseURL + Constants.API.networks
return APIClient.get(from: url, withCompletion: { result in
switch result {
case .success(let data):
let decoder = JSONDecoder()
if let cityList = try? decoder.decode(CityList.self, from: data), cityList.cities.count > 0 {
completion(.success(cityList))
}
case .failure(_):
completion(.failure(CityError.noCitiesRetrieved))
}
})
}
/**
Calculate the distance between two locations
- parameter locationA: From
- parameter locationB: To
- returns: Distance between locations
*/
fileprivate static func distance(from locationA: CLLocation, to locationB: CLLocation) -> CLLocationDistance {
return locationA.distance(from: locationB)
}
}
| mit | a869aed1f4254d992e3da8fa701ba52b | 37.883598 | 170 | 0.549326 | 5.5548 | false | false | false | false |
evolutional/flatbuffers | swift/Sources/FlatBuffers/Constants.swift | 1 | 3015 | /*
* Copyright 2021 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.
*/
#if os(Linux)
import CoreFoundation
#else
import Foundation
#endif
/// A boolean to see if the system is littleEndian
let isLitteEndian = CFByteOrderGetCurrent() == Int(CFByteOrderLittleEndian.rawValue)
/// Constant for the file id length
let FileIdLength = 4
/// Type aliases
public typealias Byte = UInt8
public typealias UOffset = UInt32
public typealias SOffset = Int32
public typealias VOffset = UInt16
/// Maximum size for a buffer
public let FlatBufferMaxSize = UInt32.max << ((MemoryLayout<SOffset>.size * 8 - 1) - 1)
/// Protocol that All Scalars should conform to
///
/// Scalar is used to conform all the numbers that can be represented in a FlatBuffer. It's used to write/read from the buffer.
public protocol Scalar: Equatable {
associatedtype NumericValue
var convertedEndian: NumericValue { get }
}
extension Scalar where Self: Verifiable {}
extension Scalar where Self: FixedWidthInteger {
/// Converts the value from BigEndian to LittleEndian
///
/// Converts values to little endian on machines that work with BigEndian, however this is NOT TESTED yet.
public var convertedEndian: NumericValue {
self as! Self.NumericValue
}
}
extension Double: Scalar, Verifiable {
public typealias NumericValue = UInt64
public var convertedEndian: UInt64 {
bitPattern.littleEndian
}
}
extension Float32: Scalar, Verifiable {
public typealias NumericValue = UInt32
public var convertedEndian: UInt32 {
bitPattern.littleEndian
}
}
extension Bool: Scalar, Verifiable {
public var convertedEndian: UInt8 {
self == true ? 1 : 0
}
public typealias NumericValue = UInt8
}
extension Int: Scalar, Verifiable {
public typealias NumericValue = Int
}
extension Int8: Scalar, Verifiable {
public typealias NumericValue = Int8
}
extension Int16: Scalar, Verifiable {
public typealias NumericValue = Int16
}
extension Int32: Scalar, Verifiable {
public typealias NumericValue = Int32
}
extension Int64: Scalar, Verifiable {
public typealias NumericValue = Int64
}
extension UInt8: Scalar, Verifiable {
public typealias NumericValue = UInt8
}
extension UInt16: Scalar, Verifiable {
public typealias NumericValue = UInt16
}
extension UInt32: Scalar, Verifiable {
public typealias NumericValue = UInt32
}
extension UInt64: Scalar, Verifiable {
public typealias NumericValue = UInt64
}
public func FlatBuffersVersion_2_0_0() {}
| apache-2.0 | 250c25c90c34271ab04614f55d393644 | 25.447368 | 127 | 0.751244 | 4.34438 | false | false | false | false |
dongdonggaui/BiblioArchiver | Carthage/Checkouts/Fuzi/Fuzi/Error.swift | 1 | 1961 | // Error.swift
// Copyright (c) 2015 Ce Zheng
//
// 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 libxml2
/**
* XMLError enumeration.
*/
public enum XMLError: Error {
/// No error
case noError
/// Contains a libxml2 error with error code and message
case libXMLError(code: Int, message: String)
/// Failed to convert String to bytes using given string encoding
case invalidData
/// XML Parser failed to parse the document
case parserFailure
internal static func lastError(_ defaultError: XMLError = .noError) -> XMLError {
let errorPtr = xmlGetLastError()
guard errorPtr != nil else {
return defaultError
}
let message = String(cString: (errorPtr?.pointee.message)!).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let code = Int((errorPtr?.pointee.code)!)
xmlResetError(errorPtr)
return .libXMLError(code: code, message: message ?? "")
}
}
| mit | dc94b1b2f3238dca7ec1f482159b926b | 39.854167 | 123 | 0.742478 | 4.560465 | false | false | false | false |
mypalal84/GoGoGithub | GoGoGithub/GoGoGithub/FoundationExtensions.swift | 1 | 1210 | //
// FoundationExtensions.swift
// GoGoGithub
//
// Created by A Cahn on 4/3/17.
// Copyright © 2017 A Cahn. All rights reserved.
//
import Foundation
extension UserDefaults {
//get access token
func getAccessToken() -> String? {
guard let token = UserDefaults.standard.string(forKey: "access_token") else { return nil }
return token
}
//save access token
func save(accessToken: String) -> Bool {
UserDefaults.standard.set(accessToken, forKey: "access_token")
return UserDefaults.standard.synchronize()
}
}
extension String {
func validate() -> Bool {
let pattern = "[^0-9a-zA-Z_-]"
do{
let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let range = NSRange(location: 0, length: self.characters.count)
let matches = regex.numberOfMatches(in: self, options: .reportCompletion, range: range)
if matches > 0 {
return false
}
return true
} catch {
return false
}
}
}
| mit | 8af64afdbb1fdc557c867193b5e8a3e6 | 22.705882 | 99 | 0.543424 | 4.759843 | false | false | false | false |
gtranchedone/FlickrParty | FlickrParty/PhotosViewController.swift | 1 | 5900 | //
// PhotosViewController.swift
// FlickrParty
//
// Created by Gianluca Tranchedone on 04/05/2015.
// Copyright (c) 2015 Gianluca Tranchedone. All rights reserved.
//
import UIKit
import Haneke
let ThumbailsFormatName = "thumbnails"
let PhotoCellReuseIdentifier = "PhotoCellReuseIdentifier"
public class PhotosViewController: BaseCollectionViewController, UICollectionViewDelegateFlowLayout {
private let maxInMemoryPhotos = 20
public let imageCache = Cache<UIImage>(name: "PhotoImagesCache")
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
public convenience init() {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.sectionInset = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0)
flowLayout.minimumInteritemSpacing = 10.0
flowLayout.minimumLineSpacing = 10.0
self.init(collectionViewLayout: flowLayout)
}
public override init(collectionViewLayout layout: UICollectionViewLayout) {
super.init(collectionViewLayout: layout)
imageCache.addFormat(Format<UIImage>(name: ThumbailsFormatName, diskCapacity: 50 * 1024 * 1024, transform: nil)) // capacity of 50MB
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func viewDidLoad() {
imageCache.removeAll() // to avoid crash with some issue in Haneke
super.viewDidLoad()
self.collectionView?.backgroundColor = UIColor.whiteColor()
self.collectionView!.registerClass(PhotoCollectionViewCell.self, forCellWithReuseIdentifier: PhotoCellReuseIdentifier)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didBecomeActive", name: UIApplicationDidBecomeActiveNotification, object: nil)
}
// MARK: - UICollectionViewDelegate -
public override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoCellReuseIdentifier, forIndexPath: indexPath) as! PhotoCollectionViewCell
dataSource!.itemAtIndexPath(indexPath) { fetchedPhoto in
let photo = fetchedPhoto as! Photo
if let thumbnailURL = photo.thumbnailURL {
let imageFetcher = NetworkFetcher<UIImage>(URL: thumbnailURL)
self.imageCache.fetch(fetcher: imageFetcher, formatName: ThumbailsFormatName).onSuccess { image in
let newIndexPath = collectionView.indexPathForCell(cell)
if let theIndexPath = newIndexPath {
if theIndexPath == indexPath {
cell.imageView.image = image
}
}
else {
cell.imageView.image = image
}
}
}
}
return cell
}
public override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let photo = dataSource!.itemAtIndexPath(indexPath) as! Photo
let viewController = PhotoDetailsViewController(photo: photo)
viewController.hidesBottomBarWhenPushed = true
self.showViewController(viewController, sender: indexPath)
}
public override func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
loadMorePhotosIfNeeded(indexPath)
cachePhotosThatAreNotNeededForDisplayInCollectionView(collectionView, referenceIndexPath: indexPath)
}
// MARK: - UICollectionViewFlowLayoutDelegate -
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
let sectionInsets = flowLayout.sectionInset.left + flowLayout.sectionInset.right
let sideLenght = ((collectionView.bounds.size.width - sectionInsets - (flowLayout.minimumInteritemSpacing * 2)) / 3)
return CGSizeMake(sideLenght, sideLenght)
}
// MARK: - Private -
private func loadMorePhotosIfNeeded(indexPath: NSIndexPath) {
if (indexPath.item == (self.dataSource!.numberOfItems() - 1)) {
if let metadata = self.dataSource!.lastMetadata {
if metadata.page < metadata.numberOfPages {
self.dataSource!.fetchContent(metadata.page + 1)
}
}
}
}
private func cachePhotosThatAreNotNeededForDisplayInCollectionView(collectionView: UICollectionView, referenceIndexPath indexPath: NSIndexPath) {
let visibleIndexPaths = collectionView.indexPathsForVisibleItems()
guard !visibleIndexPaths.isEmpty else { return }
let firstVisibleIndexPath = visibleIndexPaths.first!
let scrollingDown = (indexPath.item - firstVisibleIndexPath.item) > 0
var indexPathToCache: NSIndexPath!
if scrollingDown {
indexPathToCache = NSIndexPath(forItem: indexPath.item - maxInMemoryPhotos, inSection: 0)
}
else {
indexPathToCache = NSIndexPath(forItem: indexPath.item + maxInMemoryPhotos, inSection: 0)
}
if (indexPathToCache.item >= 0 && indexPathToCache.item < dataSource?.numberOfItems()) {
dataSource?.cacheItemAtIndexPath(indexPathToCache)
}
}
// MARK: Notifications
func didBecomeActive() {
if let dataSource = self.dataSource {
if dataSource.numberOfItems() <= 0 && !dataSource.loading {
self.reloadData()
}
}
}
}
| mit | 5d388054d2975d201004b45e40645d81 | 43.029851 | 176 | 0.679322 | 5.882353 | false | false | false | false |
wordpress-mobile/AztecEditor-iOS | Aztec/Classes/Extensions/NSTextingResult+Helpers.swift | 2 | 1018 | import Foundation
public extension NSTextCheckingResult {
/// Returns the match for the corresponding capture group position in a text
///
/// - Parameters:
/// - position: the capture group position
/// - text: the string where the match was detected
/// - Returns: the string with the captured group text
///
func captureGroup(in position: Int, text: String) -> String? {
guard position < numberOfRanges else {
return nil
}
#if swift(>=4.0)
let nsrange = self.range(at: position)
#else
let nsrange = self.rangeAt(position)
#endif
guard nsrange.location != NSNotFound else {
return nil
}
let range = text.range(fromUTF16NSRange: nsrange)
#if swift(>=4.0)
let captureGroup = String(text[range])
#else
let captureGroup = text.substring(with: range)
#endif
return captureGroup
}
}
| mpl-2.0 | 4c4d8c29b386ed62540cea337f2fa16e | 26.513514 | 80 | 0.566798 | 4.847619 | false | false | false | false |
practicalswift/swift | stdlib/public/core/Join.swift | 5 | 5811 | //===--- Join.swift - Protocol and Algorithm for concatenation ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A sequence that presents the elements of a base sequence of sequences
/// concatenated using a given separator.
@_fixed_layout // lazy-performance
public struct JoinedSequence<Base : Sequence> where Base.Element : Sequence {
public typealias Element = Base.Element.Element
@usableFromInline // lazy-performance
internal var _base: Base
@usableFromInline // lazy-performance
internal var _separator: ContiguousArray<Element>
/// Creates an iterator that presents the elements of the sequences
/// traversed by `base`, concatenated using `separator`.
///
/// - Complexity: O(`separator.count`).
@inlinable // lazy-performance
public init<Separator : Sequence>(base: Base, separator: Separator)
where Separator.Element == Element {
self._base = base
self._separator = ContiguousArray(separator)
}
}
extension JoinedSequence {
/// An iterator that presents the elements of the sequences traversed
/// by a base iterator, concatenated using a given separator.
@_fixed_layout // lazy-performance
public struct Iterator {
@usableFromInline // lazy-performance
internal var _base: Base.Iterator
@usableFromInline // lazy-performance
internal var _inner: Base.Element.Iterator?
@usableFromInline // lazy-performance
internal var _separatorData: ContiguousArray<Element>
@usableFromInline // lazy-performance
internal var _separator: ContiguousArray<Element>.Iterator?
@_frozen // lazy-performance
@usableFromInline // lazy-performance
internal enum _JoinIteratorState {
case start
case generatingElements
case generatingSeparator
case end
}
@usableFromInline // lazy-performance
internal var _state: _JoinIteratorState = .start
/// Creates a sequence that presents the elements of `base` sequences
/// concatenated using `separator`.
///
/// - Complexity: O(`separator.count`).
@inlinable // lazy-performance
public init<Separator: Sequence>(base: Base.Iterator, separator: Separator)
where Separator.Element == Element {
self._base = base
self._separatorData = ContiguousArray(separator)
}
}
}
extension JoinedSequence.Iterator: IteratorProtocol {
public typealias Element = Base.Element.Element
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@inlinable // lazy-performance
public mutating func next() -> Element? {
while true {
switch _state {
case .start:
if let nextSubSequence = _base.next() {
_inner = nextSubSequence.makeIterator()
_state = .generatingElements
} else {
_state = .end
return nil
}
case .generatingElements:
let result = _inner!.next()
if _fastPath(result != nil) {
return result
}
_inner = _base.next()?.makeIterator()
if _inner == nil {
_state = .end
return nil
}
if !_separatorData.isEmpty {
_separator = _separatorData.makeIterator()
_state = .generatingSeparator
}
case .generatingSeparator:
let result = _separator!.next()
if _fastPath(result != nil) {
return result
}
_state = .generatingElements
case .end:
return nil
}
}
}
}
extension JoinedSequence: Sequence {
/// Return an iterator over the elements of this sequence.
///
/// - Complexity: O(1).
@inlinable // lazy-performance
public __consuming func makeIterator() -> Iterator {
return Iterator(base: _base.makeIterator(), separator: _separator)
}
@inlinable // lazy-performance
public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {
var result = ContiguousArray<Element>()
let separatorSize = _separator.count
if separatorSize == 0 {
for x in _base {
result.append(contentsOf: x)
}
return result
}
var iter = _base.makeIterator()
if let first = iter.next() {
result.append(contentsOf: first)
while let next = iter.next() {
result.append(contentsOf: _separator)
result.append(contentsOf: next)
}
}
return result
}
}
extension Sequence where Element : Sequence {
/// Returns the concatenated elements of this sequence of sequences,
/// inserting the given separator between each element.
///
/// This example shows how an array of `[Int]` instances can be joined, using
/// another `[Int]` instance as the separator:
///
/// let nestedNumbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
/// let joined = nestedNumbers.joined(separator: [-1, -2])
/// print(Array(joined))
/// // Prints "[1, 2, 3, -1, -2, 4, 5, 6, -1, -2, 7, 8, 9]"
///
/// - Parameter separator: A sequence to insert between each of this
/// sequence's elements.
/// - Returns: The joined sequence of elements.
@inlinable // lazy-performance
public __consuming func joined<Separator : Sequence>(
separator: Separator
) -> JoinedSequence<Self>
where Separator.Element == Element.Element {
return JoinedSequence(base: self, separator: separator)
}
}
| apache-2.0 | 26c55d1876e92608ba7e084acaa0c7ae | 31.283333 | 80 | 0.643779 | 4.611905 | false | false | false | false |
nathantannar4/Parse-Dashboard-for-iOS-Pro | Pods/BiometricAuthentication/BiometricAuthentication/BiometricAuthentication/Constants/BiometricAuthenticationConstants.swift | 1 | 1847 | //
// BiometricAuthenticationConstants.swift
// BiometricAuthentication
//
// Created by Rushi on 27/10/17.
// Copyright © 2017 Rushi Sangani. All rights reserved.
//
import Foundation
import LocalAuthentication
/// success block
public typealias AuthenticationSuccess = (() -> ())
/// failure block
public typealias AuthenticationFailure = ((AuthenticationError) -> ())
let kBiometryNotAvailableReason = "Biometric authentication is not available for this device."
/// **************** Touch ID ****************** ///
let kTouchIdAuthenticationReason = "Confirm your fingerprint to authenticate."
let kTouchIdPasscodeAuthenticationReason = "Touch ID is locked now, because of too many failed attempts. Enter passcode to unlock Touch ID."
/// Error Messages Touch ID
let kSetPasscodeToUseTouchID = "Please set device passcode to use Touch ID for authentication."
let kNoFingerprintEnrolled = "There are no fingerprints enrolled in the device. Please go to Device Settings -> Touch ID & Passcode and enroll your fingerprints."
let kDefaultTouchIDAuthenticationFailedReason = "Touch ID does not recognize your fingerprint. Please try again with your enrolled fingerprint."
/// **************** Face ID ****************** ///
let kFaceIdAuthenticationReason = "Confirm your face to authenticate."
let kFaceIdPasscodeAuthenticationReason = "Face ID is locked now, because of too many failed attempts. Enter passcode to unlock Face ID."
/// Error Messages Face ID
let kSetPasscodeToUseFaceID = "Please set device passcode to use Face ID for authentication."
let kNoFaceIdentityEnrolled = "There is no face enrolled in the device. Please go to Device Settings -> Face ID & Passcode and enroll your face."
let kDefaultFaceIDAuthenticationFailedReason = "Face ID does not recognize your face. Please try again with your enrolled face."
| mit | 7cc1dd32a1bf8f07c517885973cfddfe | 47.578947 | 162 | 0.755146 | 4.794805 | false | false | false | false |
lukevanin/OCRAI | CardScanner/UIAlertController+Document.swift | 1 | 4663 | //
// UIAlertController+Document.swift
// CardScanner
//
// Created by Luke Van In on 2017/03/12.
// Copyright © 2017 Luke Van In. All rights reserved.
//
import UIKit
import MessageUI
import Contacts
class DocumentMailComposerDelegate: NSObject, MFMailComposeViewControllerDelegate {
private var viewController: UIViewController
init(viewController: UIViewController) {
self.viewController = viewController
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
viewController.dismiss(animated: true, completion: nil)
}
}
extension UIViewController {
func presentActionsAlertForDocument(document: Document) {
let controller = UIAlertController(
title: document.title,
message: nil,
preferredStyle: .actionSheet
)
// Fragment actions
for fragment in document.allFields {
switch (fragment.type, fragment.value) {
case (.phoneNumber, let .some(value)):
if let action = makeActionForPhoneNumber(value) {
controller.addAction(action)
}
case (.email, let .some(value)):
if let action = makeActionForEmail(value) {
controller.addAction(action)
}
case (.url, let .some(value)):
if let action = makeActionForURL(value) {
controller.addAction(action)
}
default:
break
}
}
// Share actions
if let action = makeShareAction(for: document) {
controller.addAction(action)
}
// Dismiss action
controller.addAction(makeDismissAction())
self.present(controller, animated: true, completion: nil)
}
private func makeActionForPhoneNumber(_ value: String) -> UIAlertAction? {
guard let url = URL(string: value) else {
return nil
}
return UIAlertAction(
title: "Call \(value)",
style: .default,
handler: { (action) in
UIApplication.shared.open(url, options: [:], completionHandler: nil)
})
}
private func makeActionForEmail(_ value: String) -> UIAlertAction? {
guard let components = URLComponents(string: value), MFMailComposeViewController.canSendMail() else {
return nil
}
let emailAddress = components.path
return UIAlertAction(
title: "Email \(emailAddress)",
style: .default,
handler: { (action) in
let controller = MFMailComposeViewController()
controller.setToRecipients([emailAddress])
self.present(controller, animated: true, completion: nil)
})
}
private func makeActionForURL(_ value: String) -> UIAlertAction? {
guard let url = URL(string: value) else {
return nil
}
return UIAlertAction(
title: "\(value)",
style: .default,
handler: { (action) in
UIApplication.shared.open(url, options: [:], completionHandler: nil)
})
}
private func makeShareAction(for document: Document) -> UIAlertAction? {
let contact = document.contact
guard
let filename = CNContactFormatter.string(from: contact, style: .fullName),
let data = try? CNContactVCardSerialization.data(with: [contact]),
let directory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first
else {
return nil
}
return UIAlertAction(
title: "Share Contact",
style: .default,
handler: { (action) in
let file = directory.appendingPathComponent(filename).appendingPathExtension("vcf")
try! data.write(to: file, options: [.atomic])
let controller = UIActivityViewController(
activityItems: [file],
applicationActivities: nil
)
self.present(controller, animated: true, completion: nil)
})
}
private func makeDismissAction() -> UIAlertAction {
return UIAlertAction(
title: "Dismiss",
style: .cancel,
handler: { (action) in
})
}
}
| mit | 88ab83f4c37affd7a0d2f6b285bcd34e | 31.375 | 133 | 0.556628 | 5.603365 | false | false | false | false |
benjamincongdon/TubeSync | TubeSync/ContentViewController.swift | 1 | 6029 | //
// ContentViewController.swift
// Playlist Sync
//
// Created by Benjamin Congdon on 1/11/16.
// Copyright © 2016 Benjamin Congdon. All rights reserved.
//
import Cocoa
class ContentViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSource {
var delegate:AppDelegate?
@IBOutlet weak var stopSyncButton: NSButton!
@IBOutlet weak var downloadProgressIndicator: NSProgressIndicator!
@IBOutlet weak var spinningActivityIndicator: NSProgressIndicator!
@IBOutlet weak var lastSyncLabel: NSTextField!
@IBOutlet weak var downloadProgressTextField: NSTextField!
@IBOutlet weak var downloadingStaticLabel: NSTextField!
@IBAction func syncPressed(sender: NSButton) {
delegate?.syncTimerFired()
tableView.reloadData()
}
@IBAction func goToPreferences(sender: AnyObject) {
// let menu = NSMenu(title: "Sync")
// menu.insertItem(NSMenuItem(title: "Test", action: "preferences", keyEquivalent: ""), atIndex: 0)
// NSMenu.popUpContextMenu(menu, withEvent: NSApplication.sharedApplication().currentEvent!, forView: self.view)
preferences()
}
func preferences(){
let delegate:AppDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
delegate.openPreferences()
}
@IBOutlet weak var tableView: NSTableView!
@IBAction func stopSync(sender: AnyObject) {
delegate!.syncHelper.haltSync()
}
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = (NSApp.delegate as! AppDelegate)
self.onPlaylistsChanged(nil)
print(self.delegate!.playlists)
tableView.reloadData()
//Receive notifications from Preferences that playlist list has changed
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onPlaylistsChanged:", name: PlaylistListUpdate, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onDownloadUpdate:", name: PlaylistDownloadProgressNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onSyncStart:", name: SyncInitiatedNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onSyncEnd:", name: SyncCompletionNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "receivedCurrentFileName:", name: CurrentDownloadFileName, object: nil)
}
func onSyncStart(notification:NSNotification){
lastSyncLabel.stringValue = "In progress..."
spinningActivityIndicator.startAnimation(self)
downloadingStaticLabel.hidden = false
downloadProgressIndicator.hidden = false
spinningActivityIndicator.hidden = false
dispatch_async(GlobalMainQueue){
self.tableView.reloadData()
}
stopSyncButton.hidden = false
}
func onSyncEnd(notification:NSNotification){
lastSyncLabel.stringValue = NSDate().description
spinningActivityIndicator.stopAnimation(self)
downloadProgressTextField.stringValue = ""
downloadingStaticLabel.hidden = true
downloadProgressIndicator.hidden = true
spinningActivityIndicator.hidden = true
dispatch_async(GlobalMainQueue){
self.tableView.reloadData()
}
stopSyncButton.hidden = true
}
func onDownloadUpdate(notification:NSNotification){
if let playlist = notification.object as? Playlist{
dispatch_async(GlobalMainQueue){
self.tableView.reloadData()
}
downloadProgressIndicator.maxValue = Double(playlist.entries.count)
downloadProgressIndicator.doubleValue = Double(playlist.progress!)
//downloadProgressTextField.stringValue = "\(playlist.title) (\(playlist.progress!) of \(playlist.entries.count))"
}
}
func receivedCurrentFileName(notification:NSNotification){
if let fileName = notification.object as? String {
downloadProgressTextField.stringValue = fileName
}
}
func onPlaylistsChanged(notification:NSNotification?){
tableView.reloadData()
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
if let delegate = self.delegate {
if tableColumn?.identifier == "playlist"{
let cellView = tableView.makeViewWithIdentifier("playlist", owner: self) as! NSTableCellView
cellView.textField?.stringValue = delegate.playlists[row].title
let currentPlaylist = delegate.playlists[row]
if currentPlaylist.progress > 0 && currentPlaylist.progress < currentPlaylist.entries.count {
cellView.textField?.stringValue = delegate.playlists[row].title + " (\(currentPlaylist.progress) out of \(currentPlaylist.entries.count))"
}
return cellView
}
else {
let imgView = tableView.makeViewWithIdentifier("status", owner: self) as! NSTableCellView
if delegate.playlists[row].progress == -1 {
imgView.imageView?.image = NSImage(named: "complete")
}
else if delegate.playlists[row].progress > 0 {
imgView.imageView?.image = NSImage(named: "refresh")
}
else{
imgView.imageView?.image = NSImage(named: "outOfSync")
}
return imgView
}
}
return NSView()
}
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
if let delegate = self.delegate{
return delegate.playlists.count
}
return 0
}
}
| mit | 664183cdd78526657a00598e68fae4f5 | 37.394904 | 158 | 0.646151 | 5.670743 | false | false | false | false |
yoonhg84/CPSelectionManager | Source/CPSelectionManager.swift | 1 | 2310 | //
// Created by Chope on 2016. 4. 27..
// Copyright (c) 2016 Chope. All rights reserved.
//
import UIKit
public enum CPSelectionType {
case single
case multiple
case limitedMultiple(Int)
}
public enum CPSelectionErrorType: Error {
case wrongSelectionType
}
open class CPSelectionManager {
open var selectionType = CPSelectionType.single {
didSet {
self.unselectAll()
}
}
open var changedSelection: ((CPSelectionManager) -> ())? = nil
internal var controls = [UIControl]()
open func add(control: UIControl) -> CPSelectionManager {
control.addTarget(self, action: #selector(touchUpInside(at:)), for: UIControlEvents.touchUpInside)
self.controls.append(control)
return self
}
open func removeAllControls() -> CPSelectionManager {
self.controls.removeAll()
return self
}
open func selectAll() throws {
switch self.selectionType {
case .multiple:
if self.countOfSelection() != self.controls.count {
for control in self.controls {
control.isSelected = true
}
self.changedSelection?(self);
}
default:
throw CPSelectionErrorType.wrongSelectionType
}
}
open func unselectAll() {
for control in self.controls {
control.isSelected = false
}
self.changedSelection?(self);
}
open func selectedControls() -> [UIControl] {
return self.controls.filter({ $0.isSelected })
}
open func countOfSelection() -> Int {
return self.selectedControls().count
}
@objc func touchUpInside(at control: UIControl) {
switch self.selectionType {
case .single:
self.unselectAll()
control.isSelected = !control.isSelected
case .multiple:
control.isSelected = !control.isSelected
case .limitedMultiple(let maxCount):
if control.isSelected {
control.isSelected = false
} else if self.countOfSelection() < maxCount {
control.isSelected = !control.isSelected
} else {
return
}
}
self.changedSelection?(self);
}
}
| mit | 2e1c692e594774e0aefeda68c3312805 | 25.860465 | 106 | 0.58961 | 4.925373 | false | false | false | false |
marcw/volte-ios | VolteCore/TimelineDownloader.swift | 1 | 6170 | //
// TimelineContentProvider.swift
// Volte
//
// Created by Romain Pouclet on 2016-10-11.
// Copyright © 2016 Perfectly-Cooked. All rights reserved.
//
import Foundation
import ReactiveSwift
import SwiftyJSON
import Result
import MailCore
import CoreData
public enum TimelineError: Error {
case internalError
case authenticationError
case decodingError(UInt32)
}
public func ==(lhs: TimelineError, rhs: TimelineError) -> Bool {
switch (lhs, rhs) {
case (.internalError, .internalError): return true
case (.authenticationError, .authenticationError): return true
case (.decodingError(let message1), .decodingError(let message2)) where message1 == message2: return true
default: return true
}
}
public class TimelineDownloader {
private let session = MCOIMAPSession()
private let storageController: StorageController
public init(account: Account, storageController: StorageController) {
session.hostname = "voltenetwork.xyz"
session.port = 993
session.connectionType = .TLS
session.username = account.username
session.password = account.password
self.storageController = storageController
}
public func fetchShallowMessages(start: UInt64 = 1) -> SignalProducer<MCOIMAPMessage, TimelineError> {
print("Fetching shallow messages")
return SignalProducer { sink, disposable in
let uids = MCOIndexSet(range: MCORangeMake(start, UINT64_MAX))
let operation = self.session.fetchMessagesOperation(withFolder: "INBOX", requestKind: .structure, uids: uids)
operation?.start { (error, messages, vanishedMessages) in
if let error = error as? NSError, error.code == MCOErrorCode.authentication.rawValue {
sink.send(error: .authenticationError)
} else if let _ = error {
sink.send(error: .internalError)
} else if let messages = messages {
messages.forEach { sink.send(value: $0) }
sink.sendCompleted()
} else {
sink.send(error: .internalError)
}
}
disposable.add {
operation?.cancel()
}
}
}
public func fetchMessage(with uid: UInt32) -> SignalProducer<Message, TimelineError> {
print("Fetching message with id \(uid)")
let operation = self.session.fetchMessageOperation(withFolder: "INBOX", uid: uid)!
return operation.reactive.fetch()
.flatMapError { _ in return SignalProducer<MCOMessageParser, TimelineError>(error: .decodingError(uid)) }
.attemptMap { message in
guard let parts = (message.mainPart() as? MCOMultipart)?.parts as? [MCOAttachment] else {
print("Invalid content for message \(uid)")
return Result(error: TimelineError.decodingError(uid))
}
let from = message.header.from.mailbox
let date = message.header.date
guard let voltePart = parts.filter({ $0.mimeType == "application/ld+json" }).first else {
print("No main content for message \(uid)")
return Result(error: TimelineError.decodingError(uid))
}
// Build the main message
let payload = JSON(data: voltePart.data)
let message = Message(entity: Message.entity(), insertInto: nil)
message.author = from
message.content = payload["text"].string
message.postedAt = date as NSDate?
message.uid = Int32(uid)
print("Creating message \(uid) - \(message.content)")
// Extract attachments
let attachments: [MCOAttachment] = parts.filter { $0.mimeType == "image/jpg" }
let savedAttachments = attachments.map { messageAttachment -> Attachment in
let attachment = Attachment(entity: Attachment.entity(), insertInto: nil)
attachment.data = messageAttachment.data as NSData?
attachment.message = message
return attachment
}
message.addToAttachments(NSSet(array: savedAttachments))
print("Message has \(message.attachments?.count) attachments")
return Result(value: message)
}
.flatMapError { error in
print("Got error \(error)")
return SignalProducer.empty
}
}
public func fetchItems() -> SignalProducer<[Message], TimelineError> {
print("Fetching all messages")
let context = self.storageController.container.newBackgroundContext()
return self.storageController
.lastFetchedUID()
.promoteErrors(TimelineError.self)
.flatMap(.latest, transform: { uid in
return self.fetchShallowMessages(start: UInt64(uid + 1))
})
.flatMap(.concat, transform: { message in
return self.fetchMessage(with: message.uid)
})
.collect()
.flatMap(.latest, transform: { messages -> SignalProducer<[Message], TimelineError> in
print("Fetched \(messages.count) messages")
messages.forEach { message in
context.insert(message)
message.attachments?.forEach { attachment in
context.insert(attachment as! NSManagedObject)
}
}
return context.reactive.save()
.flatMapError { _ in SignalProducer<(),TimelineError>(error: .internalError) }
.flatMap(.latest, transform: { (_) -> SignalProducer<[Message], TimelineError> in
print("Saved background context and returning \(messages.count) messages")
return SignalProducer<[Message], TimelineError>(value: messages)
})
})
}
}
| agpl-3.0 | 767dc55fa1ae68c60afdc5138d1f54cb | 39.854305 | 121 | 0.586643 | 5.158027 | false | false | false | false |
AnarchyTools/atpkg | src/parsing/Tokenization.swift | 1 | 7033 | // Copyright (c) 2016 Anarchy Tools Contributors.
//
// 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 atfoundation
public enum TokenType {
case Identifier
case OpenParen
case CloseParen
case OpenBracket
case CloseBracket
case OpenBrace
case CloseBrace
case StringLiteral
case Terminal
case Colon
case Comment
case Unknown
case EOF
}
public func ==(lhs: Token, rhs: Token) -> Bool {
return lhs.type == rhs.type &&
lhs.line == rhs.line &&
lhs.column == rhs.column &&
lhs.value == rhs.value
}
public struct Token: Equatable {
public let value: String
public let line: Int
public let column: Int
public let type: TokenType
public init(type: TokenType, value: String = "", line: Int = 0, column: Int = 0) {
self.type = type
self.value = value
self.line = line
self.column = column
}
}
func isValidIdentifierSignalCharacter(c: Character?) -> Bool {
guard let c = c else {
return false
}
return Charset.isLetter(character: c) || Charset.isNumberDigit(character: c)
}
func isValidIdenitifierCharacter(c: Character?) -> Bool {
guard let c = c else {
return false
}
return Charset.isLetter(character: c) || Charset.isNumberDigit(character: c) || c == "-" || c == "." || c == "/"
}
func isWhitespace(c: Character?) -> Bool {
guard let c = c else {
return false
}
return Charset.isWhitespace(character: c)
}
final public class Lexer {
var scanner: Scanner
var current: Token? = nil
var shouldStall = false
public init(scanner: Scanner) {
self.scanner = scanner
}
public func next() -> Token? {
if shouldStall {
shouldStall = false
return current
}
func work() -> Token {
if scanner.next() == nil { return Token(type: .EOF) }
scanner.stall()
while let info = scanner.next(), isWhitespace(c: info.character) {}
scanner.stall()
guard let next = scanner.next() else { return Token(type: .EOF) }
if next.character == "\n" {
return Token(type: .Terminal, value: "\n", line: next.line, column: next.column)
}
else if isValidIdentifierSignalCharacter(c: next.character) {
var content = String(next.character!)
while let info = scanner.next(), isValidIdenitifierCharacter(c: info.character) {
content.append(info.character!)
}
scanner.stall()
return Token(type: .Identifier, value: content, line: next.line, column: next.column)
}
else if next.character == "(" {
return Token(type: .OpenParen, value: "(", line: next.line, column: next.column)
}
else if next.character == ")" {
return Token(type: .CloseParen, value: ")", line: next.line, column: next.column)
}
else if next.character == "[" {
return Token(type: .OpenBracket, value: "[", line: next.line, column: next.column)
}
else if next.character == "]" {
return Token(type: .CloseBracket, value: "]", line: next.line, column: next.column)
}
else if next.character == "{" {
return Token(type: .OpenBrace, value: "{", line: next.line, column: next.column)
}
else if next.character == "}" {
return Token(type: .CloseBrace, value: "}", line: next.line, column: next.column)
}
else if next.character == ":" {
return Token(type: .Colon, value: ":", line: next.line, column: next.column)
}
else if next.character == ";" {
let column = scanner.peek()!.column
let line = scanner.peek()!.line
var comment = ""
while let info = scanner.next(), info.character == ";" {}
scanner.stall()
while let info = scanner.next(), info.character != "\n" {
comment.append(info.character!)
}
return Token(type: .Comment, value: comment, line: line, column: column)
}
else if next.character == "\"" {
var content = ""
while let info = scanner.next(), info.character != "\"" {
if info.character == "\\" {
let escaped = scanner.next()
let char = escaped?.character
switch escaped?.character {
case _ where char == "t": content.append("\t"); break
case _ where char == "b": fatalError("Unsupported escape sequence: \\b")
case _ where char == "n": content.append("\n"); break
case _ where char == "r": content.append("\r"); break
case _ where char == "f": fatalError("Unsupported escape sequence: \\f")
case _ where char == "'": content.append("'"); break
case _ where char == "\"": content.append("\""); break
case _ where char == "\\": content.append("\\"); break
case _ where char == "$": content.append("\\$"); break
default:
fatalError("Unsupposed escape sequence: \\\(escaped?.character)")
}
}
else {
content.append(info.character!)
}
}
return Token(type: .StringLiteral, value: content, line: next.line, column: next.column)
}
else {
return Token(type: .Unknown, value: String(next.character!), line: next.line, column: next.column)
}
}
if self.current?.type == .EOF {
self.current = nil
}
else {
self.current = work()
}
return self.current
}
func tokenize() -> [Token] {
var tokens = [Token]()
while let token = self.next() { tokens.append(token) }
return tokens
}
public func peek() -> Token? {
return current
}
public func stall() {
shouldStall = true
}
} | apache-2.0 | 7387fbd4079c7a9e2c4372b2bd0eecfb | 32.980676 | 117 | 0.523105 | 4.605763 | false | false | false | false |
nixzhu/Wormhole | Remote WatchKit Extension/InterfaceController.swift | 2 | 1934 | //
// InterfaceController.swift
// Remote WatchKit Extension
//
// Created by NIX on 15/5/20.
// Copyright (c) 2015年 nixWork. All rights reserved.
//
import WatchKit
import Wormhole
import RemoteKit
class InterfaceController: WKInterfaceController {
@IBOutlet weak var lightStateSwitch: WKInterfaceSwitch!
@IBOutlet weak var lightLevelSlider: WKInterfaceSlider!
let wormhole = Wormhole(appGroupIdentifier: Config.Wormhole.appGroupIdentifier, messageDirectoryName: Config.Wormhole.messageDirectoryName)
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
}
override func willActivate() {
super.willActivate()
if let message = wormhole.messageWithIdentifier(Config.Wormhole.Message.lightState) {
if let lightState = message as? NSNumber {
lightStateSwitch.setOn(lightState.boolValue)
self.lightState = lightState.boolValue
}
}
if let message = wormhole.messageWithIdentifier(Config.Wormhole.Message.lightLevel) {
if let lightLevel = message as? NSNumber {
lightLevelSlider.setValue(lightLevel.floatValue)
self.lightLevel = lightLevel.floatValue
}
}
}
override func didDeactivate() {
super.didDeactivate()
}
typealias LightState = Bool
var lightState: LightState = false {
didSet {
wormhole.passMessage(NSNumber(bool: lightState), withIdentifier: Config.Wormhole.Message.lightState)
}
}
var lightLevel: Float = 2 {
didSet {
wormhole.passMessage(NSNumber(float: lightLevel), withIdentifier: Config.Wormhole.Message.lightLevel)
}
}
@IBAction func switchLight(value: Bool) {
lightState = !lightState
}
@IBAction func changeLightLevels(value: Float) {
lightLevel = value
}
}
| mit | 7c5ea966b940cfaa2743b8d4fc988e49 | 27.835821 | 143 | 0.666667 | 4.77037 | false | true | false | false |
newtonstudio/cordova-plugin-device | imgly-sdk-ios-master/imglyKit/Frontend/Editor/IMGLYFocusEditorViewController.swift | 1 | 9249 | //
// IMGLYFocusEditorViewController.swift
// imglyKit
//
// Created by Sascha Schwabbauer on 13/04/15.
// Copyright (c) 2015 9elements GmbH. All rights reserved.
//
import UIKit
public class IMGLYFocusEditorViewController: IMGLYSubEditorViewController {
// MARK: - Properties
public private(set) lazy var offButton: IMGLYImageCaptionButton = {
let bundle = NSBundle(forClass: self.dynamicType)
let button = IMGLYImageCaptionButton()
button.textLabel.text = NSLocalizedString("focus-editor.off", tableName: nil, bundle: bundle, value: "", comment: "")
button.imageView.image = UIImage(named: "icon_focus_off", inBundle: bundle, compatibleWithTraitCollection: nil)
button.setTranslatesAutoresizingMaskIntoConstraints(false)
button.addTarget(self, action: "turnOff:", forControlEvents: .TouchUpInside)
return button
}()
public private(set) lazy var linearButton: IMGLYImageCaptionButton = {
let bundle = NSBundle(forClass: self.dynamicType)
let button = IMGLYImageCaptionButton()
button.textLabel.text = NSLocalizedString("focus-editor.linear", tableName: nil, bundle: bundle, value: "", comment: "")
button.imageView.image = UIImage(named: "icon_focus_linear", inBundle: bundle, compatibleWithTraitCollection: nil)
button.setTranslatesAutoresizingMaskIntoConstraints(false)
button.addTarget(self, action: "activateLinear:", forControlEvents: .TouchUpInside)
return button
}()
public private(set) lazy var radialButton: IMGLYImageCaptionButton = {
let bundle = NSBundle(forClass: self.dynamicType)
let button = IMGLYImageCaptionButton()
button.textLabel.text = NSLocalizedString("focus-editor.radial", tableName: nil, bundle: bundle, value: "", comment: "")
button.imageView.image = UIImage(named: "icon_focus_radial", inBundle: bundle, compatibleWithTraitCollection: nil)
button.setTranslatesAutoresizingMaskIntoConstraints(false)
button.addTarget(self, action: "activateRadial:", forControlEvents: .TouchUpInside)
return button
}()
private var selectedButton: IMGLYImageCaptionButton? {
willSet(newSelectedButton) {
self.selectedButton?.selected = false
}
didSet {
self.selectedButton?.selected = true
}
}
private lazy var circleGradientView: IMGLYCircleGradientView = {
let view = IMGLYCircleGradientView()
view.gradientViewDelegate = self
view.hidden = true
view.alpha = 0
return view
}()
private lazy var boxGradientView: IMGLYBoxGradientView = {
let view = IMGLYBoxGradientView()
view.gradientViewDelegate = self
view.hidden = true
view.alpha = 0
return view
}()
// MARK: - UIViewController
override public func viewDidLoad() {
super.viewDidLoad()
let bundle = NSBundle(forClass: self.dynamicType)
navigationItem.title = NSLocalizedString("focus-editor.title", tableName: nil, bundle: bundle, value: "", comment: "")
configureButtons()
configureGradientViews()
selectedButton = offButton
if fixedFilterStack.tiltShiftFilter.tiltShiftType != .Off {
fixedFilterStack.tiltShiftFilter.tiltShiftType = .Off
updatePreviewImage()
}
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
circleGradientView.frame = view.convertRect(previewImageView.visibleImageFrame, fromView: previewImageView)
circleGradientView.centerGUIElements()
boxGradientView.frame = view.convertRect(previewImageView.visibleImageFrame, fromView: previewImageView)
boxGradientView.centerGUIElements()
}
// MARK: - Configuration
private func configureButtons() {
let buttonContainerView = UIView()
buttonContainerView.setTranslatesAutoresizingMaskIntoConstraints(false)
bottomContainerView.addSubview(buttonContainerView)
buttonContainerView.addSubview(offButton)
buttonContainerView.addSubview(linearButton)
buttonContainerView.addSubview(radialButton)
let views = [
"buttonContainerView" : buttonContainerView,
"offButton" : offButton,
"linearButton" : linearButton,
"radialButton" : radialButton
]
let metrics = [
"buttonWidth" : 90
]
// Button Constraints
buttonContainerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[offButton(==buttonWidth)][linearButton(==offButton)][radialButton(==offButton)]|", options: nil, metrics: metrics, views: views))
buttonContainerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[offButton]|", options: nil, metrics: nil, views: views))
buttonContainerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[linearButton]|", options: nil, metrics: nil, views: views))
buttonContainerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[radialButton]|", options: nil, metrics: nil, views: views))
// Container Constraints
bottomContainerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[buttonContainerView]|", options: nil, metrics: nil, views: views))
bottomContainerView.addConstraint(NSLayoutConstraint(item: buttonContainerView, attribute: .CenterX, relatedBy: .Equal, toItem: bottomContainerView, attribute: .CenterX, multiplier: 1, constant: 0))
}
private func configureGradientViews() {
view.addSubview(circleGradientView)
view.addSubview(boxGradientView)
}
// MARK: - Actions
@objc private func turnOff(sender: IMGLYImageCaptionButton) {
if selectedButton == sender {
return
}
selectedButton = sender
hideBoxGradientView()
hideCircleGradientView()
updateFilterTypeAndPreview()
}
@objc private func activateLinear(sender: IMGLYImageCaptionButton) {
if selectedButton == sender {
return
}
selectedButton = sender
hideCircleGradientView()
showBoxGradientView()
updateFilterTypeAndPreview()
}
@objc private func activateRadial(sender: IMGLYImageCaptionButton) {
if selectedButton == sender {
return
}
selectedButton = sender
hideBoxGradientView()
showCircleGradientView()
updateFilterTypeAndPreview()
}
// MARK: - Helpers
private func updateFilterTypeAndPreview() {
if selectedButton == linearButton {
fixedFilterStack.tiltShiftFilter.tiltShiftType = .Box
fixedFilterStack.tiltShiftFilter.controlPoint1 = boxGradientView.normalizedControlPoint1
fixedFilterStack.tiltShiftFilter.controlPoint2 = boxGradientView.normalizedControlPoint2
} else if selectedButton == radialButton {
fixedFilterStack.tiltShiftFilter.tiltShiftType = .Circle
fixedFilterStack.tiltShiftFilter.controlPoint1 = circleGradientView.normalizedControlPoint1
fixedFilterStack.tiltShiftFilter.controlPoint2 = circleGradientView.normalizedControlPoint2
} else if selectedButton == offButton {
fixedFilterStack.tiltShiftFilter.tiltShiftType = .Off
}
updatePreviewImage()
}
private func showCircleGradientView() {
circleGradientView.hidden = false
UIView.animateWithDuration(NSTimeInterval(0.15), animations: {
self.circleGradientView.alpha = 1.0
})
}
private func hideCircleGradientView() {
UIView.animateWithDuration(NSTimeInterval(0.15), animations: {
self.circleGradientView.alpha = 0.0
},
completion: { finished in
if(finished) {
self.circleGradientView.hidden = true
}
}
)
}
private func showBoxGradientView() {
boxGradientView.hidden = false
UIView.animateWithDuration(NSTimeInterval(0.15), animations: {
self.boxGradientView.alpha = 1.0
})
}
private func hideBoxGradientView() {
UIView.animateWithDuration(NSTimeInterval(0.15), animations: {
self.boxGradientView.alpha = 0.0
},
completion: { finished in
if(finished) {
self.boxGradientView.hidden = true
}
}
)
}
}
extension IMGLYFocusEditorViewController: IMGLYGradientViewDelegate {
public func userInteractionStarted() {
fixedFilterStack.tiltShiftFilter.tiltShiftType = .Off
updatePreviewImage()
}
public func userInteractionEnded() {
updateFilterTypeAndPreview()
}
public func controlPointChanged() {
}
}
| apache-2.0 | c7f5ac549046b8032c19750c3efb3ec0 | 36.75102 | 222 | 0.656503 | 5.489021 | false | false | false | false |
PasDeChocolat/LearningSwift | PLAYGROUNDS/LSB_D005_MapFilterReduce.playground/section-2.swift | 2 | 4274 | import UIKit
/*
// Let's implement Map, Filter, & Reduce
//
// I got the inspiration for this from a
// book or a paper, I'll try to remember
// which and post it here.
/==========================================*/
let nums = [1,2,3,4,5]
/*----------------------------------------/
// Map: Imperative Style
/----------------------------------------*/
// Add ten to each number in the array.
var mappedNums = [Int]()
for n in nums {
mappedNums.append(n * 10)
}
mappedNums
/*----------------------------------------/
// Map: Functional (Fun) Style
/----------------------------------------*/
// Pass a function
func byTen(x: Int) -> Int {
return x * 10
}
nums.map(byTen)
// Pass a closure
let closureResult = nums.map { $0 * 10 }
closureResult
// Create the `by` function on the fly
func by(n: Int) -> (Int) -> Int {
return { x in
x * 10
}
}
nums.map(by(10))
// Use the global function `map`
map(nums, byTen)
map(nums) { $0 * 10 }
map(nums, by(10))
/*----------------------------------------/
// Filter: Imperative Style
/----------------------------------------*/
// Only include the even numbers
var evens = [Int]()
for n in nums {
if n % 2 == 0 { evens.append(n) }
}
evens
/*----------------------------------------/
// Filter: Fun Style
/----------------------------------------*/
// Pass a function
func isEven(x: Int) -> Bool {
return x % 2 == 0
}
nums.filter(isEven)
// Pass a closure
let evenClosureResult = nums.filter { isEven($0) }
evenClosureResult
// Pass predicate function on the fly
let oddClosureResult = nums.filter { $0 % 2 != 0 }
oddClosureResult
// Use the global function `filter`
filter(nums, isEven)
let multiplesOfThree = filter(nums) { $0 % 3 == 0 }
multiplesOfThree
/*----------------------------------------/
// Reduce: Imperative Style
/----------------------------------------*/
// Calculating a Sum
var sum = 0
for n in nums {
sum += n
}
sum
/*----------------------------------------/
// Reduce: Fun Style
/----------------------------------------*/
// Pass a function
func adder(x: Int, y: Int) -> Int {
return x + y
}
nums.reduce(0, combine: adder)
// Pass an operator
nums.reduce(0, combine: +)
// Pass a closure
let closureSum = nums.reduce(0) { $0 + $1 }
closureSum
// Pass a new operation
let fac5 = nums.reduce(1) { $0 * $1 }
fac5
// Use the global function `reduce`
reduce(nums, 0, adder)
reduce(nums, 0, +)
reduce(nums, 0) { $0 + $1 }
/*----------------------------------------/
// Build Map from Reduce
/----------------------------------------*/
func myMap(source: [Int], transform: (Int) -> Int) -> [Int] {
return reduce(source, []) { $0 + [transform($1)] }
}
// It's just like the native `map`
myMap(nums, byTen)
let doubleResult = myMap(nums) { $0 * 2 }
doubleResult
/*----------------------------------------/
// Build Filter from Reduce
/----------------------------------------*/
func myFilter(source: [Int], includeElement: (Int) -> Bool) -> [Int] {
return reduce(source, []) { includeElement($1) ? $0 + [$1] : $0 }
}
// It's just like the native `filter`
myFilter(nums, isEven)
let myFilterEvens = myFilter(nums) { $0 % 2 == 0 }
myFilterEvens
/*----------------------------------------/
// Build a Generic Map from Reduce
/----------------------------------------*/
func genericMap<T,U>(source: [T], transform: (T) -> U) -> [U] {
return reduce(source, []) { $0 + [transform($1)] }
}
// Works on any array of elements
let byPi = genericMap([1.1, 2.2, 3.3]) { $0 * 3.14 }
byPi
let exclamations = genericMap(["cat", "dog", "ice cream"]) { $0 + "!" }
exclamations
let aarray = genericMap([[1, 2, 3], [4, 5], [6]]) { map($0, byTen) }
aarray
/*----------------------------------------/
// Build a Generic Filter from Reduce
/----------------------------------------*/
func genericFilter<T>(source: [T], includeElement: (T) -> Bool) -> [T] {
return reduce(source, []) { includeElement($1) ? $0 + [$1] : $0 }
}
// Works on any array of elements
let doubleFilterResult = genericFilter([1.1, 2.2, 3.3]) { $0 > 2 }
doubleFilterResult
let stringFilterResult = genericFilter(["dog", "mouse", "raccoon"]) { count($0) > 4 }
stringFilterResult
let charsFilterResult = genericFilter(Array("raccoon")) { $0 > "m" }
charsFilterResult
| gpl-3.0 | 11bf4712f7b14e1fd106cc9f940daec0 | 19.742718 | 85 | 0.493215 | 3.424679 | false | false | false | false |
tilltue/FSCalendar | Example-Swift/SwiftExample/DIVExampleViewController.swift | 1 | 8380 | //
// DIVViewController.swift
// SwiftExample
//
// Created by dingwenchao on 06/11/2016.
// Copyright © 2016 wenchao. All rights reserved.
//
import Foundation
enum SelectionType : Int {
case none
case single
case leftBorder
case middle
case rightBorder
}
class DIVExampleViewController: UIViewController, FSCalendarDataSource, FSCalendarDelegate, FSCalendarDelegateAppearance {
private let gregorian = NSCalendar(calendarIdentifier: .gregorian)!
private let formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
private weak var calendar: FSCalendar!
private weak var eventLabel: UILabel!
override func loadView() {
let view = UIView(frame: UIScreen.main.bounds)
view.backgroundColor = UIColor.groupTableViewBackground
self.view = view
let height: CGFloat = UIDevice.current.model.hasPrefix("iPad") ? 450 : 300
let calendar = FSCalendar(frame: CGRect(x: 0, y: self.navigationController!.navigationBar.frame.maxY, width: view.frame.size.width, height: height))
calendar.dataSource = self
calendar.delegate = self
calendar.scopeGesture.isEnabled = true
calendar.allowsMultipleSelection = true
// calendar.backgroundColor = [UIColor whiteColor];
view.addSubview(calendar)
self.calendar = calendar
calendar.calendarHeaderView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.1)
calendar.calendarWeekdayView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.1)
calendar.appearance.eventSelectionColor = UIColor.white
calendar.appearance.eventOffset = CGPoint(x: 0, y: -7)
calendar.today = nil // Hide the today circle
calendar.register(DIVCalendarCell.self, forCellReuseIdentifier: "cell")
calendar.clipsToBounds = true // Remove top/bottom line
let label = UILabel(frame: CGRect(x: 0, y: calendar.frame.maxY + 10, width: self.view.frame.size.width, height: 50))
label.textAlignment = .center
label.font = UIFont.preferredFont(forTextStyle: .subheadline)
self.view.addSubview(label)
self.eventLabel = label
let attributedText = NSMutableAttributedString(string: "")
let attatchment = NSTextAttachment()
attatchment.image = UIImage(named: "icon_cat")!
attatchment.bounds = CGRect(x: 0, y: -3, width: attatchment.image!.size.width, height: attatchment.image!.size.height)
attributedText.append(NSAttributedString(attachment: attatchment))
attributedText.append(NSAttributedString(string: " Hey Daily Event "))
attributedText.append(NSAttributedString(attachment: attatchment))
self.eventLabel.attributedText = attributedText
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "FSCalendar"
// [self.calendar selectDate:[self.gregorian dateByAddingUnit:NSCalendarUnitDay value:1 toDate:[NSDate date] options:0]];
// Uncomment this to perform an 'initial-week-scope'
// self.calendar.scope = FSCalendarScopeWeek;
}
deinit {
print("\(#function)")
}
func calendar(_ calendar: FSCalendar, cellFor date: Date, at position: FSCalendarMonthPosition) -> FSCalendarCell {
let cell = calendar.dequeueReusableCell(withIdentifier: "cell", for: date, at: position)
return cell
}
func calendar(_ calendar: FSCalendar, willDisplay cell: FSCalendarCell, for date: Date, at position: FSCalendarMonthPosition) {
let divCell = (cell as! DIVCalendarCell)
// Custom today circle
divCell.circleImageView.isHidden = !self.gregorian.isDateInToday(date)
// Configure selection layer
if position == .current || calendar.scope == .week {
divCell.eventIndicator.isHidden = false
var selectionType = SelectionType.none
if calendar.selectedDates.contains(date) {
let previousDate = self.gregorian.date(byAdding: .day, value: -1, to: date, options: NSCalendar.Options(rawValue: 0))!
let nextDate = self.gregorian.date(byAdding: .day, value: 1, to: date, options: NSCalendar.Options(rawValue: 0))!
if calendar.selectedDates.contains(date) {
if calendar.selectedDates.contains(previousDate) && calendar.selectedDates.contains(nextDate) {
selectionType = .middle
}
else if calendar.selectedDates.contains(previousDate) && calendar.selectedDates.contains(date) {
selectionType = .rightBorder
}
else if calendar.selectedDates.contains(nextDate) {
selectionType = .leftBorder
}
else {
selectionType = .single
}
}
}
else {
selectionType = .none
}
if selectionType == .none {
divCell.selectionLayer.isHidden = true
return
}
divCell.selectionLayer.isHidden = false
if selectionType == .middle {
divCell.selectionLayer.path = UIBezierPath(rect: divCell.selectionLayer.bounds).cgPath
}
else if selectionType == .leftBorder {
divCell.selectionLayer.path = UIBezierPath(roundedRect: divCell.selectionLayer.bounds, byRoundingCorners: [.topLeft, .bottomLeft], cornerRadii: CGSize(width: divCell.selectionLayer.frame.width / 2, height: divCell.selectionLayer.frame.width / 2)).cgPath
}
else if selectionType == .rightBorder {
divCell.selectionLayer.path = UIBezierPath(roundedRect: divCell.selectionLayer.bounds, byRoundingCorners: [.topRight, .bottomRight], cornerRadii: CGSize(width: divCell.selectionLayer.frame.width / 2, height: divCell.selectionLayer.frame.width / 2)).cgPath
}
else if selectionType == .single {
let diameter: CGFloat = min(divCell.selectionLayer.frame.height, divCell.selectionLayer.frame.width)
divCell.selectionLayer.path = UIBezierPath(ovalIn: CGRect(x: divCell.contentView.frame.width / 2 - diameter / 2, y: divCell.contentView.frame.height / 2 - diameter / 2, width: diameter, height: diameter)).cgPath
}
}
else if position == .next || position == .previous {
divCell.circleImageView.isHidden = true
divCell.selectionLayer.isHidden = true
divCell.eventIndicator.isHidden = true
// Hide default event indicator
if self.calendar.selectedDates.contains(date) {
divCell.titleLabel!.textColor = self.calendar.appearance.titlePlaceholderColor
// Prevent placeholders from changing text color
}
}
}
func calendar(_ calendar: FSCalendar, titleFor date: Date) -> String? {
if self.gregorian.isDateInToday(date) {
return "今"
}
return nil
}
func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int {
return 2
}
func calendar(_ calendar: FSCalendar, boundingRectWillChange bounds: CGRect, animated: Bool) {
self.calendar.frame.size.height = bounds.height
self.eventLabel.frame.origin.y = calendar.frame.maxY + 10
}
func calendar(_ calendar: FSCalendar, didSelect date: Date) {
print("did select date \(self.formatter.string(from: date))")
calendar.reloadData()
}
func calendar(_ calendar: FSCalendar, didDeselect date: Date) {
print("did deselect date \(self.formatter.string(from: date))")
calendar.reloadData()
}
func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, eventDefaultColorsFor date: Date) -> [UIColor]? {
if self.gregorian.isDateInToday(date) {
return [UIColor.orange]
}
return [appearance.eventDefaultColor]
}
}
| mit | 743cae0ae57095c398504e5b988144b8 | 42.404145 | 271 | 0.631013 | 4.962678 | false | false | false | false |
EstefaniaGilVaquero/ciceIOS | AppTestSpotify/AppTestSpotify/ViewController.swift | 1 | 2390 | //
// ViewController.swift
// AppTestSpotify
//
// Created by CICE on 28/10/16.
// Copyright © 2016 CICE. All rights reserved.
//
import UIKit
import Alamofire
class ViewController: UITableViewController {
//MARK: - VARIABLES LOCALES GLOBALES
var busquedaURLSpotify = "https://api.spotify.com/v1/search?q=Muse&type=track,artist&market=US&limit=10&offset=5"
typealias JSONStandard = [String : AnyObject]
var arrayNombres = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
llamadaAlamoFireToSP(busquedaURLSpotify)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - UTILS
func llamadaAlamoFireToSP(_ conexionURL : String){
Alamofire.request(conexionURL).responseJSON { (responseData) in
self.parseAlamofiresFromSP(JSONData: responseData.data!)
}
}
//PARSEO
func parseAlamofiresFromSP(JSONData : Data){
do{
var lectorJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONStandard
// print(lectorJSON)
if let tracksData = lectorJSON["tracks"] as? JSONStandard{
if let items = tracksData["items"]{
for indice in 0..<items.count{
let itemData = items[indice] as! JSONStandard
let nameData = itemData["name"]
arrayNombres.append(nameData as! String)
self.tableView.reloadData()
}
}
}
}catch{
print(error)
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayNombres.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
cell?.textLabel?.text = arrayNombres[indexPath.row]
return cell!
}
}
| apache-2.0 | b82fa147dc2e1b6f9ab11381d3e6beed | 28.8625 | 123 | 0.602344 | 4.768463 | false | false | false | false |
TeamProxima/predictive-fault-tracker | mobile/SieHack/Pods/Charts/Source/Charts/Renderers/CandleStickChartRenderer.swift | 17 | 13451 | //
// CandleStickChartRenderer.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
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
open class CandleStickChartRenderer: LineScatterCandleRadarRenderer
{
open weak var dataProvider: CandleChartDataProvider?
public init(dataProvider: CandleChartDataProvider?, animator: Animator?, viewPortHandler: ViewPortHandler?)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.dataProvider = dataProvider
}
open override func drawData(context: CGContext)
{
guard let dataProvider = dataProvider, let candleData = dataProvider.candleData else { return }
for set in candleData.dataSets as! [ICandleChartDataSet]
{
if set.isVisible
{
drawDataSet(context: context, dataSet: set)
}
}
}
fileprivate var _shadowPoints = [CGPoint](repeating: CGPoint(), count: 4)
fileprivate var _rangePoints = [CGPoint](repeating: CGPoint(), count: 2)
fileprivate var _openPoints = [CGPoint](repeating: CGPoint(), count: 2)
fileprivate var _closePoints = [CGPoint](repeating: CGPoint(), count: 2)
fileprivate var _bodyRect = CGRect()
fileprivate var _lineSegments = [CGPoint](repeating: CGPoint(), count: 2)
open func drawDataSet(context: CGContext, dataSet: ICandleChartDataSet)
{
guard let
dataProvider = dataProvider,
let animator = animator
else { return }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let phaseY = animator.phaseY
let barSpace = dataSet.barSpace
let showCandleBar = dataSet.showCandleBar
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
context.saveGState()
context.setLineWidth(dataSet.shadowWidth)
for j in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1)
{
// get the entry
guard let e = dataSet.entryForIndex(j) as? CandleChartDataEntry else { continue }
let xPos = e.x
let open = e.open
let close = e.close
let high = e.high
let low = e.low
if showCandleBar
{
// calculate the shadow
_shadowPoints[0].x = CGFloat(xPos)
_shadowPoints[1].x = CGFloat(xPos)
_shadowPoints[2].x = CGFloat(xPos)
_shadowPoints[3].x = CGFloat(xPos)
if open > close
{
_shadowPoints[0].y = CGFloat(high * phaseY)
_shadowPoints[1].y = CGFloat(open * phaseY)
_shadowPoints[2].y = CGFloat(low * phaseY)
_shadowPoints[3].y = CGFloat(close * phaseY)
}
else if open < close
{
_shadowPoints[0].y = CGFloat(high * phaseY)
_shadowPoints[1].y = CGFloat(close * phaseY)
_shadowPoints[2].y = CGFloat(low * phaseY)
_shadowPoints[3].y = CGFloat(open * phaseY)
}
else
{
_shadowPoints[0].y = CGFloat(high * phaseY)
_shadowPoints[1].y = CGFloat(open * phaseY)
_shadowPoints[2].y = CGFloat(low * phaseY)
_shadowPoints[3].y = _shadowPoints[1].y
}
trans.pointValuesToPixel(&_shadowPoints)
// draw the shadows
var shadowColor: NSUIColor! = nil
if dataSet.shadowColorSameAsCandle
{
if open > close
{
shadowColor = dataSet.decreasingColor ?? dataSet.color(atIndex: j)
}
else if open < close
{
shadowColor = dataSet.increasingColor ?? dataSet.color(atIndex: j)
}
else
{
shadowColor = dataSet.neutralColor ?? dataSet.color(atIndex: j)
}
}
if shadowColor === nil
{
shadowColor = dataSet.shadowColor ?? dataSet.color(atIndex: j)
}
context.setStrokeColor(shadowColor.cgColor)
context.strokeLineSegments(between: _shadowPoints)
// calculate the body
_bodyRect.origin.x = CGFloat(xPos) - 0.5 + barSpace
_bodyRect.origin.y = CGFloat(close * phaseY)
_bodyRect.size.width = (CGFloat(xPos) + 0.5 - barSpace) - _bodyRect.origin.x
_bodyRect.size.height = CGFloat(open * phaseY) - _bodyRect.origin.y
trans.rectValueToPixel(&_bodyRect)
// draw body differently for increasing and decreasing entry
if open > close
{
let color = dataSet.decreasingColor ?? dataSet.color(atIndex: j)
if dataSet.isDecreasingFilled
{
context.setFillColor(color.cgColor)
context.fill(_bodyRect)
}
else
{
context.setStrokeColor(color.cgColor)
context.stroke(_bodyRect)
}
}
else if open < close
{
let color = dataSet.increasingColor ?? dataSet.color(atIndex: j)
if dataSet.isIncreasingFilled
{
context.setFillColor(color.cgColor)
context.fill(_bodyRect)
}
else
{
context.setStrokeColor(color.cgColor)
context.stroke(_bodyRect)
}
}
else
{
let color = dataSet.neutralColor ?? dataSet.color(atIndex: j)
context.setStrokeColor(color.cgColor)
context.stroke(_bodyRect)
}
}
else
{
_rangePoints[0].x = CGFloat(xPos)
_rangePoints[0].y = CGFloat(high * phaseY)
_rangePoints[1].x = CGFloat(xPos)
_rangePoints[1].y = CGFloat(low * phaseY)
_openPoints[0].x = CGFloat(xPos) - 0.5 + barSpace
_openPoints[0].y = CGFloat(open * phaseY)
_openPoints[1].x = CGFloat(xPos)
_openPoints[1].y = CGFloat(open * phaseY)
_closePoints[0].x = CGFloat(xPos) + 0.5 - barSpace
_closePoints[0].y = CGFloat(close * phaseY)
_closePoints[1].x = CGFloat(xPos)
_closePoints[1].y = CGFloat(close * phaseY)
trans.pointValuesToPixel(&_rangePoints)
trans.pointValuesToPixel(&_openPoints)
trans.pointValuesToPixel(&_closePoints)
// draw the ranges
var barColor: NSUIColor! = nil
if open > close
{
barColor = dataSet.decreasingColor ?? dataSet.color(atIndex: j)
}
else if open < close
{
barColor = dataSet.increasingColor ?? dataSet.color(atIndex: j)
}
else
{
barColor = dataSet.neutralColor ?? dataSet.color(atIndex: j)
}
context.setStrokeColor(barColor.cgColor)
context.strokeLineSegments(between: _rangePoints)
context.strokeLineSegments(between: _openPoints)
context.strokeLineSegments(between: _closePoints)
}
}
context.restoreGState()
}
open override func drawValues(context: CGContext)
{
guard
let dataProvider = dataProvider,
let viewPortHandler = self.viewPortHandler,
let candleData = dataProvider.candleData,
let animator = animator
else { return }
// if values are drawn
if isDrawingValuesAllowed(dataProvider: dataProvider)
{
var dataSets = candleData.dataSets
let phaseY = animator.phaseY
var pt = CGPoint()
for i in 0 ..< dataSets.count
{
guard let dataSet = dataSets[i] as? IBarLineScatterCandleBubbleChartDataSet
else { continue }
if !shouldDrawValues(forDataSet: dataSet)
{
continue
}
let valueFont = dataSet.valueFont
guard let formatter = dataSet.valueFormatter else { continue }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let valueToPixelMatrix = trans.valueToPixelMatrix
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
let lineHeight = valueFont.lineHeight
let yOffset: CGFloat = lineHeight + 5.0
for j in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1)
{
guard let e = dataSet.entryForIndex(j) as? CandleChartDataEntry else { break }
pt.x = CGFloat(e.x)
pt.y = CGFloat(e.high * phaseY)
pt = pt.applying(valueToPixelMatrix)
if (!viewPortHandler.isInBoundsRight(pt.x))
{
break
}
if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y))
{
continue
}
ChartUtils.drawText(
context: context,
text: formatter.stringForValue(
e.high,
entry: e,
dataSetIndex: i,
viewPortHandler: viewPortHandler),
point: CGPoint(
x: pt.x,
y: pt.y - yOffset),
align: .center,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)])
}
}
}
}
open override func drawExtras(context: CGContext)
{
}
open override func drawHighlighted(context: CGContext, indices: [Highlight])
{
guard
let dataProvider = dataProvider,
let candleData = dataProvider.candleData,
let animator = animator
else { return }
context.saveGState()
for high in indices
{
guard
let set = candleData.getDataSetByIndex(high.dataSetIndex) as? ICandleChartDataSet,
set.isHighlightEnabled
else { continue }
guard let e = set.entryForXValue(high.x, closestToY: high.y) as? CandleChartDataEntry else { continue }
if !isInBoundsX(entry: e, dataSet: set)
{
continue
}
let trans = dataProvider.getTransformer(forAxis: set.axisDependency)
context.setStrokeColor(set.highlightColor.cgColor)
context.setLineWidth(set.highlightLineWidth)
if set.highlightLineDashLengths != nil
{
context.setLineDash(phase: set.highlightLineDashPhase, lengths: set.highlightLineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
let lowValue = e.low * Double(animator.phaseY)
let highValue = e.high * Double(animator.phaseY)
let y = (lowValue + highValue) / 2.0
let pt = trans.pixelForValues(x: e.x, y: y)
high.setDraw(pt: pt)
// draw the lines
drawHighlightLines(context: context, point: pt, set: set)
}
context.restoreGState()
}
}
| mit | 12fb220eaf03a0bd0b083142ed30f8ec | 35.452575 | 130 | 0.477065 | 5.959681 | false | false | false | false |
steelwheels/KiwiControls | Source/Basic/KCType.swift | 1 | 2474 | /**
* @file KCType.swift
* @brief Define KCType class
* @par Copyright
* Copyright (C) 2017 Steel Wheels Project
*/
#if os(iOS)
import UIKit
#else
import AppKit
#endif
#if os(iOS)
public typealias KCResponder = UIResponder
public typealias KCTextViewDelegate = UITextViewDelegate
public typealias KCLayoutAttribute = NSLayoutConstraint.Attribute
public typealias KCLayoutRelation = NSLayoutConstraint.Relation
public typealias KCLayoutPriority = UILayoutPriority
public typealias KCLineBreakMode = NSLineBreakMode
public typealias KCLabel = UILabel
public typealias KCWindow = UIWindow
#else
public typealias KCResponder = NSResponder
public typealias KCTextViewDelegate = NSTextViewDelegate
public typealias KCLayoutAttribute = NSLayoutConstraint.Attribute
public typealias KCLayoutRelation = NSLayoutConstraint.Relation
public typealias KCLayoutPriority = NSLayoutConstraint.Priority
public typealias KCLineBreakMode = NSLineBreakMode
public typealias KCWindowDelegate = NSWindowDelegate
public typealias KCLabel = NSTextField
public typealias KCWindow = NSWindow
#endif
#if os(OSX)
public extension NSResponder {
var next: NSResponder? {
return self.nextResponder
}
}
#endif
#if os(iOS)
protocol KCWindowDelegate {
/* Dummy for iOS */
}
#endif
#if os(iOS)
public typealias KCEdgeInsets = UIEdgeInsets
public func KCEdgeInsetsInsetRect(_ rect: CGRect, _ inset: KCEdgeInsets) -> CGRect {
return rect.inset(by: inset)
}
#else
public typealias KCEdgeInsets = NSEdgeInsets
public func KCEdgeInsetsInsetRect(_ rect: CGRect, _ inset: KCEdgeInsets) -> CGRect {
let inseth: CGFloat = inset.left + inset.right
let originx: CGFloat
let width: CGFloat
if inseth <= rect.size.width {
originx = rect.origin.x + inset.left
width = rect.size.width - inseth
} else {
originx = rect.origin.x
width = rect.size.width
}
let insetv: CGFloat = inset.top + inset.bottom
let originy: CGFloat
let height: CGFloat
if insetv <= rect.size.height {
originy = rect.origin.y + inset.top
height = rect.size.height - insetv
} else {
originy = rect.origin.y
height = rect.size.height
}
return CGRect(x: originx, y: originy, width: width, height: height)
}
#endif
public extension KCEdgeInsets {
var description: String {
get {
let l = self.left
let t = self.top
let b = self.bottom
let r = self.right
return "(left:\(l), top:\(t), bottom:\(b), right:\(r))"
}
}
}
| lgpl-2.1 | 7594e75685afffe0491644b0772a5e74 | 24.770833 | 85 | 0.735651 | 3.539342 | false | false | false | false |
steelwheels/Coconut | CoconutData/Source/Value/CNMutableArray.swift | 1 | 7854 | /*
* @file CNMutableArrayValue.swift
* @brief Define CNMutableArrayValue class
* @par Copyright
* Copyright (C) 2022 Steel Wheels Project
*/
import Foundation
public class CNMutableArrayValue: CNMutableValue
{
private var mValues: Array<CNMutableValue>
public init(sourceDirectory srcdir: URL, cacheDirectory cachedir: URL){
mValues = []
super.init(type: .array, sourceDirectory: srcdir, cacheDirectory: cachedir)
}
public var values: Array<CNMutableValue> { get { return mValues }}
public func append(value val: CNMutableValue){
mValues.append(val)
}
public func insert(value val: CNMutableValue, at pos: Int) {
mValues.insert(val, at: pos)
}
public override func _value(forPath path: Array<CNValuePath.Element>, in root: CNMutableValue) -> Result<CNMutableValue?, NSError> {
guard let first = path.first else {
/* Return entire array */
return .success(self)
}
let rest = Array(path.dropFirst())
let result: Result<CNMutableValue?, NSError>
switch first {
case .member(let member):
result = .failure(NSError.parseError(message: "Array index is required but key is given: \(member)"))
case .index(let idx):
if 0<=idx && idx<mValues.count {
result = mValues[idx]._value(forPath: rest, in: root)
} else {
result = .failure(NSError.parseError(message: "Invalid array index: \(idx)"))
}
case .keyAndValue(let srckey, let srcval):
if let (_, curdict) = searchChild(key: srckey, value: srcval) {
if rest.count == 0 {
/* Return child itself */
result = .success(curdict)
} else {
/* Trace child */
result = curdict._value(forPath: rest, in: root)
}
} else {
result = .failure(NSError.parseError(message: "Invalid key or value: \(srckey):\(srcval.description)"))
}
}
return result
}
public override func _set(value val: CNValue, forPath path: Array<CNValuePath.Element>, in root: CNMutableValue) -> NSError? {
guard let first = path.first else {
CNLog(logLevel: .error, message: "Empty path for array value", atFunction: #function, inFile: #file)
return unmatchedPathError(path: path, place: #function)
}
let rest = Array(path.dropFirst())
let result: NSError?
switch first {
case .member(let member):
result = NSError.parseError(message: "Array index is required but key is given: \(member)")
case .index(let idx):
if rest.count == 0 {
if 0<=idx && idx<mValues.count {
mValues[idx] = toMutableValue(from: val)
root.isDirty = true
result = nil
} else if idx == mValues.count {
mValues.append(toMutableValue(from: val))
root.isDirty = true
result = nil
} else {
result = NSError.parseError(message: "Invalid array index: \(idx)")
}
} else {
if 0<=idx && idx<mValues.count {
result = mValues[idx]._set(value: val, forPath: rest, in: root)
} else {
result = NSError.parseError(message: "Invalid array index: \(idx)")
}
}
case .keyAndValue(let srckey, let srcval):
if let (curidx, curdict) = searchChild(key: srckey, value: srcval) {
if rest.count == 0 {
/* Replace child itself */
mValues[curidx] = toMutableValue(from: val)
root.isDirty = true
result = nil
} else {
/* Trace child */
result = curdict._set(value: val, forPath: rest, in: root)
}
} else {
result = NSError.parseError(message: "Invalid key or value: \(srckey):\(srcval.description)")
}
}
return result
}
public override func _append(value val: CNValue, forPath path: Array<CNValuePath.Element>, in root: CNMutableValue) -> NSError? {
let result: NSError?
if let first = path.first {
let rest = Array(path.dropFirst())
switch first {
case .member(let member):
result = NSError.parseError(message: "Array index is required but key is given: \(member)")
case .index(let idx):
if 0<=idx && idx<mValues.count {
result = mValues[idx]._append(value: val, forPath: rest, in: root)
} else {
result = NSError.parseError(message: "Array index overflow: \(idx)")
}
case .keyAndValue(let srckey, let srcval):
if let (_, curdict) = searchChild(key: srckey, value: srcval) {
if rest.count == 0 {
result = NSError.parseError(message: "Invalid key or value: \(srckey):\(srcval.description)")
} else {
/* Trace child */
result = curdict._append(value: val, forPath: rest, in: root)
}
} else {
result = NSError.parseError(message: "Invalid key or value: \(srckey):\(srcval.description)")
}
}
} else {
mValues.append(toMutableValue(from: val))
root.isDirty = true
result = nil
}
return result
}
public override func _delete(forPath path: Array<CNValuePath.Element>, in root: CNMutableValue) -> NSError? {
guard let first = path.first else {
return unmatchedPathError(path: path, place: #function)
}
let rest = Array(path.dropFirst())
let result: NSError?
switch first {
case .member(let member):
result = NSError.parseError(message: "Array index is required but key is given: \(member)")
case .index(let idx):
if rest.count == 0 {
if 0<=idx && idx<mValues.count {
mValues.remove(at: idx)
root.isDirty = true
result = nil
} else {
result = NSError.parseError(message: "Invalid array index: value:\(idx) >= count:\(mValues.count)")
}
} else {
if 0<=idx && idx<mValues.count {
result = mValues[idx]._delete(forPath: rest, in: root)
} else {
result = NSError.parseError(message: "Invalid array index: value:\(idx) >= count:\(mValues.count)")
}
}
case .keyAndValue(let srckey, let srcval):
if let (curidx, curdict) = searchChild(key: srckey, value: srcval) {
if rest.count == 0 {
/* Delete child itself */
mValues.remove(at: curidx)
root.isDirty = true
result = nil
} else {
/* Trace child */
result = curdict._delete(forPath: rest, in: root)
}
} else {
result = NSError.parseError(message: "Invalid key or value: \(srckey):\(srcval.description)")
}
}
return result
}
private func searchChild(key srckey: String, value srcval: CNValue) -> (Int, CNMutableDictionaryValue)? {
for i in 0..<mValues.count {
if let dict = mValues[i] as? CNMutableDictionaryValue {
if let curval = dict.get(forKey: srckey) {
if CNIsSameValue(nativeValue0: curval.toValue(), nativeValue1: srcval){
return (i, dict)
}
}
}
}
return nil
}
public override func _search(name nm: String, value val: String, in root: CNMutableValue) -> Result<Array<CNValuePath.Element>?, NSError> {
for i in 0..<mValues.count {
let elm = mValues[i]
switch elm._search(name: nm, value: val, in: root) {
case .success(let path):
if var mpath = path {
mpath.insert(.index(i), at: 0)
return .success(mpath)
}
case .failure(let err):
return .failure(err)
}
}
return .success(nil) // not found
}
public override func _makeLabelTable(property name: String, path pth: Array<CNValuePath.Element>) -> Dictionary<String, Array<CNValuePath.Element>> {
var result: Dictionary<String, Array<CNValuePath.Element>> = [:]
for i in 0..<mValues.count {
var curpath: Array<CNValuePath.Element> = []
curpath.append(contentsOf: pth)
curpath.append(.index(i))
let subres = mValues[i]._makeLabelTable(property: name, path: curpath)
for (skey, sval) in subres {
result[skey] = sval
}
}
return result
}
public override func clone() -> CNMutableValue {
let result = CNMutableArrayValue(sourceDirectory: self.sourceDirectory, cacheDirectory: self.cacheDirectory)
for elm in mValues {
result.append(value: elm.clone())
}
return result
}
public override func toValue() -> CNValue {
var result: Array<CNValue> = []
for elm in mValues {
result.append(elm.toValue())
}
return .arrayValue(result)
}
}
| lgpl-2.1 | 87577ff4176e17b926c9341e5066a3ac | 31.057143 | 150 | 0.656099 | 3.280702 | false | false | false | false |
czechboy0/XcodeServerSDK | XcodeServerSDK/Server Entities/LiveUpdateMessage.swift | 1 | 3217 | //
// LiveUpdateMessage.swift
// XcodeServerSDK
//
// Created by Honza Dvorsky on 26/09/2015.
// Copyright © 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
public class LiveUpdateMessage: XcodeServerEntity {
public enum MessageType: String {
//bots
case BotCreated = "botCreated"
case BotUpdated = "botUpdated"
case BotRemoved = "botRemoved"
//devices
case DeviceCreated = "deviceCreated"
case DeviceUpdated = "deviceUpdated"
case DeviceRemoved = "deviceRemoved"
//integrations
case PendingIntegrations = "pendingIntegrations"
case IntegrationCreated = "integrationCreated"
case IntegrationStatus = "integrationStatus"
case IntegrationCanceled = "cancelIntegration"
case IntegrationRemoved = "integrationRemoved"
case AdvisoryIntegrationStatus = "advisoryIntegrationStatus"
//repositories
case ListRepositories = "listRepositories"
case CreateRepository = "createRepository"
//boilerplate
case Ping = "ping"
case Pong = "pong"
case ACLUpdated = "aclUpdated"
case RequestPortalSync = "requestPortalSync"
case Unknown = ""
}
public let type: MessageType
public let message: String?
public let progress: Double?
public let integrationId: String?
public let botId: String?
public let result: Integration.Result?
public let currentStep: Integration.Step?
required public init(json: NSDictionary) throws {
let typeString = json.optionalStringForKey("name") ?? ""
self.type = MessageType(rawValue: typeString) ?? .Unknown
let args = (json["args"] as? NSArray)?[0] as? NSDictionary
self.message = args?["message"] as? String
self.progress = args?["percentage"] as? Double
self.integrationId = args?["_id"] as? String
self.botId = args?["botId"] as? String
if
let resultString = args?["result"] as? String,
let result = Integration.Result(rawValue: resultString) {
self.result = result
} else {
self.result = nil
}
if
let stepString = args?["currentStep"] as? String,
let step = Integration.Step(rawValue: stepString) {
self.currentStep = step
} else {
self.currentStep = nil
}
try super.init(json: json)
}
}
extension LiveUpdateMessage: CustomStringConvertible {
public var description: String {
let empty = "" //fixed in Swift 2.1
let nonNilComps = [
self.message,
"\(self.progress?.description ?? empty)",
self.result?.rawValue,
self.currentStep?.rawValue
]
.filter { $0 != nil }
.map { $0! }
.filter { $0.characters.count > 0 }
.map { "\"\($0)\"" }
let str = nonNilComps.joinWithSeparator(", ")
return "LiveUpdateMessage \"\(self.type)\", \(str)"
}
}
| mit | 3ca1ffb167182228f5d84250ad526f1b | 29.056075 | 69 | 0.575249 | 4.947692 | false | false | false | false |
srn214/Floral | Floral/Pods/Hue/Source/iOS+tvOS/UIImage+Hue.swift | 4 | 6017 | import UIKit
class CountedColor {
let color: UIColor
let count: Int
init(color: UIColor, count: Int) {
self.color = color
self.count = count
}
}
extension UIImage {
fileprivate func resize(to newSize: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(newSize, false, 2)
draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result!
}
public func colors(scaleDownSize: CGSize? = nil) -> (background: UIColor, primary: UIColor, secondary: UIColor, detail: UIColor) {
let cgImage: CGImage
if let scaleDownSize = scaleDownSize {
cgImage = resize(to: scaleDownSize).cgImage!
} else {
let ratio = size.width / size.height
let r_width: CGFloat = 250
cgImage = resize(to: CGSize(width: r_width, height: r_width / ratio)).cgImage!
}
let width = cgImage.width
let height = cgImage.height
let bytesPerPixel = 4
let bytesPerRow = width * bytesPerPixel
let bitsPerComponent = 8
let randomColorsThreshold = Int(CGFloat(height) * 0.01)
let blackColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
let whiteColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let raw = malloc(bytesPerRow * height)
let bitmapInfo = CGImageAlphaInfo.premultipliedFirst.rawValue
let context = CGContext(data: raw, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo)
context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height)))
let data = UnsafePointer<UInt8>(context?.data?.assumingMemoryBound(to: UInt8.self))
let imageBackgroundColors = NSCountedSet(capacity: height)
let imageColors = NSCountedSet(capacity: width * height)
let sortComparator: (CountedColor, CountedColor) -> Bool = { (a, b) -> Bool in
return a.count <= b.count
}
for x in 0..<width {
for y in 0..<height {
let pixel = ((width * y) + x) * bytesPerPixel
let color = UIColor(
red: CGFloat((data?[pixel+1])!) / 255,
green: CGFloat((data?[pixel+2])!) / 255,
blue: CGFloat((data?[pixel+3])!) / 255,
alpha: 1
)
if x >= 5 && x <= 10 {
imageBackgroundColors.add(color)
}
imageColors.add(color)
}
}
var sortedColors = [CountedColor]()
for color in imageBackgroundColors {
guard let color = color as? UIColor else { continue }
let colorCount = imageBackgroundColors.count(for: color)
if randomColorsThreshold <= colorCount {
sortedColors.append(CountedColor(color: color, count: colorCount))
}
}
sortedColors.sort(by: sortComparator)
var proposedEdgeColor = CountedColor(color: blackColor, count: 1)
if let first = sortedColors.first { proposedEdgeColor = first }
if proposedEdgeColor.color.isBlackOrWhite && !sortedColors.isEmpty {
for countedColor in sortedColors where CGFloat(countedColor.count / proposedEdgeColor.count) > 0.3 {
if !countedColor.color.isBlackOrWhite {
proposedEdgeColor = countedColor
break
}
}
}
let imageBackgroundColor = proposedEdgeColor.color
let isDarkBackgound = imageBackgroundColor.isDark
sortedColors.removeAll()
for imageColor in imageColors {
guard let imageColor = imageColor as? UIColor else { continue }
let color = imageColor.color(minSaturation: 0.15)
if color.isDark == !isDarkBackgound {
let colorCount = imageColors.count(for: color)
sortedColors.append(CountedColor(color: color, count: colorCount))
}
}
sortedColors.sort(by: sortComparator)
var primaryColor, secondaryColor, detailColor: UIColor?
for countedColor in sortedColors {
let color = countedColor.color
if primaryColor == nil &&
color.isContrasting(with: imageBackgroundColor) {
primaryColor = color
} else if secondaryColor == nil &&
primaryColor != nil &&
primaryColor!.isDistinct(from: color) &&
color.isContrasting(with: imageBackgroundColor) {
secondaryColor = color
} else if secondaryColor != nil &&
(secondaryColor!.isDistinct(from: color) &&
primaryColor!.isDistinct(from: color) &&
color.isContrasting(with: imageBackgroundColor)) {
detailColor = color
break
}
}
free(raw)
return (
imageBackgroundColor,
primaryColor ?? (isDarkBackgound ? whiteColor : blackColor),
secondaryColor ?? (isDarkBackgound ? whiteColor : blackColor),
detailColor ?? (isDarkBackgound ? whiteColor : blackColor))
}
public func color(at point: CGPoint, completion: @escaping (UIColor?) -> Void) {
let size = self.size
let cgImage = self.cgImage
DispatchQueue.global(qos: .userInteractive).async {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
guard let imgRef = cgImage,
let dataProvider = imgRef.dataProvider,
let dataCopy = dataProvider.data,
let data = CFDataGetBytePtr(dataCopy), rect.contains(point) else {
DispatchQueue.main.async {
completion(nil)
}
return
}
let pixelInfo = (Int(size.width) * Int(point.y) + Int(point.x)) * 4
let red = CGFloat(data[pixelInfo]) / 255.0
let green = CGFloat(data[pixelInfo + 1]) / 255.0
let blue = CGFloat(data[pixelInfo + 2]) / 255.0
let alpha = CGFloat(data[pixelInfo + 3]) / 255.0
DispatchQueue.main.async {
completion(UIColor(red: red, green: green, blue: blue, alpha: alpha))
}
}
}
}
| mit | 0b2b9dff53f0023e39cfb4647a5987ea | 33.1875 | 173 | 0.634702 | 4.527464 | false | false | false | false |
mansoor92/MaksabComponents | MaksabComponents/Classes/Trips/cells/UserInfoTableViewCell.swift | 1 | 1296 | //
// UserInfoTableViewCell.swift
// Maksab
//
// Created by Incubasys on 16/08/2017.
// Copyright © 2017 Incubasys. All rights reserved.
//
import UIKit
import StylingBoilerPlate
public class UserInfoTableViewCell: UITableViewCell, NibLoadableView {
@IBOutlet weak public var userPhoto: RoundImageView!
@IBOutlet weak public var userName: UILabel!
@IBOutlet weak public var carName: UILabel!
@IBOutlet weak public var licencsePlate: UILabel!
@IBOutlet weak public var ratingView: RatingView!
@IBOutlet weak public var separator: UIView!
override public func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.backgroundColor = UIColor.appColor(color: .Light)
hideDefaultSeparator()
separator.backgroundColor = UIColor.appColor(color: .Header)
}
override public func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
public func config(name: String, carName: String,carLicensePlate: String, rating: Double) {
userName.text = name
self.carName.text = carName
licencsePlate.text = carLicensePlate
ratingView.rating = rating
}
}
| mit | 40546f3e204e33230a4544943f9b785c | 29.833333 | 96 | 0.694981 | 4.480969 | false | false | false | false |
antonio081014/LeetCode-CodeBase | Swift/arranging-coins.swift | 2 | 1561 | /**
* https://leetcode.com/problems/arranging-coins/
*
*
*/
class Solution {
func arrangeCoins(_ n: Int) -> Int {
if n == 1 {return 1}
var left = 1
var right = n
while left < right {
let mid = (left + right) / 2
if mid * mid + mid <= 2 * n {
left = mid + 1
} else {
right = mid
}
}
return left - 1
}
}
/**
* https://leetcode.com/problems/arranging-coins/
*
*
*/
// Date: Wed Jul 1 09:34:58 PDT 2020
class Solution {
/// - Complexity:
/// - Time: O(logn), using a binary search, nothing else could be expected here.
/// - Space: O(1), since we only have left, right.
///
func arrangeCoins(_ n: Int) -> Int {
var left = 1
var right = n + 1
while left < right {
let mid = left + (right - left) / 2
if mid * (mid + 1) <= n * 2 {
left = mid + 1
} else {
right = mid
}
}
return left - 1
}
}
/**
* https://leetcode.com/problems/arranging-coins/
*
*
*/
// Date: Wed Jul 1 09:39:52 PDT 2020
class Solution {
/// Mathmatical way to solve this problem
/// k*(k+1) / 2 <= n
/// k^2 + k <= 2n
/// (k+1/2)^2 <= 2n + 1/4
/// k <= sqrt(2n + 1/4) - 1/2
///
/// - Complexity:
/// - Time: O(1)
/// - Space: O(1)
///
func arrangeCoins(_ n: Int) -> Int {
return Int(sqrt(Double(n) * 2.0 + 0.25) - 0.5)
}
}
| mit | 5a82c09cb4c8c651f9a4eac0334aa663 | 22.298507 | 88 | 0.432415 | 3.364224 | false | false | false | false |
treejames/firefox-ios | SharedTests/RollingFileLoggerTests.swift | 2 | 4919 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import XCTest
import Shared
class RollingFileLoggerTests: XCTestCase {
var logger: RollingFileLogger!
var logDir: String!
var sizeLimit: UInt64 = 5000
private lazy var formatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyyMMdd'T'HHmmssZ"
return formatter
}()
override func setUp() {
super.setUp()
logDir = (NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first as! String) + "/Logs"
NSFileManager.defaultManager().createDirectoryAtPath(logDir, withIntermediateDirectories: false, attributes: nil, error: nil)
logger = RollingFileLogger(filenameRoot: "test", logDirectoryPath: logDir, sizeLimit: sizeLimit)
}
func testNewLogCreatesLogFileWithTimestamp() {
let date = NSDate()
let expected = "test.\(formatter.stringFromDate(date)).log"
let expectedPath = "\(logDir)/\(expected)"
logger.newLogWithDate(date)
XCTAssertTrue(NSFileManager.defaultManager().fileExistsAtPath(expectedPath), "Log file should exist")
let testMessage = "Logging some text"
logger.info(testMessage)
let logData = NSData(contentsOfFile: expectedPath)
XCTAssertNotNil(logData, "Log data should not be nil")
let logString = NSString(data: logData!, encoding: NSUTF8StringEncoding)
XCTAssertTrue(logString!.containsString(testMessage), "Log should contain our test message that we wrote")
}
func testNewLogDeletesPreviousLogIfItsTooLarge() {
let expectedPath = createNewLogFileWithSize(5001)
var directorySize: UInt64 = 0
NSFileManager.defaultManager().moz_getAllocatedSize(&directorySize, ofDirectoryAtURL: NSURL(fileURLWithPath: logDir)!, forFilesPrefixedWith: "test", error: nil)
// Pre-condition: Folder needs to be larger than the size limit
XCTAssertGreaterThan(directorySize, sizeLimit, "Log folder should be larger than size limit")
let newDate = NSDate().dateByAddingTimeInterval(60*60) // Create a log file using a date an hour ahead
let newExpected = "test.\(formatter.stringFromDate(newDate)).log"
let newExpectedPath = "\(logDir)/\(newExpected)"
logger.newLogWithDate(newDate)
XCTAssertTrue(NSFileManager.defaultManager().fileExistsAtPath(newExpectedPath), "New log file should exist")
XCTAssertFalse(NSFileManager.defaultManager().fileExistsAtPath(expectedPath), "Old log file should NOT exist")
}
func testNewLogDeletesOldestLogFileToMakeRoomForNewFile() {
// Create 5 log files with spread out over 5 hours
var logFilePaths = [0,1,2,3,4].map { self.createNewLogFileWithSize(200, withDate: NSDate().dateByAddingTimeInterval(60 * 60 * $0)) }
// Reorder paths so oldest is first
logFilePaths.sort { $0 < $1 }
var directorySize: UInt64 = 0
NSFileManager.defaultManager().moz_getAllocatedSize(&directorySize, ofDirectoryAtURL: NSURL(fileURLWithPath: logDir)!, forFilesPrefixedWith: "test", error: nil)
// Pre-condition: Folder needs to be larger than the size limit
XCTAssertGreaterThan(directorySize, sizeLimit, "Log folder should be larger than size limit")
let newDate = NSDate().dateByAddingTimeInterval(60*60*5) // Create a log file using a date an hour ahead
let newExpected = "test.\(formatter.stringFromDate(newDate)).log"
let newExpectedPath = "\(logDir)/\(newExpected)"
logger.newLogWithDate(newDate)
XCTAssertTrue(NSFileManager.defaultManager().fileExistsAtPath(newExpectedPath), "New log file should exist")
XCTAssertFalse(NSFileManager.defaultManager().fileExistsAtPath(logFilePaths.first!), "Oldest log file should NOT exist")
}
/**
Create a log file using the test logger and returns the path to that log file
:param: size Size to make the log file
:returns: Path to log file
*/
private func createNewLogFileWithSize(size: Int, withDate date: NSDate = NSDate()) -> String {
let expected = "test.\(formatter.stringFromDate(date)).log"
let expectedPath = "\(logDir)/\(expected)"
logger.newLogWithDate(date)
XCTAssertTrue(NSFileManager.defaultManager().fileExistsAtPath(expectedPath), "Log file should exist")
let logFileHandle = NSFileHandle(forWritingAtPath: expectedPath)
XCTAssertNotNil(logFileHandle, "File should exist")
let garbageBytes = malloc(size)
let blankData = NSData(bytes: garbageBytes, length: size)
logFileHandle!.writeData(blankData)
logFileHandle!.closeFile()
return expectedPath
}
}
| mpl-2.0 | 14b8a438c352d10811c3d16fb434fd62 | 46.757282 | 168 | 0.707867 | 4.822549 | false | true | false | false |
HongliYu/firefox-ios | Client/Frontend/Intro/IntroViewController.swift | 1 | 19087 | /* 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 SnapKit
import Shared
struct IntroUX {
static let Width = 375
static let Height = 667
static let MinimumFontScale: CGFloat = 0.5
static let PagerCenterOffsetFromScrollViewBottom = UIScreen.main.bounds.width <= 320 ? 20 : 30
static let StartBrowsingButtonColor = UIColor.Photon.Blue40
static let StartBrowsingButtonHeight = 56
static let SignInButtonColor = UIColor.Photon.Blue40
static let SignInButtonHeight = 60
static let PageControlHeight = 40
static let SignInButtonWidth = 290
static let CardTextWidth = UIScreen.main.bounds.width <= 320 ? 240 : 280
static let FadeDuration = 0.25
}
protocol IntroViewControllerDelegate: AnyObject {
func introViewControllerDidFinish(_ introViewController: IntroViewController, requestToLogin: Bool)
}
class IntroViewController: UIViewController {
weak var delegate: IntroViewControllerDelegate?
// We need to hang on to views so we can animate and change constraints as we scroll
var cardViews = [CardView]()
var cards = IntroCard.defaultCards()
lazy fileprivate var startBrowsingButton: UIButton = {
let button = UIButton()
button.backgroundColor = UIColor.clear
button.setTitle(Strings.StartBrowsingButtonTitle, for: UIControlState())
button.setTitleColor(IntroUX.StartBrowsingButtonColor, for: UIControlState())
button.addTarget(self, action: #selector(IntroViewController.startBrowsing), for: UIControlEvents.touchUpInside)
button.accessibilityIdentifier = "IntroViewController.startBrowsingButton"
button.isHidden = true
return button
}()
lazy var pageControl: UIPageControl = {
let pc = UIPageControl()
pc.pageIndicatorTintColor = UIColor.black.withAlphaComponent(0.3)
pc.currentPageIndicatorTintColor = UIColor.black
pc.accessibilityIdentifier = "IntroViewController.pageControl"
pc.addTarget(self, action: #selector(IntroViewController.changePage), for: UIControlEvents.valueChanged)
return pc
}()
lazy fileprivate var scrollView: UIScrollView = {
let sc = UIScrollView()
sc.backgroundColor = UIColor.clear
sc.accessibilityLabel = NSLocalizedString("Intro Tour Carousel", comment: "Accessibility label for the introduction tour carousel")
sc.delegate = self
sc.bounces = false
sc.isPagingEnabled = true
sc.showsHorizontalScrollIndicator = false
sc.accessibilityIdentifier = "IntroViewController.scrollView"
return sc
}()
var horizontalPadding: Int {
return self.view.frame.width <= 320 ? 20 : 50
}
var verticalPadding: CGFloat {
return self.view.frame.width <= 320 ? 10 : 38
}
lazy fileprivate var imageViewContainer: UIStackView = {
let sv = UIStackView()
sv.axis = .horizontal
sv.distribution = .fillEqually
return sv
}()
// Because a stackview cannot have a background color
fileprivate var imagesBackgroundView = UIView()
override func viewDidLoad() {
syncViaLP()
assert(cards.count > 1, "Intro is empty. At least 2 cards are required")
view.backgroundColor = UIColor.Photon.White100
// Add Views
view.addSubview(pageControl)
view.addSubview(scrollView)
view.addSubview(startBrowsingButton)
scrollView.addSubview(imagesBackgroundView)
scrollView.addSubview(imageViewContainer)
// Setup constraints
imagesBackgroundView.snp.makeConstraints { make in
make.edges.equalTo(imageViewContainer)
}
imageViewContainer.snp.makeConstraints { make in
make.top.equalTo(self.view)
make.height.equalTo(self.view.snp.width)
}
startBrowsingButton.snp.makeConstraints { make in
make.left.right.equalTo(self.view)
make.bottom.equalTo(self.view.safeArea.bottom)
make.height.equalTo(IntroUX.StartBrowsingButtonHeight)
}
scrollView.snp.makeConstraints { make in
make.left.right.top.equalTo(self.view)
make.bottom.equalTo(startBrowsingButton.snp.top)
}
pageControl.snp.makeConstraints { make in
make.centerX.equalTo(self.scrollView)
make.centerY.equalTo(self.startBrowsingButton.snp.top).offset(-IntroUX.PagerCenterOffsetFromScrollViewBottom)
}
createSlides()
pageControl.addTarget(self, action: #selector(changePage), for: .valueChanged)
}
func syncViaLP() {
let startTime = Date.now()
LeanPlumClient.shared.introScreenVars?.onValueChanged({ [weak self] in
guard let newIntro = LeanPlumClient.shared.introScreenVars?.object(forKey: nil) as? [[String: Any]] else {
return
}
let decoder = JSONDecoder()
let newCards = newIntro.compactMap { (obj) -> IntroCard? in
guard let object = try? JSONSerialization.data(withJSONObject: obj, options: []) else {
return nil
}
let card = try? decoder.decode(IntroCard.self, from: object)
// Make sure the selector actually goes somewhere. Otherwise dont show that slide
if let selectorString = card?.buttonSelector, let wself = self {
return wself.responds(to: NSSelectorFromString(selectorString)) ? card : nil
} else {
return card
}
}
guard newCards != IntroCard.defaultCards(), newCards.count > 1 else {
return
}
// We need to still be on the first page otherwise the content will change underneath the user's finger
// We also need to let LP know this happened so we can track when a A/B test was not run
guard self?.pageControl.currentPage == 0 else {
let totalTime = Date.now() - startTime
LeanPlumClient.shared.track(event: .onboardingTestLoadedTooSlow, withParameters: ["Total time": "\(totalTime) ms"])
return
}
self?.cards = newCards
self?.createSlides()
self?.viewDidLayoutSubviews()
})
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.contentSize = imageViewContainer.frame.size
}
func createSlides() {
// Make sure the scrollView has been setup before setting up the slides
guard scrollView.superview != nil else {
return
}
// Wipe any existing slides
imageViewContainer.subviews.forEach { $0.removeFromSuperview() }
cardViews.forEach { $0.removeFromSuperview() }
cardViews = cards.compactMap { addIntro(card: $0) }
pageControl.numberOfPages = cardViews.count
setupDynamicFonts()
if let firstCard = cardViews.first {
setActive(firstCard, forPage: 0)
}
imageViewContainer.layoutSubviews()
scrollView.contentSize = imageViewContainer.frame.size
// This should never happen but just in case make sure there is a way out
if cardViews.count == 1 {
startBrowsingButton.isHidden = false
}
}
func addIntro(card: IntroCard) -> CardView? {
guard let image = UIImage(named: card.imageName) else {
return nil
}
let imageView = UIImageView(image: image)
imageViewContainer.addArrangedSubview(imageView)
imageView.snp.makeConstraints { make in
make.height.equalTo(imageViewContainer.snp.height)
make.width.equalTo(imageViewContainer.snp.height)
}
let cardView = CardView(verticleSpacing: verticalPadding)
cardView.configureWith(card: card)
if let selectorString = card.buttonSelector, self.responds(to: NSSelectorFromString(selectorString)) {
cardView.button.addTarget(self, action: NSSelectorFromString(selectorString), for: .touchUpInside)
cardView.button.snp.makeConstraints { make in
make.width.equalTo(IntroUX.CardTextWidth)
make.height.equalTo(IntroUX.SignInButtonHeight)
}
}
self.view.addSubview(cardView)
cardView.snp.makeConstraints { make in
make.top.equalTo(self.imageViewContainer.snp.bottom).offset(verticalPadding)
make.bottom.equalTo(self.startBrowsingButton.snp.top)
make.left.right.equalTo(self.view).inset(horizontalPadding)
}
return cardView
}
@objc func startBrowsing() {
delegate?.introViewControllerDidFinish(self, requestToLogin: false)
LeanPlumClient.shared.track(event: .dismissedOnboarding, withParameters: ["dismissedOnSlide": String(pageControl.currentPage)])
}
@objc func login() {
delegate?.introViewControllerDidFinish(self, requestToLogin: true)
LeanPlumClient.shared.track(event: .dismissedOnboardingShowLogin, withParameters: ["dismissedOnSlide": String(pageControl.currentPage)])
}
@objc func changePage() {
let swipeCoordinate = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
scrollView.setContentOffset(CGPoint(x: swipeCoordinate, y: 0), animated: true)
}
fileprivate func setActive(_ introView: UIView, forPage page: Int) {
guard introView.alpha != 1 else {
return
}
UIView.animate(withDuration: IntroUX.FadeDuration, animations: {
self.cardViews.forEach { $0.alpha = 0.0 }
introView.alpha = 1.0
self.pageControl.currentPage = page
}, completion: nil)
}
}
// UIViewController setup
extension IntroViewController {
override var prefersStatusBarHidden: Bool {
return true
}
override var shouldAutorotate: Bool {
return false
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
// This actually does the right thing on iPad where the modally
// presented version happily rotates with the iPad orientation.
return .portrait
}
}
// Dynamic Font Helper
extension IntroViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(dynamicFontChanged), name: .DynamicFontChanged, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: .DynamicFontChanged, object: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
@objc func dynamicFontChanged(_ notification: Notification) {
guard notification.name == .DynamicFontChanged else { return }
setupDynamicFonts()
}
fileprivate func setupDynamicFonts() {
startBrowsingButton.titleLabel?.font = UIFont(name: "FiraSans-Regular", size: DynamicFontHelper.defaultHelper.IntroStandardFontSize)
cardViews.forEach { cardView in
cardView.titleLabel.font = UIFont(name: "FiraSans-Medium", size: DynamicFontHelper.defaultHelper.IntroBigFontSize)
cardView.textLabel.font = UIFont(name: "FiraSans-UltraLight", size: DynamicFontHelper.defaultHelper.IntroStandardFontSize)
}
}
}
extension IntroViewController: UIScrollViewDelegate {
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
// Need to add this method so that when forcibly dragging, instead of letting deceleration happen, should also calculate what card it's on.
// This especially affects sliding to the last or first cards.
if !decelerate {
scrollViewDidEndDecelerating(scrollView)
}
}
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
// Need to add this method so that tapping the pageControl will also change the card texts.
// scrollViewDidEndDecelerating waits until the end of the animation to calculate what card it's on.
scrollViewDidEndDecelerating(scrollView)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let page = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
if let cardView = cardViews[safe: page] {
setActive(cardView, forPage: page)
}
if page != 0 {
startBrowsingButton.isHidden = false
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let maximumHorizontalOffset = scrollView.frame.width
let currentHorizontalOffset = scrollView.contentOffset.x
var percentageOfScroll = currentHorizontalOffset / maximumHorizontalOffset
percentageOfScroll = percentageOfScroll > 1.0 ? 1.0 : percentageOfScroll
let whiteComponent = UIColor.Photon.White100.components
let grayComponent = UIColor.Photon.Grey20.components
let newRed = (1.0 - percentageOfScroll) * whiteComponent.red + percentageOfScroll * grayComponent.red
let newGreen = (1.0 - percentageOfScroll) * whiteComponent.green + percentageOfScroll * grayComponent.green
let newBlue = (1.0 - percentageOfScroll) * whiteComponent.blue + percentageOfScroll * grayComponent.blue
imagesBackgroundView.backgroundColor = UIColor(red: newRed, green: newGreen, blue: newBlue, alpha: 1.0)
}
}
// A cardView repersents the text for each page of the intro. It does not include the image.
class CardView: UIView {
lazy var stackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.alignment = .center
return stackView
}()
lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.numberOfLines = 2
titleLabel.adjustsFontSizeToFitWidth = true
titleLabel.minimumScaleFactor = IntroUX.MinimumFontScale
titleLabel.textAlignment = .center
titleLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: .vertical)
return titleLabel
}()
lazy var textLabel: UILabel = {
let textLabel = UILabel()
textLabel.numberOfLines = 5
textLabel.adjustsFontSizeToFitWidth = true
textLabel.minimumScaleFactor = IntroUX.MinimumFontScale
textLabel.textAlignment = .center
textLabel.lineBreakMode = .byTruncatingTail
textLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: .vertical)
return textLabel
}()
lazy var button: UIButton = {
let button = UIButton()
button.backgroundColor = IntroUX.SignInButtonColor
button.setTitle(Strings.SignInButtonTitle, for: [])
button.setTitleColor(.white, for: [])
button.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: .vertical)
button.clipsToBounds = true
return button
}()
override init(frame: CGRect) {
super.init(frame: frame)
}
init(verticleSpacing: CGFloat) {
super.init(frame: .zero)
stackView.spacing = verticleSpacing
stackView.addArrangedSubview(titleLabel)
stackView.addArrangedSubview(textLabel)
addSubview(stackView)
stackView.snp.makeConstraints { make in
make.leading.trailing.top.equalTo(self)
make.bottom.lessThanOrEqualTo(self).offset(-IntroUX.PageControlHeight)
}
alpha = 0
}
func configureWith(card: IntroCard) {
titleLabel.text = card.title
textLabel.text = card.text
if let buttonText = card.buttonText, card.buttonSelector != nil {
button.setTitle(buttonText, for: .normal)
addSubview(button)
button.snp.makeConstraints { make in
make.bottom.centerX.equalTo(self)
}
// When there is a button reduce the spacing to make more room for text
stackView.spacing = stackView.spacing / 2
}
}
// Allows the scrollView to scroll while the CardView is in front
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
if let buttonSV = button.superview {
return convert(button.frame, from: buttonSV).contains(point)
}
return false
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
struct IntroCard: Codable {
let title: String
let text: String
let buttonText: String?
let buttonSelector: String? // Selector is a string that is synthisized into a Selector via NSSelectorFromString (for LeanPlum's sake)
let imageName: String
init(title: String, text: String, imageName: String, buttonText: String? = nil, buttonSelector: String? = nil) {
self.title = title
self.text = text
self.imageName = imageName
self.buttonText = buttonText
self.buttonSelector = buttonSelector
}
static func defaultCards() -> [IntroCard] {
let welcome = IntroCard(title: Strings.CardTitleWelcome, text: Strings.CardTextWelcome, imageName: "tour-Welcome")
let search = IntroCard(title: Strings.CardTitleSearch, text: Strings.CardTextSearch, imageName: "tour-Search")
let privateBrowsing = IntroCard(title: Strings.CardTitlePrivate, text: Strings.CardTextPrivate, imageName: "tour-Private")
let mailTo = IntroCard(title: Strings.CardTitleMail, text: Strings.CardTextMail, imageName: "tour-Mail")
let sync = IntroCard(title: Strings.CardTitleSync, text: Strings.CardTextSync, imageName: "tour-Sync", buttonText: Strings.SignInButtonTitle, buttonSelector: #selector(IntroViewController.login).description)
return [welcome, search, privateBrowsing, mailTo, sync]
}
/* Codable doesnt allow quick conversion to a dictonary */
func asDictonary() -> [String: Any]? {
guard let data = try? JSONEncoder().encode(self) else { return nil }
return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap { $0 as? [String: Any] }
}
}
extension IntroCard: Equatable {}
func == (lhs: IntroCard, rhs: IntroCard) -> Bool {
return lhs.buttonText == rhs.buttonText && lhs.buttonSelector == rhs.buttonSelector
&& lhs.imageName == rhs.imageName && lhs.text == rhs.text && lhs.title == rhs.title
}
extension UIColor {
var components: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
return (r, g, b, a)
}
}
| mpl-2.0 | 32531bdd9028ec77ef28d8ed267d7955 | 39.87152 | 215 | 0.67009 | 4.951232 | false | false | false | false |
ReactiveKit/ReactiveUIKit | Sources/UITextView.swift | 1 | 3882 | //
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// 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 ReactiveKit
import UIKit
extension UITextView {
private struct AssociatedKeys {
static var TextKey = "r_TextKey"
static var AttributedTextKey = "r_AttributedTextKey"
}
public var rText: Property<String?> {
if let rText: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.TextKey) {
return rText as! Property<String?>
} else {
let rText = Property<String?>(self.text)
objc_setAssociatedObject(self, &AssociatedKeys.TextKey, rText, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
var updatingFromSelf: Bool = false
rText.observeNext { [weak self] (text: String?) in
if !updatingFromSelf {
self?.text = text
}
}.disposeIn(rBag)
NSNotificationCenter.defaultCenter()
.rNotification(UITextViewTextDidChangeNotification, object: self)
.observeNext { [weak rText] notification in
if let textView = notification.object as? UITextView, rText = rText {
updatingFromSelf = true
rText.value = textView.text
updatingFromSelf = false
}
}.disposeIn(rBag)
return rText
}
}
public var rAttributedText: Property<NSAttributedString?> {
if let rAttributedText: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.AttributedTextKey) {
return rAttributedText as! Property<NSAttributedString?>
} else {
let rAttributedText = Property<NSAttributedString?>(self.attributedText)
objc_setAssociatedObject(self, &AssociatedKeys.AttributedTextKey, rAttributedText, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
var updatingFromSelf: Bool = false
rAttributedText.observeNext { [weak self] (text: NSAttributedString?) in
if !updatingFromSelf {
self?.attributedText = text
}
}.disposeIn(rBag)
NSNotificationCenter.defaultCenter()
.rNotification(UITextViewTextDidChangeNotification, object: self)
.observeNext { [weak rAttributedText] notification in
if let textView = notification.object as? UITextView, rAttributedText = rAttributedText {
updatingFromSelf = true
rAttributedText.value = textView.attributedText
updatingFromSelf = false
}
}.disposeIn(rBag)
return rAttributedText
}
}
public var rTextColor: Property<UIColor?> {
return rAssociatedPropertyForValueForKey("textColor")
}
}
extension UITextView: BindableType {
public func observer(disconnectDisposable: Disposable) -> (StreamEvent<String?> -> ()) {
return self.rText.observer(disconnectDisposable)
}
}
| mit | 44460afb8679721eaff42b7031f074ce | 36.68932 | 146 | 0.698351 | 4.774908 | false | false | false | false |
frtlupsvn/Vietnam-To-Go | VietNamToGo/Models/Places/Places.swift | 1 | 3293 | //
// Places.swift
// Fuot
//
// Created by Zoom Nguyen on 1/3/16.
// Copyright © 2016 Zoom Nguyen. All rights reserved.
//
import Foundation
import CoreData
import Parse
@objc(Places)
class Places: NSManagedObject {
// Insert code here to add functionality to your managed object subclass
/* SYNC DATA FROM PARSE */
static func syncPlacesWithParse(completion:()->Void){
//Get Data from Parse
let query = PFQuery(className:"Place")
if let placeLatest:Places = Places.fetchLatestObject(){
query.whereKey("updatedAt", greaterThan:placeLatest.updatedAt!)
}
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
print("Successfully retrieved \(objects!.count) places.")
// Do something with the found objects
if let objects = objects {
for object in objects {
Places.deleteObject(object.objectId!)
let place = Places.createNewEntity() as! Places
place.objectId = object.objectId
place.createdAt = object.createdAt
place.updatedAt = object.updatedAt
}
Places.saveToDefaultContext()
completion()
}
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}
}
/* FETCH ALL */
static func fetchAll() -> NSArray{
return Places.findAll()
}
/* FETCH OBJECT BY ID */
static func fetchByObjectID(objectID:String)->Places?{
let predicate = NSPredicate(format: "objectId = %@",objectID)
let arrayOjects = Places.findAllWithPredicate(predicate)
if let place:Places = arrayOjects.firstObject as? Places {
return place
}
return nil
}
/* FETCH LATEST OBJECT */
static func fetchLatestObject() -> Places?{
let arrayObjects = Places.findAll()
let descriptor: NSSortDescriptor = NSSortDescriptor(key: "updatedAt", ascending: false)
let sortedResults: NSArray = arrayObjects.sortedArrayUsingDescriptors([descriptor])
if let place:Places = sortedResults.firstObject as? Places{
return place
}
return nil
}
/* DELETE OBJECT */
static func deleteObject(objectID:String){
if let place:Places = Places.fetchByObjectID(objectID){
let context = Places.getContext()
context.deleteObject(place)
}
}
/* CONTEXT */
static func saveToDefaultContext() {
let context = SuperCoreDataStack.defaultStack.managedObjectContext
do {
try context!.save()
} catch {
abort()
}
}
static private func getContext()-> NSManagedObjectContext{
return SuperCoreDataStack.defaultStack.managedObjectContext!
}
}
| mit | 48005ffc381cfb2e9b5a6843a166c48d | 29.201835 | 95 | 0.547388 | 5.57022 | false | false | false | false |
hooman/swift | stdlib/public/core/Indices.swift | 13 | 4396 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A collection of indices for an arbitrary collection
@frozen
public struct DefaultIndices<Elements: Collection> {
@usableFromInline
internal var _elements: Elements
@usableFromInline
internal var _startIndex: Elements.Index
@usableFromInline
internal var _endIndex: Elements.Index
@inlinable
internal init(
_elements: Elements,
startIndex: Elements.Index,
endIndex: Elements.Index
) {
self._elements = _elements
self._startIndex = startIndex
self._endIndex = endIndex
}
}
extension DefaultIndices: Collection {
public typealias Index = Elements.Index
public typealias Element = Elements.Index
public typealias Indices = DefaultIndices<Elements>
public typealias SubSequence = DefaultIndices<Elements>
public typealias Iterator = IndexingIterator<DefaultIndices<Elements>>
@inlinable
public var startIndex: Index {
return _startIndex
}
@inlinable
public var endIndex: Index {
return _endIndex
}
@inlinable
public subscript(i: Index) -> Elements.Index {
// FIXME: swift-3-indexing-model: range check.
return i
}
@inlinable
public subscript(bounds: Range<Index>) -> DefaultIndices<Elements> {
// FIXME: swift-3-indexing-model: range check.
return DefaultIndices(
_elements: _elements,
startIndex: bounds.lowerBound,
endIndex: bounds.upperBound)
}
@inlinable
public func index(after i: Index) -> Index {
// FIXME: swift-3-indexing-model: range check.
return _elements.index(after: i)
}
@inlinable
public func formIndex(after i: inout Index) {
// FIXME: swift-3-indexing-model: range check.
_elements.formIndex(after: &i)
}
@inlinable
public var indices: Indices {
return self
}
@_alwaysEmitIntoClient
public func index(_ i: Index, offsetBy distance: Int) -> Index {
return _elements.index(i, offsetBy: distance)
}
@_alwaysEmitIntoClient
public func index(
_ i: Index, offsetBy distance: Int, limitedBy limit: Index
) -> Index? {
return _elements.index(i, offsetBy: distance, limitedBy: limit)
}
@_alwaysEmitIntoClient
public func distance(from start: Index, to end: Index) -> Int {
return _elements.distance(from: start, to: end)
}
}
extension DefaultIndices: BidirectionalCollection
where Elements: BidirectionalCollection {
@inlinable
public func index(before i: Index) -> Index {
// FIXME: swift-3-indexing-model: range check.
return _elements.index(before: i)
}
@inlinable
public func formIndex(before i: inout Index) {
// FIXME: swift-3-indexing-model: range check.
_elements.formIndex(before: &i)
}
}
extension DefaultIndices: RandomAccessCollection
where Elements: RandomAccessCollection { }
extension Collection where Indices == DefaultIndices<Self> {
/// The indices that are valid for subscripting the collection, in ascending
/// order.
///
/// A collection's `indices` property can hold a strong reference to the
/// collection itself, causing the collection to be non-uniquely referenced.
/// If you mutate the collection while iterating over its indices, a strong
/// reference can cause an unexpected copy of the collection. To avoid the
/// unexpected copy, use the `index(after:)` method starting with
/// `startIndex` to produce indices instead.
///
/// var c = MyFancyCollection([10, 20, 30, 40, 50])
/// var i = c.startIndex
/// while i != c.endIndex {
/// c[i] /= 5
/// i = c.index(after: i)
/// }
/// // c == MyFancyCollection([2, 4, 6, 8, 10])
@inlinable // trivial-implementation
public var indices: DefaultIndices<Self> {
return DefaultIndices(
_elements: self,
startIndex: self.startIndex,
endIndex: self.endIndex)
}
}
extension DefaultIndices: Sendable
where Elements: Sendable, Elements.Index: Sendable { }
| apache-2.0 | 66ce508ef561a5d9cee05298e000b598 | 28.503356 | 80 | 0.670382 | 4.426989 | false | false | false | false |
J-Mendes/Bliss-Assignement | Bliss-Assignement/Bliss-Assignement/QuestionDetailsViewController.swift | 1 | 3924 | //
// QuestionDetailsViewController.swift
// Bliss-Assignement
//
// Created by Jorge Mendes on 13/10/16.
// Copyright © 2016 Jorge Mendes. All rights reserved.
//
import UIKit
import AlamofireImage
class QuestionDetailsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
internal var question: Question!
@IBOutlet private weak var questionImageView: UIImageView!
@IBOutlet private weak var questionLabel: UILabel!
@IBOutlet private weak var publishedDateLabel: UILabel!
@IBOutlet private weak var voteLabel: UILabel!
@IBOutlet private weak var tableView: UITableView!
private var shareButton: UIBarButtonItem!
private var selectedIndex: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
self.initLayout()
}
private func initLayout() {
self.title = "Detail"
self.shareButton = UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: #selector(self.shareAction(_:)))
self.navigationItem.rightBarButtonItem = nil
self.navigationItem.setRightBarButtonItem(self.shareButton, animated: false)
self.questionImageView.af_setImageWithURL(NSURL(string: self.question.imageUrl)!)
self.questionLabel.text = self.question.question
self.publishedDateLabel.text = self.question.publishDate
self.voteLabel.text = "Tap on a language to vote:"
self.tableView.tableFooterView = UIView()
}
deinit {
self.questionImageView.af_cancelImageRequest()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.question.choices.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("choiceCell")
if cell == nil {
cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "choiceCell")
}
cell?.textLabel?.text = self.question.choices[indexPath.row].choice
cell?.detailTextLabel?.text = "\(self.question.choices[indexPath.row].votes) votes"
return cell!
}
// MARK: - Table view delegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.selectedIndex = indexPath.row
self.question.choices[self.selectedIndex].votes! += 1
self.tableView.reloadData()
self.updateQuestion()
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
// MARK: - UIButton actions
@IBAction func shareAction(sender: AnyObject) {
let shareView: ShareView = NSBundle.mainBundle().loadNibNamed(String(ShareView), owner: self, options: nil)?.first as! ShareView
shareView.shareUrl = "blissrecruitment://questions?question_id=\(self.question.id)"
shareView.show()
}
// MARK: - Data request
private func updateQuestion() {
ProgressHUD.showProgressHUD(UIApplication.sharedApplication().keyWindow!, text: "Voting...")
DataManager.sharedManager.updateQuestion(withQuestion: self.question) { (question: Question, error: NSError?) in
if error == nil {
ProgressHUD.dismissAllHuds(UIApplication.sharedApplication().keyWindow!)
} else {
self.question.choices[self.selectedIndex].votes! -= 1
self.tableView.reloadData()
ProgressHUD.showErrorHUD(UIApplication.sharedApplication().keyWindow!, text: "An error was occurred\nwhile voting.")
}
}
}
}
| lgpl-3.0 | 1997660a6a40bdb8621092bbdee60948 | 35.324074 | 136 | 0.673464 | 5.155059 | false | false | false | false |
TruckMuncher/TruckMuncher-iOS | TruckMuncher/api/RUser.swift | 1 | 1539 | //
// RUser.swift
// TruckMuncher
//
// Created by Josh Ault on 10/28/14.
// Copyright (c) 2014 TruckMuncher. All rights reserved.
//
import UIKit
import Realm
class RUser: RLMObject {
dynamic var id = ""
dynamic var fbUsername = ""
dynamic var twUsername = ""
dynamic var hasFb = false // realm doesnt support optionals, so we cant check if fbUsername is nil, need this flag
dynamic var hasTw = false
dynamic var postToFb = false
dynamic var postToTw = false
dynamic var sessionToken = ""
dynamic var truckIds = RLMArray(objectClassName: RString.className())
dynamic var favorites = RLMArray(objectClassName: RString.className())
class func initFromProto(auth: [String: AnyObject]) -> RUser {
let ruser = RUser()
ruser.id = auth["userId"] as! String
ruser.sessionToken = auth["sessionToken"] as! String
if let user = auth["user"] as? [String: AnyObject] {
ruser.id = user["id"] as! String
let fbUsername = user["fbUsername"] as? String
let twUsername = user["twUsername"] as? String
ruser.fbUsername = fbUsername ?? ""
ruser.twUsername = twUsername ?? ""
ruser.hasFb = fbUsername != nil
ruser.hasTw = twUsername != nil
ruser.postToFb = user["postToFb"] as? Bool ?? false
ruser.postToTw = user["postToTw"] as? Bool ?? false
}
return ruser
}
override class func primaryKey() -> String! {
return "id"
}
}
| gpl-2.0 | a0f446073e38cd820d96ffed3a060d58 | 33.2 | 118 | 0.614035 | 4.093085 | false | false | false | false |
steverichey/leddit | leddit/StoryListController.swift | 1 | 3602 | //
// StoryListController.swift
// leddit
//
// Created by dev on 8/17/15.
// Copyright © 2015 STVR. All rights reserved.
//
import Foundation
import UIKit
class StoryListController : UITableViewController {
var stories:[Story] = []
let number_of_stories = 10
override func viewDidLoad() {
super.viewDidLoad()
print("connecting")
let test = NSURLRequest(string: "https://www.reddit.com/r/gaming/top.json?limit=\(number_of_stories)")
NSURLSession.sharedSession().dataTaskWithRequest(test) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
print("connected")
if error != nil {
print(error?.description)
} else {
var stories = [Story]()
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers)
let json_data = json["data"] as? NSDictionary
let children = json_data?.objectForKey("children") as! [AnyObject]
for i in 0...(self.number_of_stories - 1) {
let obj = children[i].objectForKey("data")
let story = Story(
author: obj?.objectForKey("author") as! String,
comments: obj?.objectForKey("num_comments") as! Int,
domain: obj?.objectForKey("domain") as! String,
id: obj?.objectForKey("id") as! String,
score: obj?.objectForKey("score") as! Int,
subreddit: obj?.objectForKey("subreddit") as! String,
title: obj?.objectForKey("title") as! String,
url: obj?.objectForKey("url") as! String,
vote: VoteStatus.None
)
print(story)
stories.append(story)
}
} catch {
print(error)
}
self.stories = stories
dispatch_async(dispatch_get_main_queue(), {
// code here
self.tableView.reloadData()
})
}
}.resume()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return stories.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let story = stories[indexPath.item]
let cell = tableView.dequeueReusableCellWithIdentifier("StoryItemCellIdentifier", forIndexPath: indexPath) as! StoryItemCell
cell.cellLabel.text = story.title
cell.authorLabel.text = story.author
return cell
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
} | mit | 59717841b19637f7b198207ac8ab5ff6 | 36.134021 | 132 | 0.521244 | 5.626563 | false | false | false | false |
D8Ge/Jchat | Jchat/Pods/SwiftProtobuf/Sources/SwiftProtobuf/Google_Protobuf_Timestamp_Extensions.swift | 1 | 11220 | // ProtobufRuntime/Sources/Protobuf/Google_Protobuf_Timestamp_Extensions.swift - Timestamp extensions
//
// 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
//
// -----------------------------------------------------------------------------
///
/// Extend the generated Timestamp message with customized JSON coding,
/// arithmetic operations, and convenience methods.
///
// -----------------------------------------------------------------------------
import Swift
// TODO: Add convenience methods to interoperate with standard
// date/time classes: an initializer that accepts Unix timestamp as
// Int or Double, an easy way to convert to/from Foundation's
// NSDateTime (on Apple platforms only?), others?
private func FormatInt(n: Int32, digits: Int) -> String {
if n < 0 {
return FormatInt(n: -n, digits: digits)
} else if digits <= 0 {
return ""
} else if digits == 1 && n < 10 {
return ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"][Int(n)]
} else {
return FormatInt(n: n / 10, digits: digits - 1) + ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"][Int(n % 10)]
}
}
private func fromAscii2(_ digit0: Int, _ digit1: Int) throws -> Int {
let zero = Int(48)
let nine = Int(57)
if digit0 < zero || digit0 > nine || digit1 < zero || digit1 > nine {
throw ProtobufDecodingError.malformedJSONTimestamp
}
return digit0 * 10 + digit1 - 528
}
private func fromAscii4(_ digit0: Int, _ digit1: Int, _ digit2: Int, _ digit3: Int) throws -> Int {
let zero = Int(48)
let nine = Int(57)
if (digit0 < zero || digit0 > nine
|| digit1 < zero || digit1 > nine
|| digit2 < zero || digit2 > nine
|| digit3 < zero || digit3 > nine) {
throw ProtobufDecodingError.malformedJSONTimestamp
}
return digit0 * 1000 + digit1 * 100 + digit2 * 10 + digit3 - 53328
}
// Parse an RFC3339 timestamp into a pair of seconds-since-1970 and nanos.
private func parseTimestamp(s: String) throws -> (Int64, Int32) {
// Convert to an array of integer character values
let value = s.utf8.map{Int($0)}
if value.count < 20 {
throw ProtobufDecodingError.malformedJSONTimestamp
}
// Since the format is fixed-layout, we can just decode
// directly as follows.
let zero = Int(48)
let nine = Int(57)
let dash = Int(45)
let colon = Int(58)
let plus = Int(43)
let letterT = Int(84)
let letterZ = Int(90)
let period = Int(46)
// Year: 4 digits followed by '-'
let year = try fromAscii4(value[0], value[1], value[2], value[3])
if value[4] != dash || year < Int(1) || year > Int(9999) {
throw ProtobufDecodingError.malformedJSONTimestamp
}
// Month: 2 digits followed by '-'
let month = try fromAscii2(value[5], value[6])
if value[7] != dash || month < Int(1) || month > Int(12) {
throw ProtobufDecodingError.malformedJSONTimestamp
}
// Day: 2 digits followed by 'T'
let mday = try fromAscii2(value[8], value[9])
if value[10] != letterT || mday < Int(1) || mday > Int(31) {
throw ProtobufDecodingError.malformedJSONTimestamp
}
// Hour: 2 digits followed by ':'
let hour = try fromAscii2(value[11], value[12])
if value[13] != colon || hour > Int(23) {
throw ProtobufDecodingError.malformedJSONTimestamp
}
// Minute: 2 digits followed by ':'
let minute = try fromAscii2(value[14], value[15])
if value[16] != colon || minute > Int(59) {
throw ProtobufDecodingError.malformedJSONTimestamp
}
// Second: 2 digits (following char is checked below)
let second = try fromAscii2(value[17], value[18])
if second > Int(61) {
throw ProtobufDecodingError.malformedJSONTimestamp
}
// timegm() is almost entirely useless. It's nonexistent on
// some platforms, broken on others. Everything else I've tried
// is even worse. Hence the code below.
// (If you have a better way to do this, try it and see if it
// passes the test suite on both Linux and OS X.)
// Day of year
let mdayStart: [Int] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
var yday = Int64(mdayStart[month - 1])
let isleap = (year % 400 == 0) || ((year % 100 != 0) && (year % 4 == 0))
if isleap && (month > 2) {
yday += 1
}
yday += Int64(mday - 1)
// Days since start of epoch (including leap days)
var daysSinceEpoch = yday
daysSinceEpoch += Int64(365 * year) - Int64(719527)
daysSinceEpoch += Int64((year - 1) / 4)
daysSinceEpoch -= Int64((year - 1) / 100)
daysSinceEpoch += Int64((year - 1) / 400)
// Second within day
var daySec = Int64(hour)
daySec *= 60
daySec += Int64(minute)
daySec *= 60
daySec += Int64(second)
// Seconds since start of epoch
let t = daysSinceEpoch * Int64(86400) + daySec
// After seconds, comes various optional bits
var pos = 19
var nanos: Int32 = 0
if value[pos] == period { // "." begins fractional seconds
pos += 1
var digitValue = 100000000
while pos < value.count && value[pos] >= zero && value[pos] <= nine {
nanos += digitValue * (value[pos] - zero)
digitValue /= 10
pos += 1
}
}
var seconds: Int64 = 0
if value[pos] == plus || value[pos] == dash { // "+" or "-" starts Timezone offset
if pos + 6 > value.count {
throw ProtobufDecodingError.malformedJSONTimestamp
}
let hourOffset = try fromAscii2(value[pos + 1], value[pos + 2])
let minuteOffset = try fromAscii2(value[pos + 4], value[pos + 5])
if hourOffset > Int(13) || minuteOffset > Int(59) || value[pos + 3] != colon {
throw ProtobufDecodingError.malformedJSONTimestamp
}
var adjusted: Int64 = t
if value[pos] == plus {
adjusted -= Int64(hourOffset) * Int64(3600)
adjusted -= Int64(minuteOffset) * Int64(60)
} else {
adjusted += Int64(hourOffset) * Int64(3600)
adjusted += Int64(minuteOffset) * Int64(60)
}
if adjusted < -62135596800 || adjusted > 253402300799 {
throw ProtobufDecodingError.malformedJSONTimestamp
}
seconds = adjusted
pos += 6
} else if value[pos] == letterZ { // "Z" indicator for UTC
seconds = t
pos += 1
} else {
throw ProtobufDecodingError.malformedJSONTimestamp
}
if pos != value.count {
throw ProtobufDecodingError.malformedJSONTimestamp
}
return (seconds, nanos)
}
private func formatTimestamp(seconds: Int64, nanos: Int32) -> String? {
if ((seconds < 0 && nanos > 0)
|| (seconds > 0 && nanos < 0)
|| (seconds < -62135596800)
|| (seconds == -62135596800 && nanos < 0)
|| (seconds >= 253402300800)) {
return nil
}
// Can't just use gmtime() here because time_t is sometimes 32 bits. Ugh.
let secondsSinceStartOfDay = (Int32(seconds % 86400) + 86400) % 86400
let sec = secondsSinceStartOfDay % 60
let min = (secondsSinceStartOfDay / 60) % 60
let hour = secondsSinceStartOfDay / 3600
// The following implements Richards' algorithm (see the Wikipedia article
// for "Julian day").
// If you touch this code, please test it exhaustively by playing with
// Test_Timestamp.testJSON_range.
let julian = (seconds + 210866803200) / 86400
let f = julian + 1401 + (((4 * julian + 274277) / 146097) * 3) / 4 - 38
let e = 4 * f + 3
let g = e % 1461 / 4
let h = 5 * g + 2
let mday = Int32(h % 153 / 5 + 1)
let month = (h / 153 + 2) % 12 + 1
let year = e / 1461 - 4716 + (12 + 2 - month) / 12
// We can't use strftime here (it varies with locale)
// We can't use strftime_l here (it's not portable)
// The following is crude, but it works.
// TODO: If String(format:) works, that might be even better
// (it was broken on Linux a while back...)
let result = (FormatInt(n: Int32(year), digits: 4)
+ "-"
+ FormatInt(n: Int32(month), digits: 2)
+ "-"
+ FormatInt(n: mday, digits: 2)
+ "T"
+ FormatInt(n: hour, digits: 2)
+ ":"
+ FormatInt(n: min, digits: 2)
+ ":"
+ FormatInt(n: sec, digits: 2))
if nanos == 0 {
return "\(result)Z"
} else {
var digits: Int
var fraction: Int
if nanos % 1000000 == 0 {
fraction = Int(nanos) / 1000000
digits = 3
} else if nanos % 1000 == 0 {
fraction = Int(nanos) / 1000
digits = 6
} else {
fraction = Int(nanos)
digits = 9
}
var formatted_fraction = ""
while digits > 0 {
formatted_fraction = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"][fraction % 10] + formatted_fraction
fraction /= 10
digits -= 1
}
return "\(result).\(formatted_fraction)Z"
}
}
public extension Google_Protobuf_Timestamp {
public init(secondsSinceEpoch: Int64, nanos: Int32 = 0) {
self.init()
self.seconds = secondsSinceEpoch
self.nanos = nanos
}
public mutating func decodeFromJSONToken(token: ProtobufJSONToken) throws {
if case .string(let s) = token {
let timestamp = try parseTimestamp(s: s)
seconds = timestamp.0
nanos = timestamp.1
} else {
throw ProtobufDecodingError.schemaMismatch
}
}
public func serializeJSON() throws -> String {
let s = seconds
let n = nanos
if let formatted = formatTimestamp(seconds: s, nanos: n) {
return "\"\(formatted)\""
} else {
throw ProtobufEncodingError.timestampJSONRange
}
}
func serializeAnyJSON() throws -> String {
let value = try serializeJSON()
return "{\"@type\":\"\(anyTypeURL)\",\"value\":\(value)}"
}
}
private func normalizedTimestamp(seconds: Int64, nanos: Int32) -> Google_Protobuf_Timestamp {
var s = seconds
var n = nanos
if n >= 1000000000 || n <= -1000000000 {
s += Int64(n) / 1000000000
n = n % 1000000000
}
if s > 0 && n < 0 {
n += 1000000000
s -= 1
} else if s < 0 && n > 0 {
n -= 1000000000
s += 1
}
return Google_Protobuf_Timestamp(seconds: s, nanos: n)
}
public func -(lhs: Google_Protobuf_Timestamp, rhs: Google_Protobuf_Duration) -> Google_Protobuf_Timestamp {
return normalizedTimestamp(seconds: lhs.seconds - rhs.seconds, nanos: lhs.nanos - rhs.nanos)
}
public func+(lhs: Google_Protobuf_Timestamp, rhs: Google_Protobuf_Duration) -> Google_Protobuf_Timestamp {
return normalizedTimestamp(seconds: lhs.seconds + rhs.seconds, nanos: lhs.nanos + rhs.nanos)
}
| mit | 28d5c26f4d3e82821887ad1dc398b1c9 | 33.84472 | 122 | 0.580481 | 3.822828 | false | false | false | false |
mozilla-mobile/firefox-ios | Storage/Rust/RustPlaces.swift | 2 | 23314 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
import Shared
@_exported import MozillaAppServices
private let log = Logger.syncLogger
public protocol BookmarksHandler {
func getRecentBookmarks(limit: UInt, completion: @escaping ([BookmarkItemData]) -> Void)
}
public protocol HistoryMetadataObserver {
func noteHistoryMetadataObservation(key: HistoryMetadataKey,
observation: HistoryMetadataObservation,
completion: @escaping () -> Void)
}
public class RustPlaces: BookmarksHandler, HistoryMetadataObserver {
let databasePath: String
let writerQueue: DispatchQueue
let readerQueue: DispatchQueue
public var api: PlacesAPI?
public var writer: PlacesWriteConnection?
public var reader: PlacesReadConnection?
public fileprivate(set) var isOpen: Bool = false
private var didAttemptToMoveToBackup = false
private var notificationCenter: NotificationCenter
public init(databasePath: String,
notificationCenter: NotificationCenter = NotificationCenter.default) {
self.databasePath = databasePath
self.notificationCenter = notificationCenter
self.writerQueue = DispatchQueue(label: "RustPlaces writer queue: \(databasePath)", attributes: [])
self.readerQueue = DispatchQueue(label: "RustPlaces reader queue: \(databasePath)", attributes: [])
}
private func open() -> NSError? {
do {
api = try PlacesAPI(path: databasePath)
isOpen = true
notificationCenter.post(name: .RustPlacesOpened, object: nil)
return nil
} catch let err as NSError {
if let placesError = err as? PlacesApiError {
SentryIntegration.shared.sendWithStacktrace(
message: "Places error when opening Rust Places database",
tag: SentryTag.rustPlaces,
severity: .error,
description: placesError.localizedDescription)
} else {
SentryIntegration.shared.sendWithStacktrace(
message: "Unknown error when opening Rust Places database",
tag: SentryTag.rustPlaces,
severity: .error,
description: err.localizedDescription)
}
return err
}
}
private func close() -> NSError? {
api = nil
writer = nil
reader = nil
isOpen = false
return nil
}
private func withWriter<T>(_ callback: @escaping(_ connection: PlacesWriteConnection) throws -> T) -> Deferred<Maybe<T>> {
let deferred = Deferred<Maybe<T>>()
writerQueue.async {
guard self.isOpen else {
deferred.fill(Maybe(failure: PlacesConnectionError.connUseAfterApiClosed as MaybeErrorType))
return
}
if self.writer == nil {
self.writer = self.api?.getWriter()
}
if let writer = self.writer {
do {
let result = try callback(writer)
deferred.fill(Maybe(success: result))
} catch let error {
deferred.fill(Maybe(failure: error as MaybeErrorType))
}
} else {
deferred.fill(Maybe(failure: PlacesConnectionError.connUseAfterApiClosed as MaybeErrorType))
}
}
return deferred
}
private func withReader<T>(_ callback: @escaping(_ connection: PlacesReadConnection) throws -> T) -> Deferred<Maybe<T>> {
let deferred = Deferred<Maybe<T>>()
readerQueue.async {
guard self.isOpen else {
deferred.fill(Maybe(failure: PlacesConnectionError.connUseAfterApiClosed as MaybeErrorType))
return
}
if self.reader == nil {
do {
self.reader = try self.api?.openReader()
} catch let error {
deferred.fill(Maybe(failure: error as MaybeErrorType))
}
}
if let reader = self.reader {
do {
let result = try callback(reader)
deferred.fill(Maybe(success: result))
} catch let error {
deferred.fill(Maybe(failure: error as MaybeErrorType))
}
} else {
deferred.fill(Maybe(failure: PlacesConnectionError.connUseAfterApiClosed as MaybeErrorType))
}
}
return deferred
}
public func migrateBookmarksIfNeeded(fromBrowserDB browserDB: BrowserDB) {
// Since we use the existence of places.db as an indication that we've
// already migrated bookmarks, assert that places.db is not open here.
assert(!isOpen, "Shouldn't attempt to migrate bookmarks after opening Rust places.db")
// We only need to migrate bookmarks here if the old browser.db file
// already exists AND the new Rust places.db file does NOT exist yet.
// This is to ensure that we only ever run this migration ONCE. In
// addition, it is the caller's (Profile.swift) responsibility to NOT
// use this migration API for users signed into a Firefox Account.
// Those users will automatically get all their bookmarks on next Sync.
guard FileManager.default.fileExists(atPath: browserDB.databasePath),
!FileManager.default.fileExists(atPath: databasePath) else {
return
}
// Ensure that the old BrowserDB schema is up-to-date before migrating.
_ = browserDB.touch().value
// Open the Rust places.db now for the first time.
_ = reopenIfClosed()
do {
try api?.migrateBookmarksFromBrowserDb(path: browserDB.databasePath)
} catch let err as NSError {
SentryIntegration.shared.sendWithStacktrace(
message: "Error encountered while migrating bookmarks from BrowserDB",
tag: SentryTag.rustPlaces,
severity: .error,
description: err.localizedDescription)
}
}
public func getBookmarksTree(rootGUID: GUID, recursive: Bool) -> Deferred<Maybe<BookmarkNodeData?>> {
return withReader { connection in
return try connection.getBookmarksTree(rootGUID: rootGUID, recursive: recursive)
}
}
public func getBookmark(guid: GUID) -> Deferred<Maybe<BookmarkNodeData?>> {
return withReader { connection in
return try connection.getBookmark(guid: guid)
}
}
public func getRecentBookmarks(limit: UInt, completion: @escaping ([BookmarkItemData]) -> Void) {
let deferredResponse = withReader { connection in
return try connection.getRecentBookmarks(limit: limit)
}
deferredResponse.upon { result in
completion(result.successValue ?? [])
}
}
public func getRecentBookmarks(limit: UInt) -> Deferred<Maybe<[BookmarkItemData]>> {
return withReader { connection in
return try connection.getRecentBookmarks(limit: limit)
}
}
public func getBookmarkURLForKeyword(keyword: String) -> Deferred<Maybe<String?>> {
return withReader { connection in
return try connection.getBookmarkURLForKeyword(keyword: keyword)
}
}
public func getBookmarksWithURL(url: String) -> Deferred<Maybe<[BookmarkItemData]>> {
return withReader { connection in
return try connection.getBookmarksWithURL(url: url)
}
}
public func isBookmarked(url: String) -> Deferred<Maybe<Bool>> {
return getBookmarksWithURL(url: url).bind { result in
guard let bookmarks = result.successValue else {
return deferMaybe(false)
}
return deferMaybe(!bookmarks.isEmpty)
}
}
public func searchBookmarks(query: String, limit: UInt) -> Deferred<Maybe<[BookmarkItemData]>> {
return withReader { connection in
return try connection.searchBookmarks(query: query, limit: limit)
}
}
public func interruptWriter() {
writer?.interrupt()
}
public func interruptReader() {
reader?.interrupt()
}
public func runMaintenance() {
_ = withWriter { connection in
try connection.runMaintenance()
}
}
public func deleteBookmarkNode(guid: GUID) -> Success {
return withWriter { connection in
let result = try connection.deleteBookmarkNode(guid: guid)
guard result else {
log.debug("Bookmark with GUID \(guid) does not exist.")
return
}
self.notificationCenter.post(name: .BookmarksUpdated, object: self)
}
}
public func deleteBookmarksWithURL(url: String) -> Success {
return getBookmarksWithURL(url: url) >>== { bookmarks in
let deferreds = bookmarks.map({ self.deleteBookmarkNode(guid: $0.guid) })
return all(deferreds).bind { results in
if let error = results.find({ $0.isFailure })?.failureValue {
return deferMaybe(error)
}
self.notificationCenter.post(name: .BookmarksUpdated, object: self)
return succeed()
}
}
}
public func createFolder(parentGUID: GUID, title: String,
position: UInt32?) -> Deferred<Maybe<GUID>> {
return withWriter { connection in
return try connection.createFolder(parentGUID: parentGUID, title: title, position: position)
}
}
public func createSeparator(parentGUID: GUID,
position: UInt32?) -> Deferred<Maybe<GUID>> {
return withWriter { connection in
return try connection.createSeparator(parentGUID: parentGUID, position: position)
}
}
@discardableResult
public func createBookmark(parentGUID: GUID,
url: String,
title: String?,
position: UInt32?) -> Deferred<Maybe<GUID>> {
return withWriter { connection in
let response = try connection.createBookmark(parentGUID: parentGUID, url: url, title: title, position: position)
self.notificationCenter.post(name: .BookmarksUpdated, object: self)
return response
}
}
public func updateBookmarkNode(guid: GUID, parentGUID: GUID? = nil, position: UInt32? = nil, title: String? = nil, url: String? = nil) -> Success {
return withWriter { connection in
return try connection.updateBookmarkNode(guid: guid, parentGUID: parentGUID, position: position, title: title, url: url)
}
}
public func reopenIfClosed() -> NSError? {
var error: NSError?
writerQueue.sync {
guard !isOpen else { return }
error = open()
}
return error
}
public func forceClose() -> NSError? {
var error: NSError?
writerQueue.sync {
guard isOpen else { return }
error = close()
}
return error
}
public func syncBookmarks(unlockInfo: SyncUnlockInfo) -> Success {
let deferred = Success()
writerQueue.async {
guard self.isOpen else {
deferred.fill(Maybe(failure: PlacesConnectionError.connUseAfterApiClosed as MaybeErrorType))
return
}
do {
try _ = self.api?.syncBookmarks(unlockInfo: unlockInfo)
deferred.fill(Maybe(success: ()))
} catch let err as NSError {
if let placesError = err as? PlacesApiError {
SentryIntegration.shared.sendWithStacktrace(
message: "Places error when syncing Places database",
tag: SentryTag.rustPlaces,
severity: .error,
description: placesError.localizedDescription)
} else {
SentryIntegration.shared.sendWithStacktrace(
message: "Unknown error when opening Rust Places database",
tag: SentryTag.rustPlaces,
severity: .error,
description: err.localizedDescription)
}
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func syncHistory(unlockInfo: SyncUnlockInfo) -> Success {
let deferred = Success()
writerQueue.async {
guard self.isOpen else {
deferred.fill(Maybe(failure: PlacesConnectionError.connUseAfterApiClosed as MaybeErrorType))
return
}
do {
try _ = self.api?.syncHistory(unlockInfo: unlockInfo)
deferred.fill(Maybe(success: ()))
} catch let err as NSError {
if let placesError = err as? PlacesApiError {
SentryIntegration.shared.sendWithStacktrace(message: "Places error when syncing Places database",
tag: SentryTag.rustPlaces,
severity: .error,
description: placesError.localizedDescription)
} else {
SentryIntegration.shared.sendWithStacktrace(message: "Unknown error when opening Rust Places database",
tag: SentryTag.rustPlaces,
severity: .error,
description: err.localizedDescription)
}
deferred.fill(Maybe(failure: err))
}
}
return deferred
}
public func resetBookmarksMetadata() -> Success {
let deferred = Success()
writerQueue.async {
guard self.isOpen else {
deferred.fill(Maybe(failure: PlacesConnectionError.connUseAfterApiClosed as MaybeErrorType))
return
}
do {
try self.api?.resetBookmarkSyncMetadata()
deferred.fill(Maybe(success: ()))
} catch let error {
deferred.fill(Maybe(failure: error as MaybeErrorType))
}
}
return deferred
}
public func resetHistoryMetadata() -> Success {
let deferred = Success()
writerQueue.async {
guard self.isOpen else {
deferred.fill(Maybe(failure: PlacesConnectionError.connUseAfterApiClosed as MaybeErrorType))
return
}
do {
try self.api?.resetHistorySyncMetadata()
deferred.fill(Maybe(success: ()))
} catch let error {
deferred.fill(Maybe(failure: error as MaybeErrorType))
}
}
return deferred
}
public func getHistoryMetadataSince(since: Int64) -> Deferred<Maybe<[HistoryMetadata]>> {
return withReader { connection in
return try connection.getHistoryMetadataSince(since: since)
}
}
public func getHighlights(weights: HistoryHighlightWeights, limit: Int32) -> Deferred<Maybe<[HistoryHighlight]>> {
return withReader { connection in
return try connection.getHighlights(weights: weights, limit: limit)
}
}
public func queryHistoryMetadata(query: String, limit: Int32) -> Deferred<Maybe<[HistoryMetadata]>> {
return withReader { connection in
return try connection.queryHistoryMetadata(query: query, limit: limit)
}
}
public func noteHistoryMetadataObservation(key: HistoryMetadataKey,
observation: HistoryMetadataObservation,
completion: @escaping () -> Void) {
let deferredResponse = withReader { connection in
return self.noteHistoryMetadataObservation(key: key, observation: observation)
}
deferredResponse.upon { result in
completion()
}
}
/**
Title observations must be made first for any given url. Observe one fact at a time (e.g. just the viewTime, or just the documentType).
*/
public func noteHistoryMetadataObservation(key: HistoryMetadataKey, observation: HistoryMetadataObservation) -> Deferred<Maybe<Void>> {
return withWriter { connection in
if let title = observation.title {
let response: Void = try connection.noteHistoryMetadataObservationTitle(key: key, title: title)
self.notificationCenter.post(name: .HistoryUpdated, object: nil)
return response
}
if let documentType = observation.documentType {
let response: Void = try connection.noteHistoryMetadataObservationDocumentType(key: key, documentType: documentType)
self.notificationCenter.post(name: .HistoryUpdated, object: nil)
return response
}
if let viewTime = observation.viewTime {
let response: Void = try connection.noteHistoryMetadataObservationViewTime(key: key, viewTime: viewTime)
self.notificationCenter.post(name: .HistoryUpdated, object: nil)
return response
}
}
}
public func deleteHistoryMetadataOlderThan(olderThan: Int64) -> Deferred<Maybe<Void>> {
return withWriter { connection in
let response: Void = try connection.deleteHistoryMetadataOlderThan(olderThan: olderThan)
self.notificationCenter.post(name: .HistoryUpdated, object: nil)
return response
}
}
private func deleteHistoryMetadata(since startDate: Int64) -> Deferred<Maybe<Void>> {
let now = Date().toMillisecondsSince1970()
return withWriter { connection in
return try connection.deleteVisitsBetween(start: startDate, end: now)
}
}
public func deleteHistoryMetadata(
since startDate: Int64,
completion: @escaping (Bool) -> Void
) {
let deferredResponse = deleteHistoryMetadata(since: startDate)
deferredResponse.upon { result in
completion(result.isSuccess)
}
}
private func migrateHistory(dbPath: String, lastSyncTimestamp: Int64) -> Deferred<Maybe<HistoryMigrationResult>> {
return withWriter { connection in
return try connection.migrateHistoryFromBrowserDb(path: dbPath, lastSyncTimestamp: lastSyncTimestamp)
}
}
public func migrateHistory(dbPath: String, lastSyncTimestamp: Int64, completion: @escaping (HistoryMigrationResult) -> Void, errCallback: @escaping (Error?) -> Void) {
_ = reopenIfClosed()
let deferredResponse = self.migrateHistory(dbPath: dbPath, lastSyncTimestamp: lastSyncTimestamp)
deferredResponse.upon { result in
guard result.isSuccess, let result = result.successValue else {
errCallback(result.failureValue)
return
}
completion(result)
}
}
public func deleteHistoryMetadata(key: HistoryMetadataKey) -> Deferred<Maybe<Void>> {
return withWriter { connection in
let response: Void = try connection.deleteHistoryMetadata(key: key)
self.notificationCenter.post(name: .HistoryUpdated, object: nil)
return response
}
}
public func deleteVisitsFor(url: Url) -> Deferred<Maybe<Void>> {
return withWriter { connection in
return try connection.deleteVisitsFor(url: url)
}
}
}
// MARK: History APIs
extension VisitTransition {
public static func fromVisitType(visitType: VisitType) -> Self {
switch visitType {
case .unknown:
return VisitTransition.link
case .link:
return VisitTransition.link
case .typed:
return VisitTransition.typed
case .bookmark:
return VisitTransition.bookmark
case .embed:
return VisitTransition.embed
case .permanentRedirect:
return VisitTransition.redirectPermanent
case .temporaryRedirect:
return VisitTransition.redirectTemporary
case .download:
return VisitTransition.download
case .framedLink:
return VisitTransition.framedLink
case .recentlyClosed:
return VisitTransition.link
}
}
}
extension RustPlaces {
public func applyObservation(visitObservation: VisitObservation) -> Success {
return withWriter { connection in
return try connection.applyObservation(visitObservation: visitObservation)
}
}
public func deleteEverythingHistory() -> Success {
return withWriter { connection in
return try connection.deleteEverythingHistory()
}
}
public func deleteVisitsFor(_ url: String) -> Success {
return withWriter { connection in
return try connection.deleteVisitsFor(url: url)
}
}
public func deleteVisitsBetween(_ date: Date) -> Success {
return withWriter { connection in
return try connection.deleteVisitsBetween(start: PlacesTimestamp(date.toMillisecondsSince1970()),
end: PlacesTimestamp(Date().toMillisecondsSince1970()))
}
}
public func queryAutocomplete(matchingSearchQuery filter: String, limit: Int) -> Deferred<Maybe<[SearchResult]>> {
return withReader { connection in
return try connection.queryAutocomplete(search: filter, limit: Int32(limit))
}
}
public func getVisitPageWithBound(limit: Int, offset: Int, excludedTypes: VisitTransitionSet) -> Deferred<Maybe<HistoryVisitInfosWithBound>> {
return withReader { connection in
return try connection.getVisitPageWithBound(bound: Int64(Date().toMillisecondsSince1970()),
offset: Int64(offset),
count: Int64(limit),
excludedTypes: excludedTypes)
}
}
public func getTopFrecentSiteInfos(limit: Int, thresholdOption: FrecencyThresholdOption) -> Deferred<Maybe<[TopFrecentSiteInfo]>> {
return withReader { connection in
return try connection.getTopFrecentSiteInfos(numItems: Int32(limit), thresholdOption: thresholdOption)
}
}
}
| mpl-2.0 | 74908d92189c130cb330ab893e17edee | 36.908943 | 171 | 0.593334 | 5.337454 | false | false | false | false |
yopeso/Taylor | TaylorFramework/Taylor/CLIReporter.swift | 4 | 2163 | //
// ResultPrinter.swift
// Taylor
//
// Created by Alex Culeva on 11/10/15.
// Copyright © 2015 YOPESO. All rights reserved.
//
import Foundation
typealias ResultOutput = (path: String, warnings: Int)
struct CLIReporter {
let results: [ResultOutput]
init(results: [ResultOutput]) {
self.results = results
}
func getResultsString() -> String {
guard results.count > 0 else { return "" }
let numberOfExtraCharacters = 9
let maximalPathChars = results.map { $0.path }.maxLength
let totalChars = maximalPathChars + numberOfExtraCharacters
return results.reduce(getBorderString(totalChars)) {
$0 + getResultOutputString($1, numberOfCharacters: maximalPathChars) + "\n"
} + getBorderString(totalChars) + getStatisticsString()
}
fileprivate func getBorderString(_ size: Int) -> String {
return "=" * size + "\n"
}
fileprivate func getResultOutputString(_ resultOutput: ResultOutput, numberOfCharacters charNum: Int) -> String {
let missingSpacesString = " " * (charNum - resultOutput.path.characters.count)
let warningsString = "|" + (getResultsString(resultOutput.warnings) + " |")
return warningsString + resultOutput.path + missingSpacesString + "|"
}
fileprivate func getStatisticsString() -> String {
return "Found \(results.reduce(0) { $0 + $1.warnings }) violations in \(results.count) files."
}
fileprivate func getResultsString(_ warnings: Int) -> String {
let checkmark = "\u{001B}[0;32m✓\u{001B}[0m"
let warning = "⚠️"
let explosion = "\u{1F4A5}"
if warnings == 0 {
return " \(checkmark) "
} else if warnings < 100 {
let string = " \(warnings)" + warning
return string.padding(toLength: 5, withPad: " ", startingAt: 0)
} else {
return " \(explosion) "
}
}
}
extension Array where Element: StringType {
var maxLength: Int {
return self.reduce(0) { Swift.max($0, String(describing: $1).characters.count) }
}
}
| mit | 8fe718c1dac5b19a91c3f2f9af5a71cc | 32.169231 | 117 | 0.608534 | 4.114504 | false | false | false | false |
hoobaa/nkbd | Keyboard/mKeyboardModel.swift | 7 | 4816 | //
// KeyboardModel.swift
// TransliteratingKeyboard
//
// Created by Alexei Baboulevitch on 7/10/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
import Foundation
var counter = 0
enum ShiftState {
case Disabled
case Enabled
case Locked
func uppercase() -> Bool {
switch self {
case Disabled:
return false
case Enabled:
return true
case Locked:
return true
}
}
}
class Keyboard {
var pages: [Page]
init() {
self.pages = []
}
func addKey(key: Key, row: Int, page: Int) {
if self.pages.count <= page {
for i in self.pages.count...page {
self.pages.append(Page())
}
}
self.pages[page].addKey(key, row: row)
}
}
class Page {
var rows: [[Key]]
init() {
self.rows = []
}
func addKey(key: Key, row: Int) {
if self.rows.count <= row {
for i in self.rows.count...row {
self.rows.append([])
}
}
self.rows[row].append(key)
}
}
class Key: Hashable {
enum KeyType {
case Character
case SpecialCharacter
case Shift
case Backspace
case ModeChange
case KeyboardChange
case Period
case Space
case Return
case Settings
case Other
}
var type: KeyType
var uppercaseKeyCap: String?
var lowercaseKeyCap: String?
var uppercaseOutput: String?
var lowercaseOutput: String?
var toMode: Int? //if the key is a mode button, this indicates which page it links to
var isCharacter: Bool {
get {
switch self.type {
case
.Character,
.SpecialCharacter,
.Period:
return true
default:
return false
}
}
}
var isSpecial: Bool {
get {
switch self.type {
case .Shift:
return true
case .Backspace:
return true
case .ModeChange:
return true
case .KeyboardChange:
return true
case .Return:
return true
case .Settings:
return true
default:
return false
}
}
}
var hasOutput: Bool {
get {
return (self.uppercaseOutput != nil) || (self.lowercaseOutput != nil)
}
}
// TODO: this is kind of a hack
var hashValue: Int
init(_ type: KeyType) {
self.type = type
self.hashValue = counter
counter += 1
}
convenience init(_ key: Key) {
self.init(key.type)
self.uppercaseKeyCap = key.uppercaseKeyCap
self.lowercaseKeyCap = key.lowercaseKeyCap
self.uppercaseOutput = key.uppercaseOutput
self.lowercaseOutput = key.lowercaseOutput
self.toMode = key.toMode
}
func setLetter(letter: String) {
self.lowercaseOutput = (letter as NSString).lowercaseString
self.uppercaseOutput = (letter as NSString).uppercaseString
self.lowercaseKeyCap = self.lowercaseOutput
self.uppercaseKeyCap = self.uppercaseOutput
}
func outputForCase(uppercase: Bool) -> String {
if uppercase {
if self.uppercaseOutput != nil {
return self.uppercaseOutput!
}
else if self.lowercaseOutput != nil {
return self.lowercaseOutput!
}
else {
return ""
}
}
else {
if self.lowercaseOutput != nil {
return self.lowercaseOutput!
}
else if self.uppercaseOutput != nil {
return self.uppercaseOutput!
}
else {
return ""
}
}
}
func keyCapForCase(uppercase: Bool) -> String {
if uppercase {
if self.uppercaseKeyCap != nil {
return self.uppercaseKeyCap!
}
else if self.lowercaseKeyCap != nil {
return self.lowercaseKeyCap!
}
else {
return ""
}
}
else {
if self.lowercaseKeyCap != nil {
return self.lowercaseKeyCap!
}
else if self.uppercaseKeyCap != nil {
return self.uppercaseKeyCap!
}
else {
return ""
}
}
}
}
func ==(lhs: Key, rhs: Key) -> Bool {
return lhs.hashValue == rhs.hashValue
}
| bsd-3-clause | 88222a742a73a9cc0559240adf039626 | 22.153846 | 89 | 0.487542 | 5.107105 | false | false | false | false |
nickoneill/Pantry | Pantry/Pantry.swift | 2 | 7172 | //
// Pantry.swift
// Pantry
//
// Created by Nick O'Neill on 10/29/15.
// Copyright © 2015 That Thing in Swift. All rights reserved.
//
import Foundation
/**
# Pantry
Pantry is a lightweight way to persist structs containing user data,
cached content or other relevant objects for later retrieval.
### Storage sample
```swift
let someCustomStruct = SomeCustomStruct(...)
Pantry.pack(someCustomStruct, "user_data")
```
### Retrieval sample
```swift
if let unpackedCustomStruct: SomeCustomStruct = Pantry.unpack("user_data") {
eprint("got my data out", unpackedCustomStruct)
} else {
print("there was no struct data to get")
}
```
*/
open class Pantry {
// Set to a string identifier to enable in memory mode with no persistent caching. Useful for unit testing.
open static var enableInMemoryModeWithIdentifier: String?
// MARK: pack generics
/**
Packs a generic struct that conforms to the `Storable` protocol
- parameter object: Generic object that will be stored
- parameter key: The object's key
- parameter expires: The storage expiration. Defaults to `Never`
*/
open static func pack<T: Storable>(_ object: T, key: String, expires: StorageExpiry = .never) {
let warehouse = getWarehouse(key)
warehouse.write(object.toDictionary() as Any, expires: expires)
}
/**
Packs a generic collection of structs that conform to the `Storable` protocol
- parameter objects: Generic collection of objects that will be stored
- parameter key: The objects' key
*/
open static func pack<T: Storable>(_ objects: [T], key: String, expires: StorageExpiry = .never) {
let warehouse = getWarehouse(key)
var result = [Any]()
for object in objects {
result.append(object.toDictionary() as Any)
}
warehouse.write(result as Any, expires: expires)
}
/**
Packs a default storage type.
- parameter object: Default object that will be stored
- parameter key: The object's key
- parameter expires: The storage expiration. Defaults to `Never`
- SeeAlso: `StorableDefaultType`
*/
open static func pack<T: StorableDefaultType>(_ object: T, key: String, expires: StorageExpiry = .never) {
let warehouse = getWarehouse(key)
warehouse.write(object as Any, expires: expires)
}
/**
Packs a collection of default storage types.
- parameter objects: Collection of objects that will be stored
- parameter key: The object's key
- SeeAlso: `StorableDefaultType`
*/
open static func pack<T: StorableDefaultType>(_ objects: [T], key: String, expires: StorageExpiry = .never) {
let warehouse = getWarehouse(key)
var result = [Any]()
for object in objects {
result.append(object as Any)
}
warehouse.write(result as Any, expires: expires)
}
/**
Packs a collection of optional default storage types.
- parameter objects: Collection of optional objects that will be stored
- parameter key: The object's key
- SeeAlso: `StorableDefaultType`
*/
open static func pack<T: StorableDefaultType>(_ objects: [T?], key: String, expires: StorageExpiry = .never) {
let warehouse = getWarehouse(key)
var result = [Any]()
for object in objects {
result.append(object as Any)
}
warehouse.write(result as Any, expires: expires)
}
// MARK: unpack generics
/**
Unpacks a generic struct that conforms to the `Storable` protocol
- parameter key: The object's key
- returns: T?
*/
open static func unpack<T: Storable>(_ key: String) -> T? {
let warehouse = getWarehouse(key)
if warehouse.cacheExists() {
return T(warehouse: warehouse)
}
return nil
}
/**
Unpacks a generic collection of structs that conform to the `Storable` protocol
- parameter key: The objects' key
- returns: [T]?
*/
open static func unpack<T: Storable>(_ key: String) -> [T]? {
let warehouse = getWarehouse(key)
guard warehouse.cacheExists(),
let cache = warehouse.loadCache() as? Array<Any> else {
return nil
}
var unpackedItems = [T]()
for case let item as [String: Any] in cache {
if let unpackedItem: T = unpack(item) {
unpackedItems.append(unpackedItem)
}
}
return unpackedItems
}
/**
Unpacks a collection of default storage types.
- parameter key: The object's key
- returns: [T]?
- SeeAlso: `StorableDefaultType`
*/
open static func unpack<T: StorableDefaultType>(_ key: String) -> [T]? {
let warehouse = getWarehouse(key)
guard warehouse.cacheExists(),
let cache = warehouse.loadCache() as? Array<Any> else {
return nil
}
var unpackedItems = [T]()
for case let item as T in cache {
unpackedItems.append(item)
}
return unpackedItems
}
/**
Unacks a default storage type.
- parameter key: The object's key
- SeeAlso: `StorableDefaultType`
*/
open static func unpack<T: StorableDefaultType>(_ key: String) -> T? {
let warehouse = getWarehouse(key)
guard warehouse.cacheExists(),
let cache = warehouse.loadCache() as? T else {
return nil
}
return cache
}
/**
Expire a given object
- parameter key: The object's key
*/
open static func expire(_ key: String) {
let warehouse = getWarehouse(key)
warehouse.removeCache()
}
/// Deletes all the cache
///
/// - Note: This will clear in-memory as well as JSON cache
open static func removeAllCache() {
///Blindly remove all the data!
MemoryWarehouse.removeAllCache()
JSONWarehouse.removeAllCache()
}
open static func itemExistsForKey(_ key: String) -> Bool {
let warehouse = getWarehouse(key)
return warehouse.cacheExists()
}
static func unpack<T: Storable>(_ dictionary: [String: Any]) -> T? {
let warehouse = getWarehouse(dictionary as Any)
return T(warehouse: warehouse)
}
static func getWarehouse(_ forKey: String) -> Warehouseable & WarehouseCacheable {
if let inMemoryIdentifier = Pantry.enableInMemoryModeWithIdentifier {
return MemoryWarehouse(key: forKey, inMemoryIdentifier: inMemoryIdentifier)
} else {
return JSONWarehouse(key: forKey)
}
}
static func getWarehouse(_ forContext: Any) -> Warehouseable {
if let inMemoryIdentifier = Pantry.enableInMemoryModeWithIdentifier {
return MemoryWarehouse(context: forContext, inMemoryIdentifier: inMemoryIdentifier)
} else {
return JSONWarehouse(context: forContext)
}
}
}
| mit | c12ac9baa7edaf6904bf55e211533387 | 28.632231 | 114 | 0.612746 | 4.451273 | false | false | false | false |
inkyfox/SwiftySQL | Sources/SQLPrefixUnaryExprGenerator.swift | 3 | 1411 | //
// SQLPrefixUnaryExprGenerator.swift
// SwiftySQL
//
// Created by indy on 2016. 10. 23..
// Copyright © 2016년 Gen X Hippies Company. All rights reserved.
//
import Foundation
private let trimmedUnaryOperators = Set<String>(["+", "-", "~"])
class SQLPrefixUnaryExprGenerator: SQLElementGenerator<SQLPrefixUnaryExpr> {
override func generate(_ element: SQLPrefixUnaryExpr, forRead: Bool) -> String {
var query = element.op
if !trimmedUnaryOperators.contains(element.op) {
query += " "
}
query += element.rhs.sqlStringBoxedIfNeeded(forRead: forRead, by: generator)
return query
}
override func generateFormatted(_ element: SQLPrefixUnaryExpr,
forRead: Bool,
withIndent indent: Int) -> String {
var query = "\(element.op)"
var nextIndent = indent + query.characters.count
if !trimmedUnaryOperators.contains(element.op) {
query += " "
nextIndent += 1
}
query += element.rhs.formattedSQLStringBoxedIfNeeded(forRead: forRead,
withIndent: nextIndent,
by: generator)
return query
}
}
| mit | 7c9e8b68eec0e1441bc6692c3f291de8 | 28.333333 | 84 | 0.524858 | 5.195572 | false | false | false | false |
esttorhe/MammutAPI | Sources/MammutAPI/Mappers/TagMapper.swift | 1 | 700 | //
// Created by Esteban Torres on 23.04.17.
// Copyright (c) 2017 Esteban Torres. All rights reserved.
//
import Foundation
internal class TagMapper: ModelMapping {
typealias Model = Tag
func map(json: ModelMapping.JSONDictionary) -> Result<Model, MammutAPIError.MappingError> {
guard
let name = json["name"] as? String,
let urlString = json["url"] as? String,
let url = URL(string: urlString)
else {
return .failure(MammutAPIError.MappingError.incompleteModel)
}
let mention = Tag(
name: name,
url: url
)
return .success(mention)
}
}
| mit | 76e55db06bcd88017c545956d9d82763 | 25.923077 | 95 | 0.57 | 4.375 | false | false | false | false |
gaurav1981/Swiftz | SwiftzTests/StringExtSpec.swift | 1 | 3856 | //
// StringExtSpec.swift
// swiftz
//
// Created by Robert Widmann on 1/19/15.
// Copyright (c) 2015 TypeLift. All rights reserved.
//
import XCTest
import Swiftz
import SwiftCheck
class StringExtSpec : XCTestCase {
func testProperties() {
property["unlines • lines === ('\n' • id)"] = forAll { (x : String) in
let l = x.lines()
let u = String.unlines(l)
return u == (x + "\n")
}
property["Strings of Equatable elements obey reflexivity"] = forAll { (l : String) in
return l == l
}
property["Strings of Equatable elements obey symmetry"] = forAll { (x : String, y : String) in
return (x == y) == (y == x)
}
property["Strings of Equatable elements obey transitivity"] = forAll { (x : String, y : String, z : String) in
if (x == y) && (y == z) {
return x == z
}
return Discard()
}
property["Strings of Equatable elements obey negation"] = forAll { (x : String, y : String) in
return (x != y) == !(x == y)
}
property["Strings of Comparable elements obey reflexivity"] = forAll { (l : String) in
return l == l
}
property["String obeys the Functor identity law"] = forAll { (x : String) in
return (x.fmap(identity)) == identity(x)
}
property["String obeys the Functor composition law"] = forAll { (f : ArrowOf<Character, Character>, g : ArrowOf<Character, Character>, x : String) in
return ((f.getArrow • g.getArrow) <^> x) == (x.fmap(g.getArrow).fmap(f.getArrow))
}
property["String obeys the Applicative identity law"] = forAll { (x : String) in
return (pure(identity) <*> x) == x
}
// Swift unroller can't handle our scale.
// property["String obeys the first Applicative composition law"] = forAll { (fl : ArrayOf<ArrowOf<Character, Character>>, gl : ArrayOf<ArrowOf<Character, Character>>, x : String) in
// let f = fl.getArray.map({ $0.getArrow })
// let g = gl.getArray.map({ $0.getArrow })
// return (curry(•) <^> f <*> g <*> x) == (f <*> (g <*> x))
// }
//
// property["String obeys the second Applicative composition law"] = forAll { (fl : ArrayOf<ArrowOf<Character, Character>>, gl : ArrayOf<ArrowOf<Character, Character>>, x : String) in
// let f = fl.getArray.map({ $0.getArrow })
// let g = gl.getArray.map({ $0.getArrow })
// return (pure(curry(•)) <*> f <*> g <*> x) == (f <*> (g <*> x))
// }
property["String obeys the Monoidal left identity law"] = forAll { (x : String) in
return (x + String.mzero) == x
}
property["String obeys the Monoidal right identity law"] = forAll { (x : String) in
return (String.mzero + x) == x
}
property["cons behaves"] = forAll { (c : Character, s : String) in
return String.cons(c, tail: s) == String(c) + s
}
property["replicate behaves"] = forAll { (n : UInt, x : Character) in
return String.replicate(n, value: x) == List.replicate(n, value: String(x)).reduce({ $0 + $1 }, initial: "")
}
property["map behaves"] = forAll { (xs : String) in
return xs.map(identity) == xs.fmap(identity)
}
property["map behaves"] = forAll { (xs : String) in
let fs : Character -> String = { String.replicate(2, value: $0) }
return (xs >>- fs) == Array(xs).map(fs).reduce("", combine: +)
}
property["filter behaves"] = forAll { (xs : String, pred : ArrowOf<Character, Bool>) in
return xs.filter(pred.getArrow).reduce({ $0.0 && pred.getArrow($0.1) }, initial: true)
}
property["isPrefixOf behaves"] = forAll { (s1 : String, s2 : String) in
if s1.isPrefixOf(s2) {
return s1.stripPrefix(s2) != nil
}
if s2.isPrefixOf(s1) {
return s2.stripPrefix(s1) != nil
}
return Discard()
}
property["isSuffixOf behaves"] = forAll { (s1 : String, s2 : String) in
if s1.isSuffixOf(s2) {
return s1.stripSuffix(s2) != nil
}
if s2.isSuffixOf(s1) {
return s2.stripSuffix(s1) != nil
}
return Discard()
}
}
}
| bsd-3-clause | 47d8d78ff23907074acb4e1a0a7b9567 | 30.52459 | 184 | 0.613365 | 3.101613 | false | false | false | false |
KeithPiTsui/Pavers | Pavers/Sources/FRP/ReactiveSwift/SignalProducer.swift | 2 | 125539 | import Dispatch
import Foundation
/// A SignalProducer creates Signals that can produce values of type `Value`
/// and/or fail with errors of type `Error`. If no failure should be possible,
/// `Never` can be specified for `Error`.
///
/// SignalProducers can be used to represent operations or tasks, like network
/// requests, where each invocation of `start()` will create a new underlying
/// operation. This ensures that consumers will receive the results, versus a
/// plain Signal, where the results might be sent before any observers are
/// attached.
///
/// Because of the behavior of `start()`, different Signals created from the
/// producer may see a different version of Events. The Events may arrive in a
/// different order between Signals, or the stream might be completely
/// different!
public struct SignalProducer<Value, Error: Swift.Error> {
public typealias ProducedSignal = Signal<Value, Error>
/// `core` is the actual implementation for this `SignalProducer`. It is responsible
/// of:
///
/// 1. handling the single-observer `start`; and
/// 2. building `Signal`s on demand via its `makeInstance()` method, which produces a
/// `Signal` with the associated side effect and interrupt handle.
fileprivate let core: SignalProducerCore<Value, Error>
/// Convert an entity into its equivalent representation as `SignalProducer`.
///
/// - parameters:
/// - base: The entity to convert from.
public init<T: SignalProducerConvertible>(_ base: T) where T.Value == Value, T.Error == Error {
self = base.producer
}
/// Initializes a `SignalProducer` that will emit the same events as the
/// given signal.
///
/// If the Disposable returned from `start()` is disposed or a terminating
/// event is sent to the observer, the given signal will be disposed.
///
/// - parameters:
/// - signal: A signal to observe after starting the producer.
public init(_ signal: Signal<Value, Error>) {
self.init { observer, lifetime in
lifetime += signal.observe(observer)
}
}
/// Initialize a `SignalProducer` which invokes the supplied starting side
/// effect once upon the creation of every produced `Signal`, or in other
/// words, for every invocation of `startWithSignal(_:)`, `start(_:)` and
/// their convenience shorthands.
///
/// The supplied starting side effect would be given (1) an input `Observer`
/// to emit events to the produced `Signal`; and (2) a `Lifetime` to bind
/// resources to the lifetime of the produced `Signal`.
///
/// The `Lifetime` of a produced `Signal` ends when: (1) a terminal event is
/// sent to the input `Observer`; or (2) when the produced `Signal` is
/// interrupted via the disposable yielded at the starting call.
///
/// - parameters:
/// - startHandler: The starting side effect.
public init(_ startHandler: @escaping (Signal<Value, Error>.Observer, Lifetime) -> Void) {
self.init(SignalCore {
let disposable = CompositeDisposable()
let (signal, observer) = Signal<Value, Error>.pipe(disposable: disposable)
let observerDidSetup = { startHandler(observer, Lifetime(disposable)) }
let interruptHandle = AnyDisposable(observer.sendInterrupted)
return SignalProducerCore.Instance(signal: signal,
observerDidSetup: observerDidSetup,
interruptHandle: interruptHandle)
})
}
/// Create a SignalProducer.
///
/// - parameters:
/// - core: The `SignalProducer` core.
internal init(_ core: SignalProducerCore<Value, Error>) {
self.core = core
}
/// Creates a producer for a `Signal` that will immediately send one value
/// then complete.
///
/// - parameters:
/// - value: A value that should be sent by the `Signal` in a `value`
/// event.
public init(value: Value) {
self.init(GeneratorCore { observer, _ in
observer.send(value: value)
observer.sendCompleted()
})
}
/// Creates a producer for a `Signal` that immediately sends one value, then
/// completes.
///
/// This initializer differs from `init(value:)` in that its sole `value`
/// event is constructed lazily by invoking the supplied `action` when
/// the `SignalProducer` is started.
///
/// - parameters:
/// - action: A action that yields a value to be sent by the `Signal` as
/// a `value` event.
public init(_ action: @escaping () -> Value) {
self.init(GeneratorCore { observer, _ in
observer.send(value: action())
observer.sendCompleted()
})
}
/// Create a `SignalProducer` that will attempt the given operation once for
/// each invocation of `start()`.
///
/// Upon success, the started signal will send the resulting value then
/// complete. Upon failure, the started signal will fail with the error that
/// occurred.
///
/// - parameters:
/// - action: A closure that returns instance of `Result`.
public init(_ action: @escaping () -> Result<Value, Error>) {
self.init(GeneratorCore { observer, _ in
switch action() {
case let .success(value):
observer.send(value: value)
observer.sendCompleted()
case let .failure(error):
observer.send(error: error)
}
})
}
/// Creates a producer for a `Signal` that will immediately fail with the
/// given error.
///
/// - parameters:
/// - error: An error that should be sent by the `Signal` in a `failed`
/// event.
public init(error: Error) {
self.init(GeneratorCore { observer, _ in observer.send(error: error) })
}
/// Creates a producer for a Signal that will immediately send one value
/// then complete, or immediately fail, depending on the given Result.
///
/// - parameters:
/// - result: A `Result` instance that will send either `value` event if
/// `result` is `success`ful or `failed` event if `result` is a
/// `failure`.
public init(result: Result<Value, Error>) {
switch result {
case let .success(value):
self.init(value: value)
case let .failure(error):
self.init(error: error)
}
}
/// Creates a producer for a Signal that will immediately send the values
/// from the given sequence, then complete.
///
/// - parameters:
/// - values: A sequence of values that a `Signal` will send as separate
/// `value` events and then complete.
public init<S: Sequence>(_ values: S) where S.Iterator.Element == Value {
self.init(GeneratorCore(isDisposable: true) { observer, disposable in
for value in values {
observer.send(value: value)
if disposable.isDisposed {
break
}
}
observer.sendCompleted()
})
}
/// Creates a producer for a Signal that will immediately send the values
/// from the given sequence, then complete.
///
/// - parameters:
/// - first: First value for the `Signal` to send.
/// - second: Second value for the `Signal` to send.
/// - tail: Rest of the values to be sent by the `Signal`.
public init(values first: Value, _ second: Value, _ tail: Value...) {
self.init([ first, second ] + tail)
}
/// A producer for a Signal that immediately completes without sending any values.
public static var empty: SignalProducer {
return SignalProducer(GeneratorCore { observer, _ in observer.sendCompleted() })
}
/// A producer for a Signal that immediately interrupts when started, without
/// sending any values.
internal static var interrupted: SignalProducer {
return SignalProducer(GeneratorCore { observer, _ in observer.sendInterrupted() })
}
/// A producer for a Signal that never sends any events to its observers.
public static var never: SignalProducer {
return self.init { observer, lifetime in
lifetime.observeEnded { _ = observer }
}
}
/// Create a `Signal` from `self`, pass it into the given closure, and start the
/// associated work on the produced `Signal` as the closure returns.
///
/// - parameters:
/// - setup: A closure to be invoked before the work associated with the produced
/// `Signal` commences. Both the produced `Signal` and an interrupt handle
/// of the signal would be passed to the closure.
/// - returns: The return value of the given setup closure.
@discardableResult
public func startWithSignal<Result>(_ setup: (_ signal: Signal<Value, Error>, _ interruptHandle: Disposable) -> Result) -> Result {
let instance = core.makeInstance()
let result = setup(instance.signal, instance.interruptHandle)
if !instance.interruptHandle.isDisposed {
instance.observerDidSetup()
}
return result
}
}
/// `SignalProducerCore` is the actual implementation of a `SignalProducer`.
///
/// While `SignalProducerCore` still requires all subclasses to be able to produce
/// instances of `Signal`s, the abstraction enables room of optimization for common
/// compositional and single-observer use cases.
internal class SignalProducerCore<Value, Error: Swift.Error> {
/// `Instance` represents an instance of `Signal` created from a
/// `SignalProducer`. In addition to the `Signal` itself, it includes also the
/// starting side effect and an interrupt handle for this particular instance.
///
/// It is the responsibility of the `Instance` consumer to ensure the
/// starting side effect is invoked exactly once, and is invoked after observations
/// has properly setup.
struct Instance {
let signal: Signal<Value, Error>
let observerDidSetup: () -> Void
let interruptHandle: Disposable
}
func makeInstance() -> Instance {
fatalError()
}
/// Start the producer with an observer created by the given generator.
///
/// The created observer **must** manaully dispose of the given upstream interrupt
/// handle iff it performs any event transformation that might result in a terminal
/// event.
///
/// - parameters:
/// - generator: The closure to generate an observer.
///
/// - returns: A disposable to interrupt the started producer instance.
@discardableResult
func start(_ generator: (_ upstreamInterruptHandle: Disposable) -> Signal<Value, Error>.Observer) -> Disposable {
fatalError()
}
/// Perform an action upon every event from `self`. The action may generate zero or
/// more events.
///
/// - precondition: The action must be synchronous.
///
/// - parameters:
/// - transform: A closure that creates the said action from the given event
/// closure.
///
/// - returns: A producer that forwards events yielded by the action.
internal func flatMapEvent<U, E>(_ transform: @escaping Signal<Value, Error>.Event.Transformation<U, E>) -> SignalProducer<U, E> {
return SignalProducer<U, E>(TransformerCore(source: self, transform: transform))
}
}
private final class SignalCore<Value, Error: Swift.Error>: SignalProducerCore<Value, Error> {
private let _make: () -> Instance
init(_ action: @escaping () -> Instance) {
self._make = action
}
@discardableResult
override func start(_ generator: (Disposable) -> Signal<Value, Error>.Observer) -> Disposable {
let instance = makeInstance()
instance.signal.observe(generator(instance.interruptHandle))
instance.observerDidSetup()
return instance.interruptHandle
}
override func makeInstance() -> Instance {
return _make()
}
}
/// `TransformerCore` composes event transforms, and is intended to back synchronous
/// `SignalProducer` operators in general via the core-level operator `Core.flatMapEvent`.
///
/// It takes advantage of the deferred, single-observer nature of SignalProducer. For
/// example, when we do:
///
/// ```
/// upstream.map(transform).filterMap(filteringTransform).start()
/// ```
///
/// It is contractually guaranteed that these operators would always end up producing a
/// chain of streams, each with a _single and persistent_ observer to its upstream. The
/// multicasting & detaching capabilities of Signal is useless in these scenarios.
///
/// So TransformerCore builds on top of this very fact, and composes directly at the
/// level of event transforms, without any `Signal` in between.
///
/// - note: This core does not use `Signal` unless it is requested via `makeInstance()`.
private final class TransformerCore<Value, Error: Swift.Error, SourceValue, SourceError: Swift.Error>: SignalProducerCore<Value, Error> {
private let source: SignalProducerCore<SourceValue, SourceError>
private let transform: Signal<SourceValue, SourceError>.Event.Transformation<Value, Error>
init(source: SignalProducerCore<SourceValue, SourceError>, transform: @escaping Signal<SourceValue, SourceError>.Event.Transformation<Value, Error>) {
self.source = source
self.transform = transform
}
@discardableResult
internal override func start(_ generator: (Disposable) -> Signal<Value, Error>.Observer) -> Disposable {
// Collect all resources related to this transformed producer instance.
let disposables = CompositeDisposable()
source.start { upstreamInterrupter in
// Backpropagate the terminal event, if any, to the upstream.
disposables += upstreamInterrupter
var hasDeliveredTerminalEvent = false
// Generate the output sink that receives transformed output.
let output = generator(disposables)
// Wrap the output sink to enforce the "no event beyond the terminal
// event" contract, and the disposal upon termination.
let wrappedOutput: Signal<Value, Error>.Observer.Action = { event in
if !hasDeliveredTerminalEvent {
output.send(event)
if event.isTerminating {
// Mark that a terminal event has already been
// delivered.
hasDeliveredTerminalEvent = true
// Disposed of all associated resources, and notify
// the upstream too.
disposables.dispose()
}
}
}
// Create an input sink whose events would go through the given
// event transformation, and have the resulting events propagated
// to the output sink above.
let input = transform(wrappedOutput, Lifetime(disposables))
// Return the input sink to the source producer core.
return Signal<SourceValue, SourceError>.Observer(input)
}
// Manual interruption disposes of `disposables`, which in turn notifies
// the event transformation side effects, and the upstream instance.
return disposables
}
internal override func flatMapEvent<U, E>(_ transform: @escaping Signal<Value, Error>.Event.Transformation<U, E>) -> SignalProducer<U, E> {
return SignalProducer<U, E>(TransformerCore<U, E, SourceValue, SourceError>(source: source) { [innerTransform = self.transform] action, lifetime in
return innerTransform(transform(action, lifetime), lifetime)
})
}
internal override func makeInstance() -> Instance {
let disposable = SerialDisposable()
let (signal, observer) = Signal<Value, Error>.pipe(disposable: disposable)
func observerDidSetup() {
start { interrupter in
disposable.inner = interrupter
return observer
}
}
return Instance(signal: signal,
observerDidSetup: observerDidSetup,
interruptHandle: disposable)
}
}
/// `GeneratorCore` wraps a generator closure that would be invoked upon a produced
/// `Signal` when started. The generator closure is passed only the input observer and the
/// cancel disposable.
///
/// It is intended for constant `SignalProducers`s that synchronously emits all events
/// without escaping the `Observer`.
///
/// - note: This core does not use `Signal` unless it is requested via `makeInstance()`.
private final class GeneratorCore<Value, Error: Swift.Error>: SignalProducerCore<Value, Error> {
private let isDisposable: Bool
private let generator: (Signal<Value, Error>.Observer, Disposable) -> Void
init(isDisposable: Bool = false, _ generator: @escaping (Signal<Value, Error>.Observer, Disposable) -> Void) {
self.isDisposable = isDisposable
self.generator = generator
}
@discardableResult
internal override func start(_ observerGenerator: (Disposable) -> Signal<Value, Error>.Observer) -> Disposable {
// Object allocation is a considerable overhead. So unless the core is configured
// to be disposable, we would reuse the already-disposed, shared `NopDisposable`.
let d: Disposable = isDisposable ? _SimpleDisposable() : NopDisposable.shared
generator(observerGenerator(d), d)
return d
}
internal override func makeInstance() -> Instance {
let (signal, observer) = Signal<Value, Error>.pipe()
let d = AnyDisposable(observer.sendInterrupted)
return Instance(signal: signal,
observerDidSetup: { self.generator(observer, d) },
interruptHandle: d)
}
}
extension SignalProducer where Error == Never {
/// Creates a producer for a `Signal` that will immediately send one value
/// then complete.
///
/// - parameters:
/// - value: A value that should be sent by the `Signal` in a `value`
/// event.
public init(value: Value) {
self.init(GeneratorCore { observer, _ in
observer.send(value: value)
observer.sendCompleted()
})
}
/// Creates a producer for a Signal that will immediately send the values
/// from the given sequence, then complete.
///
/// - parameters:
/// - values: A sequence of values that a `Signal` will send as separate
/// `value` events and then complete.
public init<S: Sequence>(_ values: S) where S.Iterator.Element == Value {
self.init(GeneratorCore(isDisposable: true) { observer, disposable in
for value in values {
observer.send(value: value)
if disposable.isDisposed {
break
}
}
observer.sendCompleted()
})
}
/// Creates a producer for a Signal that will immediately send the values
/// from the given sequence, then complete.
///
/// - parameters:
/// - first: First value for the `Signal` to send.
/// - second: Second value for the `Signal` to send.
/// - tail: Rest of the values to be sent by the `Signal`.
public init(values first: Value, _ second: Value, _ tail: Value...) {
self.init([ first, second ] + tail)
}
}
extension SignalProducer where Error == Swift.Error {
/// Create a `SignalProducer` that will attempt the given failable operation once for
/// each invocation of `start()`.
///
/// Upon success, the started producer will send the resulting value then
/// complete. Upon failure, the started signal will fail with the error that
/// occurred.
///
/// - parameters:
/// - operation: A failable closure.
public init(_ action: @escaping () throws -> Value) {
self.init {
return Result {
return try action()
}
}
}
}
/// Represents reactive primitives that can be represented by `SignalProducer`.
public protocol SignalProducerConvertible {
/// The type of values being sent by `self`.
associatedtype Value
/// The type of error that can occur on `self`.
associatedtype Error: Swift.Error
/// The `SignalProducer` representation of `self`.
var producer: SignalProducer<Value, Error> { get }
}
/// A protocol for constraining associated types to `SignalProducer`.
public protocol SignalProducerProtocol {
/// The type of values being sent by `self`.
associatedtype Value
/// The type of error that can occur on `self`.
associatedtype Error: Swift.Error
/// The materialized `self`.
var producer: SignalProducer<Value, Error> { get }
}
extension SignalProducer: SignalProducerConvertible, SignalProducerProtocol {
public var producer: SignalProducer {
return self
}
}
extension SignalProducer {
/// Create a `Signal` from `self`, and observe it with the given observer.
///
/// - parameters:
/// - observer: An observer to attach to the produced `Signal`.
///
/// - returns: A disposable to interrupt the produced `Signal`.
@discardableResult
public func start(_ observer: Signal<Value, Error>.Observer = .init()) -> Disposable {
return core.start { _ in observer }
}
/// Create a `Signal` from `self`, and observe the `Signal` for all events
/// being emitted.
///
/// - parameters:
/// - action: A closure to be invoked with every event from `self`.
///
/// - returns: A disposable to interrupt the produced `Signal`.
@discardableResult
public func start(_ action: @escaping Signal<Value, Error>.Observer.Action) -> Disposable {
return start(Signal.Observer(action))
}
/// Create a `Signal` from `self`, and observe the `Signal` for all values being
/// emitted, and if any, its failure.
///
/// - parameters:
/// - action: A closure to be invoked with values from `self`, or the propagated
/// error should any `failed` event is emitted.
///
/// - returns: A disposable to interrupt the produced `Signal`.
@discardableResult
public func startWithResult(_ action: @escaping (Result<Value, Error>) -> Void) -> Disposable {
return start(
Signal.Observer(
value: { action(.success($0)) },
failed: { action(.failure($0)) }
)
)
}
/// Create a `Signal` from `self`, and observe its completion.
///
/// - parameters:
/// - action: A closure to be invoked when a `completed` event is emitted.
///
/// - returns: A disposable to interrupt the produced `Signal`.
@discardableResult
public func startWithCompleted(_ action: @escaping () -> Void) -> Disposable {
return start(Signal.Observer(completed: action))
}
/// Create a `Signal` from `self`, and observe its failure.
///
/// - parameters:
/// - action: A closure to be invoked with the propagated error, should any
/// `failed` event is emitted.
///
/// - returns: A disposable to interrupt the produced `Signal`.
@discardableResult
public func startWithFailed(_ action: @escaping (Error) -> Void) -> Disposable {
return start(Signal.Observer(failed: action))
}
/// Create a `Signal` from `self`, and observe its interruption.
///
/// - parameters:
/// - action: A closure to be invoked when an `interrupted` event is emitted.
///
/// - returns: A disposable to interrupt the produced `Signal`.
@discardableResult
public func startWithInterrupted(_ action: @escaping () -> Void) -> Disposable {
return start(Signal.Observer(interrupted: action))
}
/// Creates a `Signal` from the producer.
///
/// This is equivalent to `SignalProducer.startWithSignal`, but it has
/// the downside that any values emitted synchronously upon starting will
/// be missed by the observer, because it won't be able to subscribe in time.
/// That's why we don't want this method to be exposed as `public`,
/// but it's useful internally.
internal func startAndRetrieveSignal() -> Signal<Value, Error> {
var result: Signal<Value, Error>!
self.startWithSignal { signal, _ in
result = signal
}
return result
}
/// Create a `Signal` from `self` in the manner described by `startWithSignal`, and
/// put the interrupt handle into the given `CompositeDisposable`.
///
/// - parameters:
/// - lifetime: The `Lifetime` the interrupt handle to be added to.
/// - setup: A closure that accepts the produced `Signal`.
fileprivate func startWithSignal(during lifetime: Lifetime, setup: (Signal<Value, Error>) -> Void) {
startWithSignal { signal, interruptHandle in
lifetime += interruptHandle
setup(signal)
}
}
}
extension SignalProducer where Error == Never {
/// Create a `Signal` from `self`, and observe the `Signal` for all values being
/// emitted.
///
/// - parameters:
/// - action: A closure to be invoked with values from the produced `Signal`.
///
/// - returns: A disposable to interrupt the produced `Signal`.
@discardableResult
public func startWithValues(_ action: @escaping (Value) -> Void) -> Disposable {
return start(Signal.Observer(value: action))
}
}
extension SignalProducer {
/// Lift an unary Signal operator to operate upon SignalProducers instead.
///
/// In other words, this will create a new `SignalProducer` which will apply
/// the given `Signal` operator to _every_ created `Signal`, just as if the
/// operator had been applied to each `Signal` yielded from `start()`.
///
/// - parameters:
/// - transform: An unary operator to lift.
///
/// - returns: A signal producer that applies signal's operator to every
/// created signal.
public func lift<U, F>(_ transform: @escaping (Signal<Value, Error>) -> Signal<U, F>) -> SignalProducer<U, F> {
return SignalProducer<U, F> { observer, lifetime in
self.startWithSignal { signal, interrupter in
lifetime += interrupter
transform(signal).observe(observer)
}
}
}
/// Lift a binary Signal operator to operate upon SignalProducers.
///
/// The left producer would first be started. When both producers are synchronous this
/// order can be important depending on the operator to generate correct results.
///
/// - returns: A factory that creates a SignalProducer with the given operator
/// applied. `self` would be the LHS, and the factory input would
/// be the RHS.
fileprivate func liftLeft<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (SignalProducer<U, F>) -> SignalProducer<V, G> {
return { right in
return SignalProducer<V, G> { observer, lifetime in
right.startWithSignal { rightSignal, rightInterrupter in
lifetime += rightInterrupter
self.startWithSignal { leftSignal, leftInterrupter in
lifetime += leftInterrupter
transform(leftSignal)(rightSignal).observe(observer)
}
}
}
}
}
/// Lift a binary Signal operator to operate upon SignalProducers.
///
/// The right producer would first be started. When both producers are synchronous
/// this order can be important depending on the operator to generate correct results.
///
/// - returns: A factory that creates a SignalProducer with the given operator
/// applied. `self` would be the LHS, and the factory input would
/// be the RHS.
fileprivate func liftRight<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (SignalProducer<U, F>) -> SignalProducer<V, G> {
return { right in
return SignalProducer<V, G> { observer, lifetime in
self.startWithSignal { leftSignal, leftInterrupter in
lifetime += leftInterrupter
right.startWithSignal { rightSignal, rightInterrupter in
lifetime += rightInterrupter
transform(leftSignal)(rightSignal).observe(observer)
}
}
}
}
}
/// Lift a binary Signal operator to operate upon SignalProducers instead.
///
/// In other words, this will create a new `SignalProducer` which will apply
/// the given `Signal` operator to _every_ `Signal` created from the two
/// producers, just as if the operator had been applied to each `Signal`
/// yielded from `start()`.
///
/// - note: starting the returned producer will start the receiver of the
/// operator, which may not be adviseable for some operators.
///
/// - parameters:
/// - transform: A binary operator to lift.
///
/// - returns: A binary operator that operates on two signal producers.
public func lift<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (SignalProducer<U, F>) -> SignalProducer<V, G> {
return liftRight(transform)
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>) -> Void) {
b.startWithSignal(during: lifetime) { b in
a.startWithSignal(during: lifetime) { setup($0, b) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>) -> Void) {
c.startWithSignal(during: lifetime) { c in
flattenStart(lifetime, a, b) { setup($0, $1, c) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, D, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>, Signal<D, Error>) -> Void) {
d.startWithSignal(during: lifetime) { d in
flattenStart(lifetime, a, b, c) { setup($0, $1, $2, d) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, D, E, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>, Signal<D, Error>, Signal<E, Error>) -> Void) {
e.startWithSignal(during: lifetime) { e in
flattenStart(lifetime, a, b, c, d) { setup($0, $1, $2, $3, e) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, D, E, F, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>, Signal<D, Error>, Signal<E, Error>, Signal<F, Error>) -> Void) {
f.startWithSignal(during: lifetime) { f in
flattenStart(lifetime, a, b, c, d, e) { setup($0, $1, $2, $3, $4, f) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, D, E, F, G, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>, Signal<D, Error>, Signal<E, Error>, Signal<F, Error>, Signal<G, Error>) -> Void) {
g.startWithSignal(during: lifetime) { g in
flattenStart(lifetime, a, b, c, d, e, f) { setup($0, $1, $2, $3, $4, $5, g) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, D, E, F, G, H, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>, Signal<D, Error>, Signal<E, Error>, Signal<F, Error>, Signal<G, Error>, Signal<H, Error>) -> Void) {
h.startWithSignal(during: lifetime) { h in
flattenStart(lifetime, a, b, c, d, e, f, g) { setup($0, $1, $2, $3, $4, $5, $6, h) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, D, E, F, G, H, I, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>, Signal<D, Error>, Signal<E, Error>, Signal<F, Error>, Signal<G, Error>, Signal<H, Error>, Signal<I, Error>) -> Void) {
i.startWithSignal(during: lifetime) { i in
flattenStart(lifetime, a, b, c, d, e, f, g, h) { setup($0, $1, $2, $3, $4, $5, $6, $7, i) }
}
}
/// Start the producers in the argument order.
///
/// - parameters:
/// - disposable: The `CompositeDisposable` to collect the interrupt handles of all
/// produced `Signal`s.
/// - setup: The closure to accept all produced `Signal`s at once.
private func flattenStart<A, B, C, D, E, F, G, H, I, J, Error>(_ lifetime: Lifetime, _ a: SignalProducer<A, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>, _ j: SignalProducer<J, Error>, _ setup: (Signal<A, Error>, Signal<B, Error>, Signal<C, Error>, Signal<D, Error>, Signal<E, Error>, Signal<F, Error>, Signal<G, Error>, Signal<H, Error>, Signal<I, Error>, Signal<J, Error>) -> Void) {
j.startWithSignal(during: lifetime) { j in
flattenStart(lifetime, a, b, c, d, e, f, g, h, i) { setup($0, $1, $2, $3, $4, $5, $6, $7, $8, j) }
}
}
extension SignalProducer {
/// Map each value in the producer to a new value.
///
/// - parameters:
/// - transform: A closure that accepts a value and returns a different
/// value.
///
/// - returns: A signal producer that, when started, will send a mapped
/// value of `self.`
public func map<U>(_ transform: @escaping (Value) -> U) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.map(transform))
}
/// Map each value in the producer to a new constant value.
///
/// - parameters:
/// - value: A new value.
///
/// - returns: A signal producer that, when started, will send a mapped
/// value of `self`.
public func map<U>(value: U) -> SignalProducer<U, Error> {
return lift { $0.map(value: value) }
}
/// Map each value in the producer to a new value by applying a key path.
///
/// - parameters:
/// - keyPath: A key path relative to the producer's `Value` type.
///
/// - returns: A producer that will send new values.
public func map<U>(_ keyPath: KeyPath<Value, U>) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.filterMap { $0[keyPath: keyPath] })
}
/// Map errors in the producer to a new error.
///
/// - parameters:
/// - transform: A closure that accepts an error object and returns a
/// different error.
///
/// - returns: A producer that emits errors of new type.
public func mapError<F>(_ transform: @escaping (Error) -> F) -> SignalProducer<Value, F> {
return core.flatMapEvent(Signal.Event.mapError(transform))
}
/// Maps each value in the producer to a new value, lazily evaluating the
/// supplied transformation on the specified scheduler.
///
/// - important: Unlike `map`, there is not a 1-1 mapping between incoming
/// values, and values sent on the returned producer. If
/// `scheduler` has not yet scheduled `transform` for
/// execution, then each new value will replace the last one as
/// the parameter to `transform` once it is finally executed.
///
/// - parameters:
/// - transform: The closure used to obtain the returned value from this
/// producer's underlying value.
///
/// - returns: A producer that, when started, sends values obtained using
/// `transform` as this producer sends values.
public func lazyMap<U>(on scheduler: Scheduler, transform: @escaping (Value) -> U) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.lazyMap(on: scheduler, transform: transform))
}
/// Preserve only values which pass the given closure.
///
/// - parameters:
/// - isIncluded: A closure to determine whether a value from `self` should be
/// included in the produced `Signal`.
///
/// - returns: A producer that, when started, forwards the values passing the given
/// closure.
public func filter(_ isIncluded: @escaping (Value) -> Bool) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.filter(isIncluded))
}
/// Applies `transform` to values from the producer and forwards values with non `nil` results unwrapped.
/// - parameters:
/// - transform: A closure that accepts a value from the `value` event and
/// returns a new optional value.
///
/// - returns: A producer that will send new values, that are non `nil` after the transformation.
public func filterMap<U>(_ transform: @escaping (Value) -> U?) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.filterMap(transform))
}
/// Yield the first `count` values from the input producer.
///
/// - precondition: `count` must be non-negative number.
///
/// - parameters:
/// - count: A number of values to take from the signal.
///
/// - returns: A producer that, when started, will yield the first `count`
/// values from `self`.
public func take(first count: Int) -> SignalProducer<Value, Error> {
guard count >= 1 else { return .interrupted }
return core.flatMapEvent(Signal.Event.take(first: count))
}
/// Yield an array of values when `self` completes.
///
/// - note: When `self` completes without collecting any value, it will send
/// an empty array of values.
///
/// - returns: A producer that, when started, will yield an array of values
/// when `self` completes.
public func collect() -> SignalProducer<[Value], Error> {
return core.flatMapEvent(Signal.Event.collect)
}
/// Yield an array of values until it reaches a certain count.
///
/// - precondition: `count` must be greater than zero.
///
/// - note: When the count is reached the array is sent and the signal
/// starts over yielding a new array of values.
///
/// - note: When `self` completes any remaining values will be sent, the
/// last array may not have `count` values. Alternatively, if were
/// not collected any values will sent an empty array of values.
///
/// - returns: A producer that, when started, collects at most `count`
/// values from `self`, forwards them as a single array and
/// completes.
public func collect(count: Int) -> SignalProducer<[Value], Error> {
return core.flatMapEvent(Signal.Event.collect(count: count))
}
/// Collect values from `self`, and emit them if the predicate passes.
///
/// When `self` completes any remaining values will be sent, regardless of the
/// collected values matching `shouldEmit` or not.
///
/// If `self` completes without having emitted any value, an empty array would be
/// emitted, followed by the completion of the produced `Signal`.
///
/// ````
/// let (producer, observer) = SignalProducer<Int, Never>.buffer(1)
///
/// producer
/// .collect { values in values.reduce(0, combine: +) == 8 }
/// .startWithValues { print($0) }
///
/// observer.send(value: 1)
/// observer.send(value: 3)
/// observer.send(value: 4)
/// observer.send(value: 7)
/// observer.send(value: 1)
/// observer.send(value: 5)
/// observer.send(value: 6)
/// observer.sendCompleted()
///
/// // Output:
/// // [1, 3, 4]
/// // [7, 1]
/// // [5, 6]
/// ````
///
/// - parameters:
/// - shouldEmit: A closure to determine, when every time a new value is received,
/// whether the collected values should be emitted.
///
/// - returns: A producer of arrays of values, as instructed by the `shouldEmit`
/// closure.
public func collect(_ shouldEmit: @escaping (_ values: [Value]) -> Bool) -> SignalProducer<[Value], Error> {
return core.flatMapEvent(Signal.Event.collect(shouldEmit))
}
/// Collect values from `self`, and emit them if the predicate passes.
///
/// When `self` completes any remaining values will be sent, regardless of the
/// collected values matching `shouldEmit` or not.
///
/// If `self` completes without having emitted any value, an empty array would be
/// emitted, followed by the completion of the produced `Signal`.
///
/// ````
/// let (producer, observer) = SignalProducer<Int, Never>.buffer(1)
///
/// producer
/// .collect { values, value in value == 7 }
/// .startWithValues { print($0) }
///
/// observer.send(value: 1)
/// observer.send(value: 1)
/// observer.send(value: 7)
/// observer.send(value: 7)
/// observer.send(value: 5)
/// observer.send(value: 6)
/// observer.sendCompleted()
///
/// // Output:
/// // [1, 1]
/// // [7]
/// // [7, 5, 6]
/// ````
///
/// - parameters:
/// - shouldEmit: A closure to determine, when every time a new value is received,
/// whether the collected values should be emitted. The new value
/// is **not** included in the collected values, and is included when
/// the next value is received.
///
/// - returns: A producer of arrays of values, as instructed by the `shouldEmit`
/// closure.
public func collect(_ shouldEmit: @escaping (_ collected: [Value], _ latest: Value) -> Bool) -> SignalProducer<[Value], Error> {
return core.flatMapEvent(Signal.Event.collect(shouldEmit))
}
/// Forward the latest values on `scheduler` every `interval`.
///
/// - note: If `self` terminates while values are being accumulated,
/// the behaviour will be determined by `discardWhenCompleted`.
/// If `true`, the values will be discarded and the returned producer
/// will terminate immediately.
/// If `false`, that values will be delivered at the next interval.
///
/// - parameters:
/// - interval: A repetition interval.
/// - scheduler: A scheduler to send values on.
/// - skipEmpty: Whether empty arrays should be sent if no values were
/// accumulated during the interval.
/// - discardWhenCompleted: A boolean to indicate if the latest unsent
/// values should be discarded on completion.
///
/// - returns: A producer that sends all values that are sent from `self`
/// at `interval` seconds apart.
public func collect(every interval: DispatchTimeInterval, on scheduler: DateScheduler, skipEmpty: Bool = false, discardWhenCompleted: Bool = true) -> SignalProducer<[Value], Error> {
return core.flatMapEvent(Signal.Event.collect(every: interval, on: scheduler, skipEmpty: skipEmpty, discardWhenCompleted: discardWhenCompleted))
}
/// Forward all events onto the given scheduler, instead of whichever
/// scheduler they originally arrived upon.
///
/// - parameters:
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A producer that, when started, will yield `self` values on
/// provided scheduler.
public func observe(on scheduler: Scheduler) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.observe(on: scheduler))
}
/// Combine the latest value of the receiver with the latest value from the
/// given producer.
///
/// - note: The returned producer will not send a value until both inputs
/// have sent at least one value each.
///
/// - note: If either producer is interrupted, the returned producer will
/// also be interrupted.
///
/// - note: The returned producer will not complete until both inputs
/// complete.
///
/// - parameters:
/// - other: A producer to combine `self`'s value with.
///
/// - returns: A producer that, when started, will yield a tuple containing
/// values of `self` and given producer.
public func combineLatest<U>(with other: SignalProducer<U, Error>) -> SignalProducer<(Value, U), Error> {
return SignalProducer.combineLatest(self, other)
}
/// Combine the latest value of the receiver with the latest value from the
/// given producer.
///
/// - note: The returned producer will not send a value until both inputs
/// have sent at least one value each.
///
/// - note: If either producer is interrupted, the returned producer will
/// also be interrupted.
///
/// - note: The returned producer will not complete until both inputs
/// complete.
///
/// - parameters:
/// - other: A producer to combine `self`'s value with.
///
/// - returns: A producer that, when started, will yield a tuple containing
/// values of `self` and given producer.
public func combineLatest<Other: SignalProducerConvertible>(with other: Other) -> SignalProducer<(Value, Other.Value), Error> where Other.Error == Error {
return combineLatest(with: other.producer)
}
/// Merge the given producer into a single `SignalProducer` that will emit all
/// values from both of them, and complete when all of them have completed.
///
/// - parameters:
/// - other: A producer to merge `self`'s value with.
///
/// - returns: A producer that sends all values of `self` and given producer.
public func merge(with other: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return SignalProducer.merge(self, other)
}
/// Merge the given producer into a single `SignalProducer` that will emit all
/// values from both of them, and complete when all of them have completed.
///
/// - parameters:
/// - other: A producer to merge `self`'s value with.
///
/// - returns: A producer that sends all values of `self` and given producer.
public func merge<Other: SignalProducerConvertible>(with other: Other) -> SignalProducer<Value, Error> where Other.Value == Value, Other.Error == Error {
return merge(with: other.producer)
}
/// Delay `value` and `completed` events by the given interval, forwarding
/// them on the given scheduler.
///
/// - note: `failed` and `interrupted` events are always scheduled
/// immediately.
///
/// - parameters:
/// - interval: Interval to delay `value` and `completed` events by.
/// - scheduler: A scheduler to deliver delayed events on.
///
/// - returns: A producer that, when started, will delay `value` and
/// `completed` events and will yield them on given scheduler.
public func delay(_ interval: TimeInterval, on scheduler: DateScheduler) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.delay(interval, on: scheduler))
}
/// Skip the first `count` values, then forward everything afterward.
///
/// - parameters:
/// - count: A number of values to skip.
///
/// - returns: A producer that, when started, will skip the first `count`
/// values, then forward everything afterward.
public func skip(first count: Int) -> SignalProducer<Value, Error> {
guard count != 0 else { return self }
return core.flatMapEvent(Signal.Event.skip(first: count))
}
/// Treats all Events from the input producer as plain values, allowing them
/// to be manipulated just like any other value.
///
/// In other words, this brings Events “into the monad.”
///
/// - note: When a Completed or Failed event is received, the resulting
/// producer will send the Event itself and then complete. When an
/// `interrupted` event is received, the resulting producer will
/// send the `Event` itself and then interrupt.
///
/// - returns: A producer that sends events as its values.
public func materialize() -> SignalProducer<ProducedSignal.Event, Never> {
return core.flatMapEvent(Signal.Event.materialize)
}
/// Treats all Results from the input producer as plain values, allowing them
/// to be manipulated just like any other value.
///
/// In other words, this brings Results “into the monad.”
///
/// - note: When a Failed event is received, the resulting producer will
/// send the `Result.failure` itself and then complete.
///
/// - returns: A producer that sends results as its values.
public func materializeResults() -> SignalProducer<Result<Value, Error>, Never> {
return core.flatMapEvent(Signal.Event.materializeResults)
}
/// Forward the latest value from `self` with the value from `sampler` as a
/// tuple, only when `sampler` sends a `value` event.
///
/// - note: If `sampler` fires before a value has been observed on `self`,
/// nothing happens.
///
/// - parameters:
/// - sampler: A producer that will trigger the delivery of `value` event
/// from `self`.
///
/// - returns: A producer that will send values from `self` and `sampler`,
/// sampled (possibly multiple times) by `sampler`, then complete
/// once both input producers have completed, or interrupt if
/// either input producer is interrupted.
public func sample<U>(with sampler: SignalProducer<U, Never>) -> SignalProducer<(Value, U), Error> {
return liftLeft(Signal.sample(with:))(sampler)
}
/// Forward the latest value from `self` with the value from `sampler` as a
/// tuple, only when `sampler` sends a `value` event.
///
/// - note: If `sampler` fires before a value has been observed on `self`,
/// nothing happens.
///
/// - parameters:
/// - sampler: A producer that will trigger the delivery of `value` event
/// from `self`.
///
/// - returns: A producer that will send values from `self` and `sampler`,
/// sampled (possibly multiple times) by `sampler`, then complete
/// once both input producers have completed, or interrupt if
/// either input producer is interrupted.
public func sample<Sampler: SignalProducerConvertible>(with sampler: Sampler) -> SignalProducer<(Value, Sampler.Value), Error> where Sampler.Error == Never {
return sample(with: sampler.producer)
}
/// Forward the latest value from `self` whenever `sampler` sends a `value`
/// event.
///
/// - note: If `sampler` fires before a value has been observed on `self`,
/// nothing happens.
///
/// - parameters:
/// - sampler: A producer that will trigger the delivery of `value` event
/// from `self`.
///
/// - returns: A producer that, when started, will send values from `self`,
/// sampled (possibly multiple times) by `sampler`, then complete
/// once both input producers have completed, or interrupt if
/// either input producer is interrupted.
public func sample(on sampler: SignalProducer<(), Never>) -> SignalProducer<Value, Error> {
return liftLeft(Signal.sample(on:))(sampler)
}
/// Forward the latest value from `self` whenever `sampler` sends a `value`
/// event.
///
/// - note: If `sampler` fires before a value has been observed on `self`,
/// nothing happens.
///
/// - parameters:
/// - sampler: A producer that will trigger the delivery of `value` event
/// from `self`.
///
/// - returns: A producer that, when started, will send values from `self`,
/// sampled (possibly multiple times) by `sampler`, then complete
/// once both input producers have completed, or interrupt if
/// either input producer is interrupted.
public func sample<Sampler: SignalProducerConvertible>(on sampler: Sampler) -> SignalProducer<Value, Error> where Sampler.Value == (), Sampler.Error == Never {
return sample(on: sampler.producer)
}
/// Forward the latest value from `samplee` with the value from `self` as a
/// tuple, only when `self` sends a `value` event.
/// This is like a flipped version of `sample(with:)`, but `samplee`'s
/// terminal events are completely ignored.
///
/// - note: If `self` fires before a value has been observed on `samplee`,
/// nothing happens.
///
/// - parameters:
/// - samplee: A producer whose latest value is sampled by `self`.
///
/// - returns: A producer that will send values from `self` and `samplee`,
/// sampled (possibly multiple times) by `self`, then terminate
/// once `self` has terminated. **`samplee`'s terminated events
/// are ignored**.
public func withLatest<U>(from samplee: SignalProducer<U, Never>) -> SignalProducer<(Value, U), Error> {
return liftRight(Signal.withLatest)(samplee.producer)
}
/// Forward the latest value from `samplee` with the value from `self` as a
/// tuple, only when `self` sends a `value` event.
/// This is like a flipped version of `sample(with:)`, but `samplee`'s
/// terminal events are completely ignored.
///
/// - note: If `self` fires before a value has been observed on `samplee`,
/// nothing happens.
///
/// - parameters:
/// - samplee: A producer whose latest value is sampled by `self`.
///
/// - returns: A producer that will send values from `self` and `samplee`,
/// sampled (possibly multiple times) by `self`, then terminate
/// once `self` has terminated. **`samplee`'s terminated events
/// are ignored**.
public func withLatest<Samplee: SignalProducerConvertible>(from samplee: Samplee) -> SignalProducer<(Value, Samplee.Value), Error> where Samplee.Error == Never {
return withLatest(from: samplee.producer)
}
/// Forwards events from `self` until `lifetime` ends, at which point the
/// returned producer will complete.
///
/// - parameters:
/// - lifetime: A lifetime whose `ended` signal will cause the returned
/// producer to complete.
///
/// - returns: A producer that will deliver events until `lifetime` ends.
public func take(during lifetime: Lifetime) -> SignalProducer<Value, Error> {
return lift { $0.take(during: lifetime) }
}
/// Forward events from `self` until `trigger` sends a `value` or `completed`
/// event, at which point the returned producer will complete.
///
/// - parameters:
/// - trigger: A producer whose `value` or `completed` events will stop the
/// delivery of `value` events from `self`.
///
/// - returns: A producer that will deliver events until `trigger` sends
/// `value` or `completed` events.
public func take(until trigger: SignalProducer<(), Never>) -> SignalProducer<Value, Error> {
return liftRight(Signal.take(until:))(trigger)
}
/// Forward events from `self` until `trigger` sends a `value` or `completed`
/// event, at which point the returned producer will complete.
///
/// - parameters:
/// - trigger: A producer whose `value` or `completed` events will stop the
/// delivery of `value` events from `self`.
///
/// - returns: A producer that will deliver events until `trigger` sends
/// `value` or `completed` events.
public func take<Trigger: SignalProducerConvertible>(until trigger: Trigger) -> SignalProducer<Value, Error> where Trigger.Value == (), Trigger.Error == Never {
return take(until: trigger.producer)
}
/// Do not forward any values from `self` until `trigger` sends a `value`
/// or `completed`, at which point the returned producer behaves exactly
/// like `producer`.
///
/// - parameters:
/// - trigger: A producer whose `value` or `completed` events will start
/// the deliver of events on `self`.
///
/// - returns: A producer that will deliver events once the `trigger` sends
/// `value` or `completed` events.
public func skip(until trigger: SignalProducer<(), Never>) -> SignalProducer<Value, Error> {
return liftRight(Signal.skip(until:))(trigger)
}
/// Do not forward any values from `self` until `trigger` sends a `value`
/// or `completed`, at which point the returned producer behaves exactly
/// like `producer`.
///
/// - parameters:
/// - trigger: A producer whose `value` or `completed` events will start
/// the deliver of events on `self`.
///
/// - returns: A producer that will deliver events once the `trigger` sends
/// `value` or `completed` events.
public func skip<Trigger: SignalProducerConvertible>(until trigger: Trigger) -> SignalProducer<Value, Error> where Trigger.Value == (), Trigger.Error == Never {
return skip(until: trigger.producer)
}
/// Forward events from `self` with history: values of the returned producer
/// are a tuples whose first member is the previous value and whose second member
/// is the current value. `initial` is supplied as the first member when `self`
/// sends its first value.
///
/// - parameters:
/// - initial: A value that will be combined with the first value sent by
/// `self`.
///
/// - returns: A producer that sends tuples that contain previous and current
/// sent values of `self`.
public func combinePrevious(_ initial: Value) -> SignalProducer<(Value, Value), Error> {
return core.flatMapEvent(Signal.Event.combinePrevious(initial: initial))
}
/// Forward events from `self` with history: values of the produced signal
/// are a tuples whose first member is the previous value and whose second member
/// is the current value.
///
/// The produced `Signal` would not emit any tuple until it has received at least two
/// values.
///
/// - returns: A producer that sends tuples that contain previous and current
/// sent values of `self`.
public func combinePrevious() -> SignalProducer<(Value, Value), Error> {
return core.flatMapEvent(Signal.Event.combinePrevious(initial: nil))
}
/// Combine all values from `self`, and forward the final result.
///
/// See `scan(_:_:)` if the resulting producer needs to forward also the partial
/// results.
///
/// - parameters:
/// - initialResult: The value to use as the initial accumulating value.
/// - nextPartialResult: A closure that combines the accumulating value and the
/// latest value from `self`. The result would be used in the
/// next call of `nextPartialResult`, or emit to the returned
/// `Signal` when `self` completes.
///
/// - returns: A producer that sends the final result as `self` completes.
public func reduce<U>(_ initialResult: U, _ nextPartialResult: @escaping (U, Value) -> U) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.reduce(initialResult, nextPartialResult))
}
/// Combine all values from `self`, and forward the final result.
///
/// See `scan(into:_:)` if the resulting producer needs to forward also the partial
/// results.
///
/// - parameters:
/// - initialResult: The value to use as the initial accumulating value.
/// - nextPartialResult: A closure that combines the accumulating value and the
/// latest value from `self`. The result would be used in the
/// next call of `nextPartialResult`, or emit to the returned
/// `Signal` when `self` completes.
///
/// - returns: A producer that sends the final value as `self` completes.
public func reduce<U>(into initialResult: U, _ nextPartialResult: @escaping (inout U, Value) -> Void) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.reduce(into: initialResult, nextPartialResult))
}
/// Combine all values from `self`, and forward the partial results and the final
/// result.
///
/// See `reduce(_:_:)` if the resulting producer needs to forward only the final
/// result.
///
/// - parameters:
/// - initialResult: The value to use as the initial accumulating value.
/// - nextPartialResult: A closure that combines the accumulating value and the
/// latest value from `self`. The result would be forwarded,
/// and would be used in the next call of `nextPartialResult`.
///
/// - returns: A producer that sends the partial results of the accumuation, and the
/// final result as `self` completes.
public func scan<U>(_ initialResult: U, _ nextPartialResult: @escaping (U, Value) -> U) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.scan(initialResult, nextPartialResult))
}
/// Combine all values from `self`, and forward the partial results and the final
/// result.
///
/// See `reduce(into:_:)` if the resulting producer needs to forward only the final
/// result.
///
/// - parameters:
/// - initialResult: The value to use as the initial accumulating value.
/// - nextPartialResult: A closure that combines the accumulating value and the
/// latest value from `self`. The result would be forwarded,
/// and would be used in the next call of `nextPartialResult`.
///
/// - returns: A producer that sends the partial results of the accumuation, and the
/// final result as `self` completes.
public func scan<U>(into initialResult: U, _ nextPartialResult: @escaping (inout U, Value) -> Void) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.scan(into: initialResult, nextPartialResult))
}
/// Forward only values from `self` that are not considered equivalent to its
/// immediately preceding value.
///
/// - note: The first value is always forwarded.
///
/// - parameters:
/// - isEquivalent: A closure to determine whether two values are equivalent.
///
/// - returns: A producer which conditionally forwards values from `self`
public func skipRepeats(_ isEquivalent: @escaping (Value, Value) -> Bool) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.skipRepeats(isEquivalent))
}
/// Do not forward any value from `self` until `shouldContinue` returns `false`, at
/// which point the returned signal starts to forward values from `self`, including
/// the one leading to the toggling.
///
/// - parameters:
/// - shouldContinue: A closure to determine whether the skipping should continue.
///
/// - returns: A producer which conditionally forwards values from `self`.
public func skip(while shouldContinue: @escaping (Value) -> Bool) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.skip(while: shouldContinue))
}
/// Forwards events from `self` until `replacement` begins sending events.
///
/// - parameters:
/// - replacement: A producer to wait to wait for values from and start
/// sending them as a replacement to `self`'s values.
///
/// - returns: A producer which passes through `value`, `failed`, and
/// `interrupted` events from `self` until `replacement` sends an
/// event, at which point the returned producer will send that
/// event and switch to passing through events from `replacement`
/// instead, regardless of whether `self` has sent events
/// already.
public func take(untilReplacement replacement: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return liftRight(Signal.take(untilReplacement:))(replacement)
}
/// Forwards events from `self` until `replacement` begins sending events.
///
/// - parameters:
/// - replacement: A producer to wait to wait for values from and start
/// sending them as a replacement to `self`'s values.
///
/// - returns: A producer which passes through `value`, `failed`, and
/// `interrupted` events from `self` until `replacement` sends an
/// event, at which point the returned producer will send that
/// event and switch to passing through events from `replacement`
/// instead, regardless of whether `self` has sent events
/// already.
public func take<Replacement: SignalProducerConvertible>(untilReplacement replacement: Replacement) -> SignalProducer<Value, Error> where Replacement.Value == Value, Replacement.Error == Error {
return take(untilReplacement: replacement.producer)
}
/// Wait until `self` completes and then forward the final `count` values
/// on the returned producer.
///
/// - parameters:
/// - count: Number of last events to send after `self` completes.
///
/// - returns: A producer that receives up to `count` values from `self`
/// after `self` completes.
public func take(last count: Int) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.take(last: count))
}
/// Forward any values from `self` until `shouldContinue` returns `false`, at which
/// point the produced `Signal` would complete.
///
/// - parameters:
/// - shouldContinue: A closure to determine whether the forwarding of values should
/// continue.
///
/// - returns: A producer which conditionally forwards values from `self`.
public func take(while shouldContinue: @escaping (Value) -> Bool) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.take(while: shouldContinue))
}
/// Zip elements of two producers into pairs. The elements of any Nth pair
/// are the Nth elements of the two input producers.
///
/// - parameters:
/// - other: A producer to zip values with.
///
/// - returns: A producer that sends tuples of `self` and `otherProducer`.
public func zip<U>(with other: SignalProducer<U, Error>) -> SignalProducer<(Value, U), Error> {
return SignalProducer.zip(self, other)
}
/// Zip elements of two producers into pairs. The elements of any Nth pair
/// are the Nth elements of the two input producers.
///
/// - parameters:
/// - other: A producer to zip values with.
///
/// - returns: A producer that sends tuples of `self` and `otherProducer`.
public func zip<Other: SignalProducerConvertible>(with other: Other) -> SignalProducer<(Value, Other.Value), Error> where Other.Error == Error {
return zip(with: other.producer)
}
/// Apply an action to every value from `self`, and forward the value if the action
/// succeeds. If the action fails with an error, the produced `Signal` would propagate
/// the failure and terminate.
///
/// - parameters:
/// - action: An action which yields a `Result`.
///
/// - returns: A producer which forwards the values from `self` until the given action
/// fails.
public func attempt(_ action: @escaping (Value) -> Result<(), Error>) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.attempt(action))
}
/// Apply a transform to every value from `self`, and forward the transformed value
/// if the action succeeds. If the action fails with an error, the produced `Signal`
/// would propagate the failure and terminate.
///
/// - parameters:
/// - action: A transform which yields a `Result` of the transformed value or the
/// error.
///
/// - returns: A producer which forwards the transformed values.
public func attemptMap<U>(_ action: @escaping (Value) -> Result<U, Error>) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.attemptMap(action))
}
/// Forward the latest value on `scheduler` after at least `interval`
/// seconds have passed since *the returned signal* last sent a value.
///
/// If `self` always sends values more frequently than `interval` seconds,
/// then the returned signal will send a value every `interval` seconds.
///
/// To measure from when `self` last sent a value, see `debounce`.
///
/// - seealso: `debounce`
///
/// - note: If multiple values are received before the interval has elapsed,
/// the latest value is the one that will be passed on.
///
/// - note: If `self` terminates while a value is being throttled, that
/// value will be discarded and the returned producer will terminate
/// immediately.
///
/// - note: If the device time changed backwards before previous date while
/// a value is being throttled, and if there is a new value sent,
/// the new value will be passed anyway.
///
/// - parameters:
/// - interval: Number of seconds to wait between sent values.
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A producer that sends values at least `interval` seconds
/// appart on a given scheduler.
public func throttle(_ interval: TimeInterval, on scheduler: DateScheduler) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.throttle(interval, on: scheduler))
}
/// Conditionally throttles values sent on the receiver whenever
/// `shouldThrottle` is true, forwarding values on the given scheduler.
///
/// - note: While `shouldThrottle` remains false, values are forwarded on the
/// given scheduler. If multiple values are received while
/// `shouldThrottle` is true, the latest value is the one that will
/// be passed on.
///
/// - note: If the input signal terminates while a value is being throttled,
/// that value will be discarded and the returned signal will
/// terminate immediately.
///
/// - note: If `shouldThrottle` completes before the receiver, and its last
/// value is `true`, the returned signal will remain in the throttled
/// state, emitting no further values until it terminates.
///
/// - parameters:
/// - shouldThrottle: A boolean property that controls whether values
/// should be throttled.
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A producer that sends values only while `shouldThrottle` is false.
public func throttle<P: PropertyProtocol>(while shouldThrottle: P, on scheduler: Scheduler) -> SignalProducer<Value, Error>
where P.Value == Bool
{
// Using `Property.init(_:)` avoids capturing a strong reference
// to `shouldThrottle`, so that we don't extend its lifetime.
let shouldThrottle = Property(shouldThrottle)
return lift { $0.throttle(while: shouldThrottle, on: scheduler) }
}
/// Forward the latest value on `scheduler` after at least `interval`
/// seconds have passed since `self` last sent a value.
///
/// If `self` always sends values more frequently than `interval` seconds,
/// then the returned signal will never send any values.
///
/// To measure from when the *returned signal* last sent a value, see
/// `throttle`.
///
/// - seealso: `throttle`
///
/// - note: If multiple values are received before the interval has elapsed,
/// the latest value is the one that will be passed on.
///
/// - note: If `self` terminates while a value is being debounced,
/// the behaviour will be determined by `discardWhenCompleted`.
/// If `true`, that value will be discarded and the returned producer
/// will terminate immediately.
/// If `false`, that value will be delivered at the next debounce
/// interval.
///
/// - parameters:
/// - interval: A number of seconds to wait before sending a value.
/// - scheduler: A scheduler to send values on.
/// - discardWhenCompleted: A boolean to indicate if the latest value
/// should be discarded on completion.
///
/// - returns: A producer that sends values that are sent from `self` at
/// least `interval` seconds apart.
public func debounce(_ interval: TimeInterval, on scheduler: DateScheduler, discardWhenCompleted: Bool = true) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.debounce(interval, on: scheduler, discardWhenCompleted: discardWhenCompleted))
}
/// Forward events from `self` until `interval`. Then if producer isn't
/// completed yet, fails with `error` on `scheduler`.
///
/// - note: If the interval is 0, the timeout will be scheduled immediately.
/// The producer must complete synchronously (or on a faster
/// scheduler) to avoid the timeout.
///
/// - parameters:
/// - interval: Number of seconds to wait for `self` to complete.
/// - error: Error to send with `failed` event if `self` is not completed
/// when `interval` passes.
/// - scheduler: A scheduler to deliver error on.
///
/// - returns: A producer that sends events for at most `interval` seconds,
/// then, if not `completed` - sends `error` with `failed` event
/// on `scheduler`.
public func timeout(after interval: TimeInterval, raising error: Error, on scheduler: DateScheduler) -> SignalProducer<Value, Error> {
return lift { $0.timeout(after: interval, raising: error, on: scheduler) }
}
}
extension SignalProducer where Value: OptionalProtocol {
/// Unwraps non-`nil` values and forwards them on the returned signal, `nil`
/// values are dropped.
///
/// - returns: A producer that sends only non-nil values.
public func skipNil() -> SignalProducer<Value.Wrapped, Error> {
return core.flatMapEvent(Signal.Event.skipNil)
}
}
extension SignalProducer where Value: EventProtocol, Error == Never {
/// The inverse of materialize(), this will translate a producer of `Event`
/// _values_ into a producer of those events themselves.
///
/// - returns: A producer that sends values carried by `self` events.
public func dematerialize() -> SignalProducer<Value.Value, Value.Error> {
return core.flatMapEvent(Signal.Event.dematerialize)
}
}
extension SignalProducer where Value: ResultProtocol, Error == Never {
/// The inverse of materializeResults(), this will translate a producer of `Result`
/// _values_ into a producer of those events themselves.
///
/// - returns: A producer that sends values carried by `self` results.
public func dematerializeResults() -> SignalProducer<Value.Success, Value.Failure> {
return core.flatMapEvent(Signal.Event.dematerializeResults)
}
}
extension SignalProducer where Error == Never {
/// Promote a producer that does not generate failures into one that can.
///
/// - note: This does not actually cause failers to be generated for the
/// given producer, but makes it easier to combine with other
/// producers that may fail; for example, with operators like
/// `combineLatestWith`, `zipWith`, `flatten`, etc.
///
/// - parameters:
/// - _ An `ErrorType`.
///
/// - returns: A producer that has an instantiatable `ErrorType`.
public func promoteError<F>(_: F.Type = F.self) -> SignalProducer<Value, F> {
return core.flatMapEvent(Signal.Event.promoteError(F.self))
}
/// Promote a producer that does not generate failures into one that can.
///
/// - note: This does not actually cause failers to be generated for the
/// given producer, but makes it easier to combine with other
/// producers that may fail; for example, with operators like
/// `combineLatestWith`, `zipWith`, `flatten`, etc.
///
/// - parameters:
/// - _ An `ErrorType`.
///
/// - returns: A producer that has an instantiatable `ErrorType`.
public func promoteError(_: Error.Type = Error.self) -> SignalProducer<Value, Error> {
return self
}
/// Forward events from `self` until `interval`. Then if producer isn't
/// completed yet, fails with `error` on `scheduler`.
///
/// - note: If the interval is 0, the timeout will be scheduled immediately.
/// The producer must complete synchronously (or on a faster
/// scheduler) to avoid the timeout.
///
/// - parameters:
/// - interval: Number of seconds to wait for `self` to complete.
/// - error: Error to send with `failed` event if `self` is not completed
/// when `interval` passes.
/// - scheudler: A scheduler to deliver error on.
///
/// - returns: A producer that sends events for at most `interval` seconds,
/// then, if not `completed` - sends `error` with `failed` event
/// on `scheduler`.
public func timeout<NewError>(
after interval: TimeInterval,
raising error: NewError,
on scheduler: DateScheduler
) -> SignalProducer<Value, NewError> {
return lift { $0.timeout(after: interval, raising: error, on: scheduler) }
}
/// Apply a throwable action to every value from `self`, and forward the values
/// if the action succeeds. If the action throws an error, the produced `Signal`
/// would propagate the failure and terminate.
///
/// - parameters:
/// - action: A throwable closure to perform an arbitrary action on the value.
///
/// - returns: A producer which forwards the successful values of the given action.
public func attempt(_ action: @escaping (Value) throws -> Void) -> SignalProducer<Value, Swift.Error> {
return self
.promoteError(Swift.Error.self)
.attempt(action)
}
/// Apply a throwable action to every value from `self`, and forward the results
/// if the action succeeds. If the action throws an error, the produced `Signal`
/// would propagate the failure and terminate.
///
/// - parameters:
/// - action: A throwable closure to perform an arbitrary action on the value, and
/// yield a result.
///
/// - returns: A producer which forwards the successful results of the given action.
public func attemptMap<U>(_ action: @escaping (Value) throws -> U) -> SignalProducer<U, Swift.Error> {
return self
.promoteError(Swift.Error.self)
.attemptMap(action)
}
}
extension SignalProducer where Error == Swift.Error {
/// Apply a throwable action to every value from `self`, and forward the values
/// if the action succeeds. If the action throws an error, the produced `Signal`
/// would propagate the failure and terminate.
///
/// - parameters:
/// - action: A throwable closure to perform an arbitrary action on the value.
///
/// - returns: A producer which forwards the successful values of the given action.
public func attempt(_ action: @escaping (Value) throws -> Void) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.attempt(action))
}
/// Apply a throwable transform to every value from `self`, and forward the results
/// if the action succeeds. If the transform throws an error, the produced `Signal`
/// would propagate the failure and terminate.
///
/// - parameters:
/// - transform: A throwable transform.
///
/// - returns: A producer which forwards the successfully transformed values.
public func attemptMap<U>(_ transform: @escaping (Value) throws -> U) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.attemptMap(transform))
}
}
extension SignalProducer where Value == Never {
/// Promote a producer that does not generate values, as indicated by `Never`,
/// to be a producer of the given type of value.
///
/// - note: The promotion does not result in any value being generated.
///
/// - parameters:
/// - _ The type of value to promote to.
///
/// - returns: A producer that forwards all terminal events from `self`.
public func promoteValue<U>(_: U.Type = U.self) -> SignalProducer<U, Error> {
return core.flatMapEvent(Signal.Event.promoteValue(U.self))
}
/// Promote a producer that does not generate values, as indicated by `Never`,
/// to be a producer of the given type of value.
///
/// - note: The promotion does not result in any value being generated.
///
/// - parameters:
/// - _ The type of value to promote to.
///
/// - returns: A producer that forwards all terminal events from `self`.
public func promoteValue(_: Value.Type = Value.self) -> SignalProducer<Value, Error> {
return self
}
}
extension SignalProducer where Value: Equatable {
/// Forward only values from `self` that are not equal to its immediately preceding
/// value.
///
/// - note: The first value is always forwarded.
///
/// - returns: A producer which conditionally forwards values from `self`.
public func skipRepeats() -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.skipRepeats(==))
}
}
extension SignalProducer {
/// Forward only those values from `self` that have unique identities across
/// the set of all values that have been seen.
///
/// - note: This causes the identities to be retained to check for
/// uniqueness.
///
/// - parameters:
/// - transform: A closure that accepts a value and returns identity
/// value.
///
/// - returns: A producer that sends unique values during its lifetime.
public func uniqueValues<Identity: Hashable>(_ transform: @escaping (Value) -> Identity) -> SignalProducer<Value, Error> {
return core.flatMapEvent(Signal.Event.uniqueValues(transform))
}
}
extension SignalProducer where Value: Hashable {
/// Forward only those values from `self` that are unique across the set of
/// all values that have been seen.
///
/// - note: This causes the values to be retained to check for uniqueness.
/// Providing a function that returns a unique value for each sent
/// value can help you reduce the memory footprint.
///
/// - returns: A producer that sends unique values during its lifetime.
public func uniqueValues() -> SignalProducer<Value, Error> {
return uniqueValues { $0 }
}
}
extension SignalProducer {
/// Injects side effects to be performed upon the specified producer events.
///
/// - note: In a composed producer, `starting` is invoked in the reverse
/// direction of the flow of events.
///
/// - parameters:
/// - starting: A closure that is invoked before the producer is started.
/// - started: A closure that is invoked after the producer is started.
/// - event: A closure that accepts an event and is invoked on every
/// received event.
/// - failed: A closure that accepts error object and is invoked for
/// `failed` event.
/// - completed: A closure that is invoked for `completed` event.
/// - interrupted: A closure that is invoked for `interrupted` event.
/// - terminated: A closure that is invoked for any terminating event.
/// - disposed: A closure added as disposable when signal completes.
/// - value: A closure that accepts a value from `value` event.
///
/// - returns: A producer with attached side-effects for given event cases.
public func on(
starting: (() -> Void)? = nil,
started: (() -> Void)? = nil,
event: ((ProducedSignal.Event) -> Void)? = nil,
failed: ((Error) -> Void)? = nil,
completed: (() -> Void)? = nil,
interrupted: (() -> Void)? = nil,
terminated: (() -> Void)? = nil,
disposed: (() -> Void)? = nil,
value: ((Value) -> Void)? = nil
) -> SignalProducer<Value, Error> {
return SignalProducer(SignalCore {
let instance = self.core.makeInstance()
let signal = instance.signal.on(event: event,
failed: failed,
completed: completed,
interrupted: interrupted,
terminated: terminated,
disposed: disposed,
value: value)
return .init(signal: signal,
observerDidSetup: { starting?(); instance.observerDidSetup(); started?() },
interruptHandle: instance.interruptHandle)
})
}
/// Start the returned producer on the given `Scheduler`.
///
/// - note: This implies that any side effects embedded in the producer will
/// be performed on the given scheduler as well.
///
/// - note: Events may still be sent upon other schedulers — this merely
/// affects where the `start()` method is run.
///
/// - parameters:
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A producer that will deliver events on given `scheduler` when
/// started.
public func start(on scheduler: Scheduler) -> SignalProducer<Value, Error> {
return SignalProducer { observer, lifetime in
lifetime += scheduler.schedule {
self.startWithSignal { signal, signalDisposable in
lifetime += signalDisposable
signal.observe(observer)
}
}
}
}
}
extension SignalProducer {
/// Combines the values of all the given producers, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<A: SignalProducerConvertible, B: SignalProducerConvertible>(_ a: A, _ b: B) -> SignalProducer<(Value, B.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer) { Signal.combineLatest($0, $1).observe(observer) }
}
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C) -> SignalProducer<(Value, B.Value, C.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer) { Signal.combineLatest($0, $1, $2).observe(observer) }
}
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D) -> SignalProducer<(Value, B.Value, C.Value, D.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer) { Signal.combineLatest($0, $1, $2, $3).observe(observer) }
}
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer) { Signal.combineLatest($0, $1, $2, $3, $4).observe(observer) }
}
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value, F.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error, F.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer, f.producer) { Signal.combineLatest($0, $1, $2, $3, $4, $5).observe(observer) }
}
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible, G: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error, F.Error == Error, G.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer, f.producer, g.producer) { Signal.combineLatest($0, $1, $2, $3, $4, $5, $6).observe(observer) }
}
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible, G: SignalProducerConvertible, H: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error, F.Error == Error, G.Error == Error, H.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer, f.producer, g.producer, h.producer) { Signal.combineLatest($0, $1, $2, $3, $4, $5, $6, $7).observe(observer) }
}
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible, G: SignalProducerConvertible, H: SignalProducerConvertible, I: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value, I.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error, F.Error == Error, G.Error == Error, H.Error == Error, I.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer, f.producer, g.producer, h.producer, i.producer) { Signal.combineLatest($0, $1, $2, $3, $4, $5, $6, $7, $8).observe(observer) }
}
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatest(with:)`.
public static func combineLatest<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible, G: SignalProducerConvertible, H: SignalProducerConvertible, I: SignalProducerConvertible, J: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I, _ j: J) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value, I.Value, J.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error, F.Error == Error, G.Error == Error, H.Error == Error, I.Error == Error, J.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer, f.producer, g.producer, h.producer, i.producer, j.producer) { Signal.combineLatest($0, $1, $2, $3, $4, $5, $6, $7, $8, $9).observe(observer) }
}
}
/// Combines the values of all the given producers, in the manner described by
/// `combineLatest(with:)`. Will return an empty `SignalProducer` if the sequence is empty.
public static func combineLatest<S: Sequence>(_ producers: S) -> SignalProducer<[Value], Error> where S.Iterator.Element: SignalProducerConvertible, S.Iterator.Element.Value == Value, S.Iterator.Element.Error == Error {
return start(producers, Signal.combineLatest)
}
/// Zips the values of all the given producers, in the manner described by
/// `zip(with:)`.
public static func zip<A: SignalProducerConvertible, B: SignalProducerConvertible>(_ a: A, _ b: B) -> SignalProducer<(Value, B.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer) { Signal.zip($0, $1).observe(observer) }
}
}
/// Zips the values of all the given producers, in the manner described by
/// `zip(with:)`.
public static func zip<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C) -> SignalProducer<(Value, B.Value, C.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer) { Signal.zip($0, $1, $2).observe(observer) }
}
}
/// Zips the values of all the given producers, in the manner described by
/// `zip(with:)`.
public static func zip<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D) -> SignalProducer<(Value, B.Value, C.Value, D.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer) { Signal.zip($0, $1, $2, $3).observe(observer) }
}
}
/// Zips the values of all the given producers, in the manner described by
/// `zip(with:)`.
public static func zip<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer) { Signal.zip($0, $1, $2, $3, $4).observe(observer) }
}
}
/// Zips the values of all the given producers, in the manner described by
/// `zip(with:)`.
public static func zip<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value, F.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error, F.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer, f.producer) { Signal.zip($0, $1, $2, $3, $4, $5).observe(observer) }
}
}
/// Zips the values of all the given producers, in the manner described by
/// `zip(with:)`.
public static func zip<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible, G: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error, F.Error == Error, G.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer, f.producer, g.producer) { Signal.zip($0, $1, $2, $3, $4, $5, $6).observe(observer) }
}
}
/// Zips the values of all the given producers, in the manner described by
/// `zip(with:)`.
public static func zip<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible, G: SignalProducerConvertible, H: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error, F.Error == Error, G.Error == Error, H.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer, f.producer, g.producer, h.producer) { Signal.zip($0, $1, $2, $3, $4, $5, $6, $7).observe(observer) }
}
}
/// Zips the values of all the given producers, in the manner described by
/// `zip(with:)`.
public static func zip<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible, G: SignalProducerConvertible, H: SignalProducerConvertible, I: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value, I.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error, F.Error == Error, G.Error == Error, H.Error == Error, I.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer, f.producer, g.producer, h.producer, i.producer) { Signal.zip($0, $1, $2, $3, $4, $5, $6, $7, $8).observe(observer) }
}
}
/// Zips the values of all the given producers, in the manner described by
/// `zip(with:)`.
public static func zip<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible, G: SignalProducerConvertible, H: SignalProducerConvertible, I: SignalProducerConvertible, J: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I, _ j: J) -> SignalProducer<(Value, B.Value, C.Value, D.Value, E.Value, F.Value, G.Value, H.Value, I.Value, J.Value), Error> where A.Value == Value, A.Error == Error, B.Error == Error, C.Error == Error, D.Error == Error, E.Error == Error, F.Error == Error, G.Error == Error, H.Error == Error, I.Error == Error, J.Error == Error {
return .init { observer, lifetime in
flattenStart(lifetime, a.producer, b.producer, c.producer, d.producer, e.producer, f.producer, g.producer, h.producer, i.producer, j.producer) { Signal.zip($0, $1, $2, $3, $4, $5, $6, $7, $8, $9).observe(observer) }
}
}
/// Zips the values of all the given producers, in the manner described by
/// `zipWith`. Will return an empty `SignalProducer` if the sequence is empty.
public static func zip<S: Sequence>(_ producers: S) -> SignalProducer<[Value], Error> where S.Iterator.Element: SignalProducerConvertible, S.Iterator.Element.Value == Value, S.Iterator.Element.Error == Error {
return start(producers, Signal.zip)
}
private static func start<S: Sequence>(_ producers: S, _ transform: @escaping (ReversedCollection<[Signal<Value, Error>]>) -> Signal<[Value], Error>) -> SignalProducer<[Value], Error> where S.Iterator.Element: SignalProducerConvertible, S.Iterator.Element.Value == Value, S.Iterator.Element.Error == Error {
return SignalProducer<[Value], Error> { observer, lifetime in
var producers = Array(producers)
var signals: [Signal<Value, Error>] = []
guard !producers.isEmpty else {
observer.sendCompleted()
return
}
func start() {
guard !producers.isEmpty else {
transform(signals.reversed()).observe(observer)
return
}
producers.removeLast().producer.startWithSignal { signal, interruptHandle in
lifetime += interruptHandle
signals.append(signal)
start()
}
}
start()
}
}
}
extension SignalProducer {
/// Repeat `self` a total of `count` times. In other words, start producer
/// `count` number of times, each one after previously started producer
/// completes.
///
/// - note: Repeating `1` time results in an equivalent signal producer.
///
/// - note: Repeating `0` times results in a producer that instantly
/// completes.
///
/// - precondition: `count` must be non-negative integer.
///
/// - parameters:
/// - count: Number of repetitions.
///
/// - returns: A signal producer start sequentially starts `self` after
/// previously started producer completes.
public func `repeat`(_ count: Int) -> SignalProducer<Value, Error> {
precondition(count >= 0)
if count == 0 {
return .empty
} else if count == 1 {
return producer
}
return SignalProducer { observer, lifetime in
let serialDisposable = SerialDisposable()
lifetime += serialDisposable
func iterate(_ current: Int) {
self.startWithSignal { signal, signalDisposable in
serialDisposable.inner = signalDisposable
signal.observe { event in
if case .completed = event {
let remainingTimes = current - 1
if remainingTimes > 0 {
iterate(remainingTimes)
} else {
observer.sendCompleted()
}
} else {
observer.send(event)
}
}
}
}
iterate(count)
}
}
/// Ignore failures up to `count` times.
///
/// - precondition: `count` must be non-negative integer.
///
/// - parameters:
/// - count: Number of retries.
///
/// - returns: A signal producer that restarts up to `count` times.
public func retry(upTo count: Int) -> SignalProducer<Value, Error> {
precondition(count >= 0)
if count == 0 {
return producer
} else {
return flatMapError { _ in
self.retry(upTo: count - 1)
}
}
}
/// Delays retrying on failure by `interval` up to `count` attempts.
///
/// - precondition: `count` must be non-negative integer.
///
/// - parameters:
/// - count: Number of retries.
/// - interval: An interval between invocations.
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A signal producer that restarts up to `count` times.
public func retry(upTo count: Int, interval: TimeInterval, on scheduler: DateScheduler) -> SignalProducer<Value, Error> {
precondition(count >= 0)
if count == 0 {
return producer
}
var retries = count
return flatMapError { error -> SignalProducer<Value, Error> in
// The final attempt shouldn't defer the error if it fails
var producer = SignalProducer<Value, Error>(error: error)
if retries > 0 {
producer = SignalProducer.empty
.delay(interval, on: scheduler)
.concat(producer)
}
retries -= 1
return producer
}
.retry(upTo: count)
}
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`. Any failure or interruption sent from `self` is
/// forwarded immediately, in which case `replacement` will not be started,
/// and none of its events will be be forwarded.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then<U>(_ replacement: SignalProducer<U, Never>) -> SignalProducer<U, Error> {
return _then(replacement.promoteError(Error.self))
}
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`. Any failure or interruption sent from `self` is
/// forwarded immediately, in which case `replacement` will not be started,
/// and none of its events will be be forwarded.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then<Replacement: SignalProducerConvertible>(_ replacement: Replacement) -> SignalProducer<Replacement.Value, Error> where Replacement.Error == Never {
return then(replacement.producer)
}
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`. Any failure or interruption sent from `self` is
/// forwarded immediately, in which case `replacement` will not be started,
/// and none of its events will be be forwarded.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then<U>(_ replacement: SignalProducer<U, Error>) -> SignalProducer<U, Error> {
return _then(replacement)
}
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`. Any failure or interruption sent from `self` is
/// forwarded immediately, in which case `replacement` will not be started,
/// and none of its events will be be forwarded.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then<Replacement: SignalProducerConvertible>(_ replacement: Replacement) -> SignalProducer<Replacement.Value, Error> where Replacement.Error == Error {
return then(replacement.producer)
}
// NOTE: The overload below is added to disambiguate compile-time selection of
// `then(_:)`.
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`. Any failure or interruption sent from `self` is
/// forwarded immediately, in which case `replacement` will not be started,
/// and none of its events will be be forwarded.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then(_ replacement: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return _then(replacement)
}
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`. Any failure or interruption sent from `self` is
/// forwarded immediately, in which case `replacement` will not be started,
/// and none of its events will be be forwarded.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then<Replacement: SignalProducerConvertible>(_ replacement: Replacement) -> SignalProducer<Value, Error> where Replacement.Value == Value, Replacement.Error == Error {
return then(replacement.producer)
}
// NOTE: The method below is the shared implementation of `then(_:)`. The underscore
// prefix is added to avoid self referencing in `then(_:)` overloads with
// regard to the most specific rule of overload selection in Swift.
internal func _then<Replacement: SignalProducerConvertible>(_ replacement: Replacement) -> SignalProducer<Replacement.Value, Error> where Replacement.Error == Error {
return SignalProducer<Replacement.Value, Error> { observer, lifetime in
self.startWithSignal { signal, signalDisposable in
lifetime += signalDisposable
signal.observe { event in
switch event {
case let .failed(error):
observer.send(error: error)
case .completed:
lifetime += replacement.producer.start(observer)
case .interrupted:
observer.sendInterrupted()
case .value:
break
}
}
}
}
}
}
extension SignalProducer where Error == Never {
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then<U, F>(_ replacement: SignalProducer<U, F>) -> SignalProducer<U, F> {
return promoteError(F.self)._then(replacement)
}
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then<Replacement: SignalProducerConvertible>(_ replacement: Replacement) -> SignalProducer<Replacement.Value, Replacement.Error> {
return then(replacement.producer)
}
// NOTE: The overload below is added to disambiguate compile-time selection of
// `then(_:)`.
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then<U>(_ replacement: SignalProducer<U, Never>) -> SignalProducer<U, Never> {
return _then(replacement)
}
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then<Replacement: SignalProducerConvertible>(_ replacement: Replacement) -> SignalProducer<Replacement.Value, Never> where Replacement.Error == Never {
return then(replacement.producer)
}
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then(_ replacement: SignalProducer<Value, Never>) -> SignalProducer<Value, Never> {
return _then(replacement)
}
/// Wait for completion of `self`, *then* forward all events from
/// `replacement`.
///
/// - note: All values sent from `self` are ignored.
///
/// - parameters:
/// - replacement: A producer to start when `self` completes.
///
/// - returns: A producer that sends events from `self` and then from
/// `replacement` when `self` completes.
public func then<Replacement: SignalProducerConvertible>(_ replacement: Replacement) -> SignalProducer<Value, Never> where Replacement.Value == Value, Replacement.Error == Never {
return then(replacement.producer)
}
}
extension SignalProducer {
/// Start the producer, then block, waiting for the first value.
///
/// When a single value or error is sent, the returned `Result` will
/// represent those cases. However, when no values are sent, `nil` will be
/// returned.
///
/// - returns: Result when single `value` or `failed` event is received.
/// `nil` when no events are received.
public func first() -> Result<Value, Error>? {
return take(first: 1).single()
}
/// Start the producer, then block, waiting for events: `value` and
/// `completed`.
///
/// When a single value or error is sent, the returned `Result` will
/// represent those cases. However, when no values are sent, or when more
/// than one value is sent, `nil` will be returned.
///
/// - returns: Result when single `value` or `failed` event is received.
/// `nil` when 0 or more than 1 events are received.
public func single() -> Result<Value, Error>? {
let semaphore = DispatchSemaphore(value: 0)
var result: Result<Value, Error>?
take(first: 2).start { event in
switch event {
case let .value(value):
if result != nil {
// Move into failure state after recieving another value.
result = nil
return
}
result = .success(value)
case let .failed(error):
result = .failure(error)
semaphore.signal()
case .completed, .interrupted:
semaphore.signal()
}
}
semaphore.wait()
return result
}
/// Start the producer, then block, waiting for the last value.
///
/// When a single value or error is sent, the returned `Result` will
/// represent those cases. However, when no values are sent, `nil` will be
/// returned.
///
/// - returns: Result when single `value` or `failed` event is received.
/// `nil` when no events are received.
public func last() -> Result<Value, Error>? {
return take(last: 1).single()
}
/// Starts the producer, then blocks, waiting for completion.
///
/// When a completion or error is sent, the returned `Result` will represent
/// those cases.
///
/// - returns: Result when single `completion` or `failed` event is
/// received.
public func wait() -> Result<(), Error> {
return then(SignalProducer<(), Error>(value: ())).last() ?? .success(())
}
/// Creates a new `SignalProducer` that will multicast values emitted by
/// the underlying producer, up to `capacity`.
/// This means that all clients of this `SignalProducer` will see the same
/// version of the emitted values/errors.
///
/// The underlying `SignalProducer` will not be started until `self` is
/// started for the first time. When subscribing to this producer, all
/// previous values (up to `capacity`) will be emitted, followed by any new
/// values.
///
/// If you find yourself needing *the current value* (the last buffered
/// value) you should consider using `PropertyType` instead, which, unlike
/// this operator, will guarantee at compile time that there's always a
/// buffered value. This operator is not recommended in most cases, as it
/// will introduce an implicit relationship between the original client and
/// the rest, so consider alternatives like `PropertyType`, or representing
/// your stream using a `Signal` instead.
///
/// This operator is only recommended when you absolutely need to introduce
/// a layer of caching in front of another `SignalProducer`.
///
/// - precondition: `capacity` must be non-negative integer.
///
/// - parameters:
/// - capacity: Number of values to hold.
///
/// - returns: A caching producer that will hold up to last `capacity`
/// values.
public func replayLazily(upTo capacity: Int) -> SignalProducer<Value, Error> {
precondition(capacity >= 0, "Invalid capacity: \(capacity)")
// This will go "out of scope" when the returned `SignalProducer` goes
// out of scope. This lets us know when we're supposed to dispose the
// underlying producer. This is necessary because `struct`s don't have
// `deinit`.
let lifetimeToken = Lifetime.Token()
let lifetime = Lifetime(lifetimeToken)
let state = Atomic(ReplayState<Value, Error>(upTo: capacity))
let start: Atomic<(() -> Void)?> = Atomic {
// Start the underlying producer.
self
.take(during: lifetime)
.start { event in
let observers: Bag<Signal<Value, Error>.Observer>? = state.modify { state in
defer { state.enqueue(event) }
return state.observers
}
observers?.forEach { $0.send(event) }
}
}
return SignalProducer { observer, lifetime in
// Don't dispose of the original producer until all observers
// have terminated.
lifetime.observeEnded { _ = lifetimeToken }
while true {
var result: Result<Bag<Signal<Value, Error>.Observer>.Token?, ReplayError<Value>>!
state.modify {
result = $0.observe(observer)
}
switch result! {
case let .success(token):
if let token = token {
lifetime.observeEnded {
state.modify {
$0.removeObserver(using: token)
}
}
}
// Start the underlying producer if it has never been started.
start.swap(nil)?()
// Terminate the replay loop.
return
case let .failure(error):
error.values.forEach(observer.send(value:))
}
}
}
}
}
extension SignalProducer where Value == Bool {
/// Create a producer that computes a logical NOT in the latest values of `self`.
///
/// - returns: A producer that emits the logical NOT results.
public func negate() -> SignalProducer<Value, Error> {
return map(!)
}
/// Create a producer that computes a logical AND between the latest values of `self`
/// and `producer`.
///
/// - parameters:
/// - booleans: A producer of booleans to be combined with `self`.
///
/// - returns: A producer that emits the logical AND results.
public func and(_ booleans: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return combineLatest(with: booleans).map { $0.0 && $0.1 }
}
/// Create a producer that computes a logical AND between the latest values of `self`
/// and `producer`.
///
/// - parameters:
/// - booleans: A producer of booleans to be combined with `self`.
///
/// - returns: A producer that emits the logical AND results.
public func and<Booleans: SignalProducerConvertible>(_ booleans: Booleans) -> SignalProducer<Value, Error> where Booleans.Value == Value, Booleans.Error == Error {
return and(booleans.producer)
}
/// Create a producer that computes a logical OR between the latest values of `self`
/// and `producer`.
///
/// - parameters:
/// - booleans: A producer of booleans to be combined with `self`.
///
/// - returns: A producer that emits the logical OR results.
public func or(_ booleans: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return combineLatest(with: booleans).map { $0.0 || $0.1 }
}
/// Create a producer that computes a logical OR between the latest values of `self`
/// and `producer`.
///
/// - parameters:
/// - booleans: A producer of booleans to be combined with `self`.
///
/// - returns: A producer that emits the logical OR results.
public func or<Booleans: SignalProducerConvertible>(_ booleans: Booleans) -> SignalProducer<Value, Error> where Booleans.Value == Value, Booleans.Error == Error {
return or(booleans.producer)
}
}
/// Represents a recoverable error of an observer not being ready for an
/// attachment to a `ReplayState`, and the observer should replay the supplied
/// values before attempting to observe again.
private struct ReplayError<Value>: Error {
/// The values that should be replayed by the observer.
let values: [Value]
}
private struct ReplayState<Value, Error: Swift.Error> {
let capacity: Int
/// All cached values.
var values: [Value] = []
/// A termination event emitted by the underlying producer.
///
/// This will be nil if termination has not occurred.
var terminationEvent: Signal<Value, Error>.Event?
/// The observers currently attached to the caching producer, or `nil` if the
/// caching producer was terminated.
var observers: Bag<Signal<Value, Error>.Observer>? = Bag()
/// The set of in-flight replay buffers.
var replayBuffers: [ObjectIdentifier: [Value]] = [:]
/// Initialize the replay state.
///
/// - parameters:
/// - capacity: The maximum amount of values which can be cached by the
/// replay state.
init(upTo capacity: Int) {
self.capacity = capacity
}
/// Attempt to observe the replay state.
///
/// - warning: Repeatedly observing the replay state with the same observer
/// should be avoided.
///
/// - parameters:
/// - observer: The observer to be registered.
///
/// - returns: If the observer is successfully attached, a `Result.success`
/// with the corresponding removal token would be returned.
/// Otherwise, a `Result.failure` with a `ReplayError` would be
/// returned.
mutating func observe(_ observer: Signal<Value, Error>.Observer) -> Result<Bag<Signal<Value, Error>.Observer>.Token?, ReplayError<Value>> {
// Since the only use case is `replayLazily`, which always creates a unique
// `Observer` for every produced signal, we can use the ObjectIdentifier of
// the `Observer` to track them directly.
let id = ObjectIdentifier(observer)
switch replayBuffers[id] {
case .none where !values.isEmpty:
// No in-flight replay buffers was found, but the `ReplayState` has one or
// more cached values in the `ReplayState`. The observer should replay
// them before attempting to observe again.
replayBuffers[id] = []
return .failure(ReplayError(values: values))
case let .some(buffer) where !buffer.isEmpty:
// An in-flight replay buffer was found with one or more buffered values.
// The observer should replay them before attempting to observe again.
defer { replayBuffers[id] = [] }
return .failure(ReplayError(values: buffer))
case let .some(buffer) where buffer.isEmpty:
// Since an in-flight but empty replay buffer was found, the observer is
// ready to be attached to the `ReplayState`.
replayBuffers.removeValue(forKey: id)
default:
// No values has to be replayed. The observer is ready to be attached to
// the `ReplayState`.
break
}
if let event = terminationEvent {
observer.send(event)
}
return .success(observers?.insert(observer))
}
/// Enqueue the supplied event to the replay state.
///
/// - parameter:
/// - event: The event to be cached.
mutating func enqueue(_ event: Signal<Value, Error>.Event) {
switch event {
case let .value(value):
for key in replayBuffers.keys {
replayBuffers[key]!.append(value)
}
switch capacity {
case 0:
// With a capacity of zero, `state.values` can never be filled.
break
case 1:
values = [value]
default:
values.append(value)
let overflow = values.count - capacity
if overflow > 0 {
values.removeFirst(overflow)
}
}
case .completed, .failed, .interrupted:
// Disconnect all observers and prevent future attachments.
terminationEvent = event
observers = nil
}
}
/// Remove the observer represented by the supplied token.
///
/// - parameters:
/// - token: The token of the observer to be removed.
mutating func removeObserver(using token: Bag<Signal<Value, Error>.Observer>.Token) {
observers?.remove(using: token)
}
}
extension SignalProducer where Value == Date, Error == Never {
/// Create a repeating timer of the given interval, with a reasonable default
/// leeway, sending updates on the given scheduler.
///
/// - note: This timer will never complete naturally, so all invocations of
/// `start()` must be disposed to avoid leaks.
///
/// - precondition: `interval` must be non-negative number.
///
/// - note: If you plan to specify an `interval` value greater than 200,000
/// seconds, use `timer(interval:on:leeway:)` instead
/// and specify your own `leeway` value to avoid potential overflow.
///
/// - parameters:
/// - interval: An interval between invocations.
/// - scheduler: A scheduler to deliver events on.
///
/// - returns: A producer that sends `Date` values every `interval` seconds.
public static func timer(interval: DispatchTimeInterval, on scheduler: DateScheduler) -> SignalProducer<Value, Error> {
// Apple's "Power Efficiency Guide for Mac Apps" recommends a leeway of
// at least 10% of the timer interval.
return timer(interval: interval, on: scheduler, leeway: interval * 0.1)
}
/// Creates a repeating timer of the given interval, sending updates on the
/// given scheduler.
///
/// - note: This timer will never complete naturally, so all invocations of
/// `start()` must be disposed to avoid leaks.
///
/// - precondition: `interval` must be non-negative number.
///
/// - precondition: `leeway` must be non-negative number.
///
/// - parameters:
/// - interval: An interval between invocations.
/// - scheduler: A scheduler to deliver events on.
/// - leeway: Interval leeway. Apple's "Power Efficiency Guide for Mac Apps"
/// recommends a leeway of at least 10% of the timer interval.
///
/// - returns: A producer that sends `Date` values every `interval` seconds.
public static func timer(interval: DispatchTimeInterval, on scheduler: DateScheduler, leeway: DispatchTimeInterval) -> SignalProducer<Value, Error> {
precondition(interval.timeInterval >= 0)
precondition(leeway.timeInterval >= 0)
return SignalProducer { observer, lifetime in
lifetime += scheduler.schedule(
after: scheduler.currentDate.addingTimeInterval(interval),
interval: interval,
leeway: leeway,
action: { observer.send(value: scheduler.currentDate) }
)
}
}
}
| mit | 0807dff5a4d400d86b2f3937a311570e | 42.048354 | 733 | 0.674737 | 3.834937 | false | false | false | false |
arvedviehweger/swift | validation-test/stdlib/CollectionDiagnostics.swift | 1 | 5826 | // RUN: %target-typecheck-verify-swift -verify-ignore-unknown
import StdlibUnittest
import StdlibCollectionUnittest
//
// Check that Collection.SubSequence is constrained to Collection.
//
// expected-error@+3 {{type 'CollectionWithBadSubSequence' does not conform to protocol 'Collection'}}
// expected-error@+2 {{type 'CollectionWithBadSubSequence' does not conform to protocol '_IndexableBase'}}
// expected-error@+1 {{type 'CollectionWithBadSubSequence' does not conform to protocol 'Sequence'}}
struct CollectionWithBadSubSequence : Collection {
var startIndex: MinimalIndex {
fatalError("unreachable")
}
var endIndex: MinimalIndex {
fatalError("unreachable")
}
subscript(i: MinimalIndex) -> OpaqueValue<Int> {
fatalError("unreachable")
}
// expected-note@+3 {{possibly intended match 'CollectionWithBadSubSequence.SubSequence' (aka 'OpaqueValue<Int8>') does not conform to 'Sequence'}}
// expected-note@+2 {{possibly intended match}}
// expected-note@+1 {{possibly intended match}}
typealias SubSequence = OpaqueValue<Int8>
}
func useCollectionTypeSubSequenceIndex<C : Collection>(_ c: C) {}
func useCollectionTypeSubSequenceGeneratorElement<C : Collection>(_ c: C) {}
func sortResultIgnored<
S : Sequence,
MC : MutableCollection
>(_ sequence: S, mutableCollection: MC, array: [Int])
where S.Iterator.Element : Comparable, MC.Iterator.Element : Comparable {
var sequence = sequence // expected-warning {{variable 'sequence' was never mutated; consider changing to 'let' constant}}
var mutableCollection = mutableCollection // expected-warning {{variable 'mutableCollection' was never mutated; consider changing to 'let' constant}}
var array = array // expected-warning {{variable 'array' was never mutated; consider changing to 'let' constant}}
sequence.sorted() // expected-warning {{result of call to 'sorted()' is unused}}
sequence.sorted { $0 < $1 } // expected-warning {{result of call to 'sorted(by:)' is unused}}
mutableCollection.sorted() // expected-warning {{result of call to 'sorted()' is unused}}
mutableCollection.sorted { $0 < $1 } // expected-warning {{result of call to 'sorted(by:)' is unused}}
array.sorted() // expected-warning {{result of call to 'sorted()' is unused}}
array.sorted { $0 < $1 } // expected-warning {{result of call to 'sorted(by:)' is unused}}
}
// expected-warning@+1 {{'Indexable' is deprecated: it will be removed in Swift 4.0. Please use 'Collection' instead}}
struct GoodIndexable : Indexable {
func index(after i: Int) -> Int { return i + 1 }
var startIndex: Int { return 0 }
var endIndex: Int { return 0 }
subscript(pos: Int) -> Int { return 0 }
subscript(bounds: Range<Int>) -> [Int] { return [] }
}
// expected-warning@+2 {{'Indexable' is deprecated: it will be removed in Swift 4.0. Please use 'Collection' instead}}
// expected-error@+1 {{type 'BadIndexable1' does not conform to protocol '_IndexableBase'}}
struct BadIndexable1 : Indexable {
func index(after i: Int) -> Int { return i + 1 }
var startIndex: Int { return 0 }
var endIndex: Int { return 0 }
subscript(pos: Int) -> Int { return 0 }
// Missing 'subscript(_:) -> SubSequence'.
}
// expected-warning@+2 {{'Indexable' is deprecated: it will be removed in Swift 4.0. Please use 'Collection' instead}}
// expected-error@+1 {{type 'BadIndexable2' does not conform to protocol '_IndexableBase'}}
struct BadIndexable2 : Indexable {
var startIndex: Int { return 0 }
var endIndex: Int { return 0 }
subscript(pos: Int) -> Int { return 0 }
subscript(bounds: Range<Int>) -> [Int] { return [] }
// Missing index(after:) -> Int
}
// expected-warning@+1 {{'BidirectionalIndexable' is deprecated: it will be removed in Swift 4.0. Please use 'BidirectionalCollection' instead}}
struct GoodBidirectionalIndexable1 : BidirectionalIndexable {
var startIndex: Int { return 0 }
var endIndex: Int { return 0 }
func index(after i: Int) -> Int { return i + 1 }
func index(before i: Int) -> Int { return i - 1 }
subscript(pos: Int) -> Int { return 0 }
subscript(bounds: Range<Int>) -> [Int] { return [] }
}
// We'd like to see: {{type 'BadBidirectionalIndexable' does not conform to protocol 'BidirectionalIndexable'}}
// But the compiler doesn't generate that error.
// expected-warning@+1 {{'BidirectionalIndexable' is deprecated: it will be removed in Swift 4.0. Please use 'BidirectionalCollection' instead}}
struct BadBidirectionalIndexable : BidirectionalIndexable {
var startIndex: Int { return 0 }
var endIndex: Int { return 0 }
subscript(pos: Int) -> Int { return 0 }
subscript(bounds: Range<Int>) -> [Int] { return [] }
// This is a poor error message; it would be better to get a message
// that index(before:) was missing.
//
// expected-error@+1 {{'index(after:)' has different argument names from those required by protocol '_BidirectionalIndexable' ('index(before:)'}}
func index(after i: Int) -> Int { return 0 }
}
//
// Check that RangeReplaceableCollection.SubSequence is defaulted.
//
struct RangeReplaceableCollection_SubSequence_IsDefaulted : RangeReplaceableCollection {
var startIndex: Int { fatalError() }
var endIndex: Int { fatalError() }
subscript(pos: Int) -> Int { return 0 }
func index(after: Int) -> Int { fatalError() }
func index(before: Int) -> Int { fatalError() }
func index(_: Int, offsetBy: Int) -> Int { fatalError() }
func distance(from: Int, to: Int) -> Int { fatalError() }
mutating func replaceSubrange<C>(
_ subrange: Range<Int>,
with newElements: C
) where C : Collection, C.Iterator.Element == Int {
fatalError()
}
}
// FIXME: Remove -verify-ignore-unknown.
// <unknown>:0: error: unexpected note produced: possibly intended match
// <unknown>:0: error: unexpected note produced: possibly intended match
| apache-2.0 | 924e951dedcaa08a76f806b6d2a40095 | 40.028169 | 151 | 0.7046 | 4.108604 | false | false | false | false |
STShenZhaoliang/iOS-GuidesAndSampleCode | 精通Swift设计模式/Chapter 04/SportsStore/SportsStore/Product.swift | 1 | 917 | class Product {
private(set) var name:String;
private(set) var description:String;
private(set) var category:String;
private var stockLevelBackingValue:Int = 0;
private var priceBackingValue:Double = 0;
init(name:String, description:String, category:String, price:Double,
stockLevel:Int) {
self.name = name;
self.description = description;
self.category = category;
self.price = price;
self.stockLevel = stockLevel;
}
var stockLevel:Int {
get { return stockLevelBackingValue;}
set { stockLevelBackingValue = max(0, newValue);}
}
private(set) var price:Double {
get { return priceBackingValue;}
set { priceBackingValue = max(1, newValue);}
}
var stockValue:Double {
get {
return price * Double(stockLevel);
}
}
}
| mit | 24f0df31d3fb4787e5f4f00508aaf539 | 26.787879 | 72 | 0.591058 | 4.451456 | false | false | false | false |
huangboju/Moots | Examples/UIScrollViewDemo/UIScrollViewDemo/Controllers/WindowVC.swift | 1 | 1130 | //
// WindowVC.swift
// UIScrollViewDemo
//
// Created by xiAo_Ju on 2019/2/20.
// Copyright © 2019 伯驹 黄. All rights reserved.
//
import UIKit
// https://medium.com/@evicoli/creating-custom-notification-ios-banner-sliding-over-status-bar-4a7b5f842307
class WindowVC: UIViewController {
let bannerView = UIView(frame: CGRect(x: 0, y: 0, width: 414 - 30, height: 200))
var window: UIWindow?
override func viewDidLoad() {
super.viewDidLoad()
let bannerWindow = UIWindow(frame: CGRect(x: 15, y: -200, width: 414 - 30, height: 200))
bannerWindow.layer.cornerRadius = 12
bannerWindow.layer.masksToBounds = true
bannerWindow.windowLevel = UIWindow.Level.statusBar
bannerWindow.addSubview(bannerView)
bannerWindow.rootViewController = self
window = bannerWindow
bannerView.backgroundColor = .red
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
window?.isHidden = false
UIWindow.animate(withDuration: 0.3) {
self.window?.frame.origin.y = 32
}
}
}
| mit | 5c20daa0342057727fbea7436d8db576 | 29.351351 | 107 | 0.653606 | 3.968198 | false | false | false | false |
ProcedureKit/ProcedureKit | Sources/ProcedureKitCoreData/MakeFetchedResultController.swift | 2 | 3053 | //
// ProcedureKit
//
// Copyright © 2015-2018 ProcedureKit. All rights reserved.
//
#if SWIFT_PACKAGE
import ProcedureKit
import Foundation
#endif
import CoreData
/**
Makes a FetchResultsController, using the viewContext from a NSPersistenContainer
which is injected before execution, but after initialization. For example:
```swift
let coreDataStack = LoadCoreDataProcedure(name: "CoreDataEntities")
let makeFRC = MakeFetchedResultControllerProcedure(for: "MyEntity")
.injectResult(from: coreDataStack)
```
*/
@available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *)
open class MakeFetchedResultControllerProcedure<Result: NSFetchRequestResult>: TransformProcedure<NSPersistentContainer, NSFetchedResultsController<Result>> {
static func transform(fetchRequest: NSFetchRequest<Result>, sectionNameKeyPath: String? = nil, cacheName: String? = nil) -> (NSPersistentContainer) throws -> NSFetchedResultsController<Result> {
return { (container) in
let frc = NSFetchedResultsController(
fetchRequest: fetchRequest,
managedObjectContext: container.viewContext,
sectionNameKeyPath: sectionNameKeyPath,
cacheName: cacheName)
try container.viewContext.performAndWait(block: frc.performFetch)
return frc
}
}
/// Initializes the FetchedResultsController with a NSFetchRequest
public init(fetchRequest: NSFetchRequest<Result>, sectionNameKeyPath: String? = nil, cacheName: String? = nil) {
super.init(transform: MakeFetchedResultControllerProcedure<Result>.transform(fetchRequest: fetchRequest, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName))
name = "Make FRC \(fetchRequest.entityName ?? "")".trimmingCharacters(in: .whitespaces)
}
/// Convenience initalizer using just the entity name, fetch limit (default is 50) and sort descriptors (default is empty).
public init(for entityName: String, fetchLimit: Int = 50, sortDescriptors: [NSSortDescriptor] = [], sectionNameKeyPath: String? = nil, cacheName: String? = nil) {
let fetchRequest: NSFetchRequest<Result> = NSFetchRequest(entityName: entityName)
fetchRequest.fetchLimit = fetchLimit
fetchRequest.sortDescriptors = sortDescriptors
super.init(transform: MakeFetchedResultControllerProcedure<Result>.transform(fetchRequest: fetchRequest, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName))
name = "Make FRC \(fetchRequest.entityName ?? "")".trimmingCharacters(in: .whitespaces)
}
}
@available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *)
public extension MakeFetchedResultControllerProcedure where Result: NSManagedObject {
convenience init(fetchLimit: Int = 50, sortDescriptors: [NSSortDescriptor] = [], sectionNameKeyPath: String? = nil, cacheName: String? = nil) {
self.init(for: Result.entityName, fetchLimit: fetchLimit, sortDescriptors: sortDescriptors, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName)
}
}
| mit | dda86f6e2913f62015893e34a5780915 | 43.231884 | 198 | 0.737877 | 5.190476 | false | false | false | false |
xusader/firefox-ios | Sync/Record.swift | 3 | 3118 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
let ONE_YEAR_IN_SECONDS = 365 * 24 * 60 * 60;
/**
* Immutable representation for Sync records.
*
* Envelopes consist of:
* Required: "id", "collection", "payload".
* Optional: "modified", "sortindex", "ttl".
*
* Deletedness is a property of the payload.
*/
public class Record<T: CleartextPayloadJSON> {
public let id: String
public let payload: T
public let modified: Timestamp
public let sortindex: Int
public let ttl: Int // Seconds.
// This is a hook for decryption.
// Right now it only parses the string. In subclasses, it'll parse the
// string, decrypt the contents, and return the data as a JSON object.
// From the docs:
//
// payload none string 256k
// A string containing a JSON structure encapsulating the data of the record.
// This structure is defined separately for each WBO type.
// Parts of the structure may be encrypted, in which case the structure
// should also specify a record for decryption.
//
// @seealso EncryptedRecord.
public class func payloadFromPayloadString(envelope: EnvelopeJSON, payload: String) -> T? {
return T(payload)
}
// TODO: consider using error tuples.
public class func fromEnvelope(envelope: EnvelopeJSON, payloadFactory: (String) -> T?) -> Record<T>? {
if !(envelope.isValid()) {
println("Invalid envelope.")
return nil
}
let payload = payloadFactory(envelope.payload)
if (payload == nil) {
println("Unable to parse payload.")
return nil
}
if payload!.isValid() {
return Record<T>(envelope: envelope, payload: payload!)
}
println("Invalid payload \(payload!.toString(pretty: true)).")
return nil
}
/**
* Accepts an envelope and a decrypted payload.
* Inputs are not validated. Use `fromEnvelope` above.
*/
convenience init(envelope: EnvelopeJSON, payload: T) {
// TODO: modified, sortindex, ttl
self.init(id: envelope.id, payload: payload, modified: envelope.modified, sortindex: envelope.sortindex)
}
init(id: String, payload: T, modified: Timestamp = Timestamp(time(nil)), sortindex: Int = 0, ttl: Int = ONE_YEAR_IN_SECONDS) {
self.id = id
self.payload = payload;
self.modified = modified
self.sortindex = sortindex
self.ttl = ttl
}
func equalIdentifiers(rec: Record) -> Bool {
return rec.id == self.id
}
// Override me.
func equalPayloads(rec: Record) -> Bool {
return equalIdentifiers(rec) && rec.payload.deleted == self.payload.deleted
}
func equals(rec: Record) -> Bool {
return rec.sortindex == self.sortindex &&
rec.modified == self.modified &&
equalPayloads(rec)
}
}
| mpl-2.0 | bdc724d4f7689507070263e7f6e6d290 | 31.14433 | 130 | 0.624759 | 4.242177 | false | false | false | false |
TeamDeverse/BC-Agora | BC-Agora/DataManager.swift | 1 | 1899 | //
// DataManager.swift
// TopApps
//
// Created by Dani Arnaout on 9/2/14.
// Edited by Eric Cerney on 9/27/14.
// Copyright (c) 2014 Ray Wenderlich All rights reserved.
//
import Foundation
let TopAppURL = "https://itunes.apple.com/us/rss/topgrossingipadapplications/limit=25/json"
class DataManager {
class func getTopAppsDataFromFileWithSuccess(success: ((data: NSData) -> Void)) {
//1
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
//2
let filePath = NSBundle.mainBundle().pathForResource("TopApps",ofType:"json")
var readError:NSError?
if let data = NSData(contentsOfFile:filePath!,
options: NSDataReadingOptions.DataReadingUncached,
error:&readError) {
success(data: data)
}
})
}
class func loadDataFromURL(url: NSURL, completion:(data: NSData?, error: NSError?) -> Void) {
var session = NSURLSession.sharedSession()
// Use NSURLSession to get data from an NSURL
let loadDataTask = session.dataTaskWithURL(url, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if let responseError = error {
completion(data: nil, error: responseError)
} else if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 200 {
var statusError = NSError(domain:"com.raywenderlich", code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code has unexpected value."])
completion(data: nil, error: statusError)
} else {
completion(data: data, error: nil)
}
}
})
loadDataTask.resume()
}
} | mit | 0fba5196aa569dcdb9d5badb7e9a67a6 | 37 | 184 | 0.598736 | 4.783375 | false | false | false | false |
benlangmuir/swift | validation-test/compiler_crashers_2_fixed/0191-sr9508.swift | 28 | 247 | // RUN: %target-swift-frontend -typecheck %s
protocol P {
associatedtype A
}
struct S1: P {
typealias A = Int
}
struct S2<G: P>: P {
typealias A = G.A
}
struct S3<G: P> {
}
extension S3 where G == S2<S1> {
typealias B = G.A
}
| apache-2.0 | 62293a21b57b5419a7c7f6f12d73abea | 11.35 | 44 | 0.582996 | 2.546392 | false | false | false | false |
magnetsystems/max-ios | Tests/Tests/MMUserSpec.swift | 1 | 4897 | /*
* Copyright (c) 2015 Magnet Systems, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import Foundation
import Quick
import Nimble
import MagnetMax
class MMUserSpec : QuickSpec {
override func spec() {
describe("MMUser") {
let user = MMUser()
user.firstName = "Jane"
user.lastName = "Doe"
user.email = "jane.doe_\(NSDate.timeIntervalSinceReferenceDate())@magnet.com"
user.userName = user.email
user.password = "magnet"
it("should be able to register with valid information") {
var createdUser: MMUser?
user.register({ user in
createdUser = user
}) { error in
}
expect(createdUser?.userID).toEventually(beNil(), timeout: 10)
expect(createdUser?.firstName).toEventually(equal(user.firstName), timeout: 10)
expect(createdUser?.lastName).toEventually(equal(user.lastName), timeout: 10)
expect(createdUser?.email).toEventually(equal(user.email), timeout: 10)
}
it("should be able to login with valid information") {
let credential = NSURLCredential(user: user.userName, password: user.password, persistence: .None)
var loggedInUser: MMUser?
MMUser.login(credential, rememberMe: false, success: {
loggedInUser = MMUser.currentUser()
}) { error in
}
expect(loggedInUser?.userID).toEventually(beNil(), timeout: 10)
expect(loggedInUser?.firstName).toEventually(equal(user.firstName), timeout: 10)
expect(loggedInUser?.lastName).toEventually(equal(user.lastName), timeout: 10)
expect(loggedInUser?.email).toEventually(equal(user.email), timeout: 10)
}
it("should be able to logout") {
var loggedInUser: MMUser? = MMUser()
MMUser.logout({ () -> Void in
loggedInUser = MMUser.currentUser()
}) { (error) -> Void in
}
expect(loggedInUser).toEventually(beNil(), timeout: 10)
}
let user2 = MMUser()
user2.firstName = "Jane2"
user2.lastName = "Doe2"
user2.email = "jane2.doe2_\(NSDate.timeIntervalSinceReferenceDate())@magnet.com"
user2.userName = user2.email
user2.password = "magnet"
it("should be able to register second user with valid information") {
var createdUser: MMUser?
user2.register({ user in
createdUser = user
}) { error in
}
expect(createdUser?.userID).toEventually(beNil(), timeout: 10)
expect(createdUser?.firstName).toEventually(equal(user2.firstName), timeout: 10)
expect(createdUser?.lastName).toEventually(equal(user2.lastName), timeout: 10)
expect(createdUser?.email).toEventually(equal(user2.email), timeout: 10)
}
it("should be able to login multiple times") {
let credential = NSURLCredential(user: user.userName, password: user.password, persistence: .None)
let credential2 = NSURLCredential(user: user2.userName, password: user2.password, persistence: .None)
var didFinish : Bool = false
MMUser.login(credential, rememberMe: false, success: {
MMUser.login(credential, rememberMe: true, success: {
MMUser.login(credential, rememberMe: false, success: {
MMUser.login(credential2, rememberMe: false, success: {
didFinish = true
}) { error in
}
}) { error in
}
}) { error in
}
}) { error in
}
expect(didFinish).toEventually(beTrue(), timeout: 15)
}
}
}
}
| apache-2.0 | 125222f70a4d3642ff2fdc0fe56bb0da | 41.582609 | 117 | 0.539514 | 5.193001 | false | false | false | false |
yannickl/QRCodeReader.swift | Sources/ReaderOverlayView.swift | 1 | 3674 | /*
* QRCodeReader.swift
*
* Copyright 2014-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import UIKit
/// The overlay state
public enum QRCodeReaderViewOverlayState {
/// The overlay is in normal state
case normal
/// The overlay is in valid state
case valid
/// The overlay is in wrong state
case wrong
}
/// The overlay protocol
public protocol QRCodeReaderViewOverlay: UIView {
/// Set the state of the overlay
func setState(_ state: QRCodeReaderViewOverlayState)
}
/// Overlay over the camera view to display the area (a square) where to scan the code.
public final class ReaderOverlayView: UIView {
private var overlay: CAShapeLayer = {
var overlay = CAShapeLayer()
overlay.backgroundColor = UIColor.clear.cgColor
overlay.fillColor = UIColor.clear.cgColor
overlay.strokeColor = UIColor.white.cgColor
overlay.lineWidth = 3
overlay.lineDashPattern = [7.0, 7.0]
overlay.lineDashPhase = 0
return overlay
}()
private var state: QRCodeReaderViewOverlayState = .normal {
didSet {
switch state {
case .normal:
overlay.strokeColor = defaultColor.cgColor
case .valid:
overlay.strokeColor = highlightValidColor.cgColor
case .wrong:
overlay.strokeColor = highlightWrongColor.cgColor
}
setNeedsDisplay()
}
}
/// The default overlay color
public var defaultColor: UIColor = .white
/// The overlay color when a valid code has been scanned
public var highlightValidColor: UIColor = .green
/// The overlay color when a wrong code has been scanned
public var highlightWrongColor: UIColor = .red
override init(frame: CGRect) {
super.init(frame: frame)
setupOverlay()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupOverlay()
}
private func setupOverlay() {
state = .normal
layer.addSublayer(overlay)
}
var rectOfInterest: CGRect = CGRect(x: 0, y: 0, width: 1, height: 1) {
didSet {
setNeedsDisplay()
}
}
public override func draw(_ rect: CGRect) {
let innerRect = CGRect(
x: rect.width * rectOfInterest.minX,
y: rect.height * rectOfInterest.minY,
width: rect.width * rectOfInterest.width,
height: rect.height * rectOfInterest.height
)
overlay.path = UIBezierPath(roundedRect: innerRect, cornerRadius: 5).cgPath
}
}
extension ReaderOverlayView: QRCodeReaderViewOverlay {
public func setState(_ state: QRCodeReaderViewOverlayState) {
self.state = state
}
}
| mit | 3d168e4b0ea4219f0a94bcd3bd3df049 | 28.869919 | 87 | 0.704954 | 4.519065 | false | false | false | false |
ReiVerdugo/uikit-fundamentals | Click Counter/Click Counter/AppDelegate.swift | 1 | 4597 | //
// AppDelegate.swift
// Click Counter
//
// Created by devstn5 on 2016-09-28.
// Copyright © 2016 Rverdugo. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Click_Counter")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| mit | 2ef52eab21f0cd7434a8a9880be7e6c3 | 48.419355 | 285 | 0.686031 | 5.832487 | false | false | false | false |
Mioke/PlanB | PlanB/PlanB/Base/KMViewController/UIViewController+TaskManager.swift | 1 | 2241 | //
// UIViewController+TaskManager.swift
// swiftArchitecture
//
// Created by Klein Mioke on 15/11/27.
// Copyright © 2015年 KleinMioke. All rights reserved.
//
import UIKit
extension UIViewController: sender, receiver {
typealias receiveDataType = AnyObject
func doTask(task: () throws -> receiveDataType, identifier: String) {
let block = {
do {
let result = try task()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.finishTaskWithReuslt(result, identifier: identifier)
})
} catch let e {
if let error = e as? ErrorResultType {
self.taskCancelledWithError(error, identifier: identifier)
} else {
Log.debugPrintln("Undefined error")
}
}
}
dispatch_async(dispatch_get_global_queue(0, 0), block)
}
@available(*, deprecated, message="尽量不要使用block回调,保证结构统一性。To make sure the unitarity of callback ,don't use this except neccesary")
func doTask(task: () throws -> receiveDataType, callBack: (receiveDataType) -> Void, failure: (ErrorResultType) -> Void) {
dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
do {
let result = try task()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
callBack(result)
})
} catch let e {
if let error = e as? ErrorResultType {
failure(error)
} else {
Log.debugPrintln("Undefined error")
}
}
}
}
func taskCancelledWithError(error: ErrorResultType, identifier: String) {
NetworkManager.dealError(error)
}
/**
Task's callback. 任务的回调函数
- parameter result: Task execution's result. 任务执行返回的结果
- parameter identifier: Task's identifier. 任务的标识
*/
func finishTaskWithReuslt(result: receiveDataType, identifier: String) {
}
}
| gpl-3.0 | 3e97010d52eb36f83b42cf0ad11fd332 | 30.333333 | 134 | 0.541628 | 4.639485 | false | false | false | false |
rain2540/Swift_100_Examples | CollatzConjecture.playground/Contents.swift | 1 | 1009 | import UIKit
/*:
考拉兹猜想:一个正整数,如果它是奇数,则对它乘3再加1,如果它是偶数,则对它除以2,如此循环,最终都能够得到1
*/
typealias CollatzInfo = (number: Int, step: Int, path: [Int])
func collatzConjecture(_ number: Int) -> CollatzInfo {
guard number > 0 else {
return (number, 0, [])
}
var step = 0
var pathNumbers: [Int] = [number]
var tempNumber = number
while tempNumber != 1 {
if tempNumber % 2 == 0 {
tempNumber /= 2
pathNumbers.append(tempNumber)
} else {
tempNumber = tempNumber * 3 + 1
pathNumbers.append(tempNumber)
}
step += 1
}
let info = (number, step, pathNumbers)
return info
}
print(collatzConjecture(0))
for i in 1 ..< 27 {
let info = collatzConjecture(i)
print(info)
}
let info = collatzConjecture(27)
print(info)
for j in 28 ..< 101 {
let info = collatzConjecture(j)
print(info)
}
| mit | e60e6f4e1cef9f5c9cd35274eb012297 | 18.717391 | 61 | 0.586549 | 3.013289 | false | false | false | false |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/1031-getselftypeforcontainer.swift | 10 | 453 | // RUN: not %target-swift-frontend %s -parse
// REQUIRES: asserts
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol b : C {
}
let start = b, let t.c {
typealias d>(n: b {
protocol C = 0] = """\())] = c: e? = T) -> A {
}
protocol A : a {
}
protocol a {
func e: b {
}
func c(() -> Any) {
}
protocol A {
}
typealias d : e: C {
| apache-2.0 | f1559df9da42ad6f02bb221c4fb61996 | 18.695652 | 87 | 0.620309 | 3 | false | true | false | false |
petester42/Moya | Demo/Tests/RxSwiftMoyaProviderTests.swift | 6 | 3190 | import Quick
import Nimble
import Moya
import RxSwift
import Alamofire
class RxSwiftMoyaProviderSpec: QuickSpec {
override func spec() {
describe("provider with Observable") {
var provider: RxMoyaProvider<GitHub>!
beforeEach {
provider = RxMoyaProvider(stubClosure: MoyaProvider.ImmediatelyStub)
}
it("returns a Response object") {
var called = false
_ = provider.request(.Zen).subscribeNext { (object) -> Void in
called = true
}
expect(called).to(beTruthy())
}
it("returns stubbed data for zen request") {
var message: String?
let target: GitHub = .Zen
_ = provider.request(target).subscribeNext { (response) -> Void in
message = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String
}
let sampleString = NSString(data: (target.sampleData as NSData), encoding: NSUTF8StringEncoding)
expect(message).to(equal(sampleString))
}
it("returns correct data for user profile request") {
var receivedResponse: NSDictionary?
let target: GitHub = .UserProfile("ashfurrow")
_ = provider.request(target).subscribeNext { (response) -> Void in
receivedResponse = try! NSJSONSerialization.JSONObjectWithData(response.data, options: []) as? NSDictionary
}
expect(receivedResponse).toNot(beNil())
}
}
describe("failing") {
var provider: RxMoyaProvider<GitHub>!
beforeEach {
provider = RxMoyaProvider<GitHub>(endpointClosure: failureEndpointClosure, stubClosure: MoyaProvider.ImmediatelyStub)
}
it("returns the correct error message") {
var receivedError: Moya.Error?
waitUntil { done in
_ = provider.request(.Zen).subscribeError { (error) -> Void in
receivedError = error as? Moya.Error
done()
}
}
switch receivedError {
case .Some(.Underlying(let error as NSError)):
expect(error.localizedDescription) == "Houston, we have a problem"
default:
fail("expected an Underlying error that Houston has a problem")
}
}
it("returns an error") {
var errored = false
let target: GitHub = .Zen
_ = provider.request(target).subscribeError { (error) -> Void in
errored = true
}
expect(errored).to(beTruthy())
}
}
}
}
| mit | 1362be3b01f17573ee0c21a5bd0eb732 | 35.25 | 133 | 0.47837 | 6.444444 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/Room/TimelineCells/Styles/Bubble/BubbleRoomCellLayoutUpdater.swift | 1 | 9986 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
@objcMembers
class BubbleRoomCellLayoutUpdater: RoomCellLayoutUpdating {
// MARK: - Properties
private var theme: Theme
private var incomingColor: UIColor {
return self.theme.roomCellIncomingBubbleBackgroundColor
}
private var outgoingColor: UIColor {
return self.theme.roomCellOutgoingBubbleBackgroundColor
}
// MARK: - Setup
init(theme: Theme) {
self.theme = theme
}
// MARK: - Public
func updateLayoutIfNeeded(for cell: MXKRoomBubbleTableViewCell, andCellData cellData: MXKRoomBubbleCellData) {
if cellData.isIncoming {
self.updateLayout(forIncomingTextMessageCell: cell, andCellData: cellData)
} else {
self.updateLayout(forOutgoingTextMessageCell: cell, andCellData: cellData)
}
}
func updateLayout(forIncomingTextMessageCell cell: MXKRoomBubbleTableViewCell, andCellData cellData: MXKRoomBubbleCellData) {
}
func updateLayout(forOutgoingTextMessageCell cell: MXKRoomBubbleTableViewCell, andCellData cellData: MXKRoomBubbleCellData) {
}
func setupLayout(forIncomingTextMessageCell cell: MXKRoomBubbleTableViewCell) {
self.setupIncomingMessageTextViewMargins(for: cell)
cell.setNeedsUpdateConstraints()
}
func setupLayout(forOutgoingTextMessageCell cell: MXKRoomBubbleTableViewCell) {
self.setupOutgoingMessageTextViewMargins(for: cell)
// Hide avatar view
cell.pictureView?.isHidden = true
cell.setNeedsUpdateConstraints()
}
func setupLayout(forOutgoingFileAttachmentCell cell: MXKRoomBubbleTableViewCell) {
// Hide avatar view
cell.pictureView?.isHidden = true
self.setupOutgoingFileAttachViewMargins(for: cell)
}
func setupLayout(forIncomingFileAttachmentCell cell: MXKRoomBubbleTableViewCell) {
self.setupIncomingFileAttachViewMargins(for: cell)
}
func updateLayout(forSelectedStickerCell cell: RoomSelectedStickerBubbleCell) {
if cell.bubbleData.isIncoming {
self.setupLayout(forIncomingFileAttachmentCell: cell)
} else {
self.setupLayout(forOutgoingFileAttachmentCell: cell)
cell.userNameLabel?.isHidden = true
cell.pictureView?.isHidden = true
}
}
func maximumTextViewWidth(for cell: MXKRoomBubbleTableViewCell, cellData: MXKCellData, maximumCellWidth: CGFloat) -> CGFloat {
guard cell.messageTextView != nil else {
return 0
}
let maxTextViewWidth: CGFloat
let textViewleftMargin: CGFloat
let textViewRightMargin: CGFloat
if let roomBubbleCellData = cellData as? RoomBubbleCellData, cell is MXKRoomIncomingTextMsgBubbleCell || cell is MXKRoomOutgoingTextMsgBubbleCell {
if roomBubbleCellData.isIncoming {
let textViewInsets = self.getIncomingMessageTextViewInsets(from: cell)
textViewleftMargin = cell.msgTextViewLeadingConstraint.constant + textViewInsets.left
// Right inset is in fact margin in this case
textViewRightMargin = textViewInsets.right
} else {
let textViewMargins = self.getOutgoingMessageTextViewMargins(from: cell)
textViewleftMargin = textViewMargins.left
textViewRightMargin = textViewMargins.right
}
} else {
textViewleftMargin = cell.msgTextViewLeadingConstraint.constant
textViewRightMargin = cell.msgTextViewTrailingConstraint.constant
}
maxTextViewWidth = maximumCellWidth - (textViewleftMargin + textViewRightMargin)
guard maxTextViewWidth >= 0 else {
return 0
}
guard maxTextViewWidth <= maximumCellWidth else {
return maxTextViewWidth
}
return maxTextViewWidth
}
// MARK: Themable
func update(theme: Theme) {
self.theme = theme
}
// MARK: - Private
// MARK: Text message
private func getIncomingMessageTextViewInsets(from bubbleCell: MXKRoomBubbleTableViewCell) -> UIEdgeInsets {
let messageViewMarginTop: CGFloat = 0
let messageViewMarginBottom: CGFloat = 0
let messageViewMarginLeft: CGFloat = 0
let messageViewMarginRight: CGFloat = BubbleRoomCellLayoutConstants.incomingBubbleBackgroundMargins.right + BubbleRoomCellLayoutConstants.bubbleTextViewInsets.right
let messageViewInsets = UIEdgeInsets(top: messageViewMarginTop, left: messageViewMarginLeft, bottom: messageViewMarginBottom, right: messageViewMarginRight)
return messageViewInsets
}
private func setupIncomingMessageTextViewMargins(for cell: MXKRoomBubbleTableViewCell) {
guard cell.messageTextView != nil else {
return
}
let messageViewInsets = self.getIncomingMessageTextViewInsets(from: cell)
cell.msgTextViewBottomConstraint.constant += messageViewInsets.bottom
cell.msgTextViewTopConstraint.constant += messageViewInsets.top
cell.msgTextViewLeadingConstraint.constant += messageViewInsets.left
// Right inset is in fact margin in this case
cell.msgTextViewTrailingConstraint.constant = messageViewInsets.right
}
private func getOutgoingMessageTextViewMargins(from bubbleCell: MXKRoomBubbleTableViewCell) -> UIEdgeInsets {
let messageViewMarginTop: CGFloat = 0
let messageViewMarginBottom: CGFloat = 0
let messageViewMarginLeft = BubbleRoomCellLayoutConstants.outgoingBubbleBackgroundMargins.left + BubbleRoomCellLayoutConstants.bubbleTextViewInsets.left
let messageViewMarginRight = BubbleRoomCellLayoutConstants.outgoingBubbleBackgroundMargins.right + BubbleRoomCellLayoutConstants.bubbleTextViewInsets.right
let messageViewInsets = UIEdgeInsets(top: messageViewMarginTop, left: messageViewMarginLeft, bottom: messageViewMarginBottom, right: messageViewMarginRight)
return messageViewInsets
}
private func setupOutgoingMessageTextViewMargins(for cell: MXKRoomBubbleTableViewCell) {
guard let messageTextView = cell.messageTextView else {
return
}
let contentView = cell.contentView
let messageViewMargins = self.getOutgoingMessageTextViewMargins(from: cell)
cell.msgTextViewLeadingConstraint.isActive = false
cell.msgTextViewTrailingConstraint.isActive = false
let leftConstraint = messageTextView.leadingAnchor.constraint(greaterThanOrEqualTo: contentView.leadingAnchor, constant: messageViewMargins.left)
let rightConstraint = messageTextView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -messageViewMargins.right)
NSLayoutConstraint.activate([
leftConstraint,
rightConstraint
])
cell.msgTextViewLeadingConstraint = leftConstraint
cell.msgTextViewTrailingConstraint = rightConstraint
cell.msgTextViewBottomConstraint.constant += messageViewMargins.bottom
}
// MARK: File attachment
private func setupOutgoingFileAttachViewMargins(for cell: MXKRoomBubbleTableViewCell) {
guard let attachmentView = cell.attachmentView else {
return
}
let contentView = cell.contentView
let rightMargin = BubbleRoomCellLayoutConstants.outgoingBubbleBackgroundMargins.right
if let attachViewLeadingConstraint = cell.attachViewLeadingConstraint {
attachViewLeadingConstraint.isActive = false
cell.attachViewLeadingConstraint = nil
}
let rightConstraint = attachmentView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -rightMargin)
NSLayoutConstraint.activate([
rightConstraint
])
cell.attachViewTrailingConstraint = rightConstraint
}
private func setupIncomingFileAttachViewMargins(for cell: MXKRoomBubbleTableViewCell) {
guard let attachmentView = cell.attachmentView,
cell.attachViewLeadingConstraint == nil || cell.attachViewLeadingConstraint.isActive == false else {
return
}
if let attachViewTrailingConstraint = cell.attachViewTrailingConstraint {
attachViewTrailingConstraint.isActive = false
cell.attachViewTrailingConstraint = nil
}
let contentView = cell.contentView
let leftMargin: CGFloat = BubbleRoomCellLayoutConstants.incomingBubbleBackgroundMargins.left
let leftConstraint = attachmentView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: leftMargin)
NSLayoutConstraint.activate([
leftConstraint
])
cell.attachViewLeadingConstraint = leftConstraint
}
}
| apache-2.0 | 13b2a3617c6e1f64f9e63922b9693c6c | 35.713235 | 172 | 0.680352 | 5.856891 | false | false | false | false |
evenCoder/VRPhoto | VRPhoto/VRPhoto/VRPhotoLib/MMPhotoViewController.swift | 1 | 1589 | //
// MMPhotoViewController.swift
// VR图片浏览
//
// Created by 黄进文 on 2017/2/25.
// Copyright © 2017年 evenCoder. All rights reserved.
//
import UIKit
class MMPhotoViewController: UIViewController {
fileprivate var photoUrl: String?
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?, urlString: String?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
guard let url = urlString else {
return
}
photoUrl = url
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
let photo = MMPhotoView(frame: view.bounds)
photo.photoURL = photoUrl
view.addSubview(photo)
view.addSubview(closeButton)
}
@objc fileprivate func closeButtonClick() {
dismiss(animated: true, completion: nil)
}
// MARK: - 懒加载
fileprivate lazy var closeButton: UIButton = {
let btn = UIButton()
btn.frame = CGRect(x: 10, y: 20, width: 50, height: 50)
btn.layer.cornerRadius = 25
btn.layer.masksToBounds = true
btn.setImage(UIImage(named: "Images.bundle/" + "close"), for: UIControlState.normal)
btn.addTarget(self, action: #selector(MMPhotoViewController.closeButtonClick), for: UIControlEvents.touchUpInside)
return btn
}()
}
| mit | 37fa0fb627bb4c27af4b312369e401f8 | 20.162162 | 122 | 0.60728 | 4.660714 | false | false | false | false |
xiandan/diaobaoweibo-swift | XWeibo-swift/Classes/Library/PhotoSelector/UIImage+Scale.swift | 1 | 803 | //
// UIImage+Scale.swift
// PhotoSelector
//
// Created by Apple on 15/11/11.
// Copyright © 2015年 Apple. All rights reserved.
//
import UIKit
extension UIImage {
func scaleImage(newWidth: CGFloat = 300) -> UIImage {
//图片的尺寸小于300
if size.width <= newWidth {
return self
}
let newHeight = newWidth * size.height / size.width
let newSize = CGSize(width: newWidth, height: newHeight)
UIGraphicsBeginImageContext(newSize)
drawInRect(CGRect(origin: CGPoint(x: 0, y: 0), size: newSize))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
| apache-2.0 | 390803304d10ece9bd962429f57a3a72 | 18.65 | 70 | 0.566158 | 5.038462 | false | false | false | false |
burningmantech/ranger-ims-mac | IncidentsTests/AddressTests.swift | 1 | 12106 | //
// AddressTests.swift
// Incidents
//
// © 2015 Burning Man and its contributors. All rights reserved.
// See the file COPYRIGHT.md for terms.
//
import XCTest
class AddressDescriptionTests: XCTestCase {
func test_description_full() {
let address = Address(textDescription: "Camp with tents")
XCTAssertEqual(address.description, "Camp with tents")
}
func test_description_nil() {
let address = Address()
XCTAssertEqual(address.description, "")
}
}
class AddressComparisonTests: XCTestCase {
func test_equal() {
XCTAssertEqual(
Address(textDescription: "Ranger Outpost Tokyo"),
Address(textDescription: "Ranger Outpost Tokyo")
)
}
func test_notEqual() {
XCTAssertNotEqual(
Address(textDescription: "Ranger Outpost Berlin"),
Address(textDescription: "Ranger Outpost Tokyo")
)
}
func test_lessThan() {
XCTAssertLessThan(
Address(textDescription: "Ranger Outpost Berlin"),
Address(textDescription: "Ranger Outpost Tokyo")
)
}
func test_notLessThan_greater() {
XCTAssertFalse(
Address(textDescription: "Ranger Outpost Tokyo") <
Address(textDescription: "Ranger Outpost Berlin")
)
}
func test_notLessThan_equal() {
XCTAssertFalse(
Address(textDescription: "Ranger Outpost Tokyo") <
Address(textDescription: "Ranger Outpost Tokyo")
)
}
}
class AddressNillishTests: XCTestCase {
func test_nilAttributes() {
XCTAssertTrue(Address().isNillish())
}
func test_textDescription() {
XCTAssertFalse(
Address(textDescription: "over there").isNillish()
)
}
}
class RodGarettAddressDescriptionTests: XCTestCase {
func test_description_full() {
let address = RodGarettAddress(
concentric : ConcentricStreet.C,
radialHour : 8,
radialMinute : 45,
textDescription : "Red and yellow flags, dome"
)
XCTAssertEqual(
address.description,
"8:45@\(ConcentricStreet.C), Red and yellow flags, dome"
)
}
func test_description_concentric() {
let address = RodGarettAddress(concentric: ConcentricStreet.C)
XCTAssertEqual(address.description, "-:-@\(ConcentricStreet.C)")
}
func test_description_radialHour() {
let address = RodGarettAddress(radialHour: 8)
XCTAssertEqual(address.description, "8:-@-")
}
func test_description_radialMinute() {
let address = RodGarettAddress(radialMinute: 45)
XCTAssertEqual(address.description, "-:45@-")
}
func test_description_textDescription() {
let address = RodGarettAddress(
textDescription : "Red and yellow flags, dome"
)
XCTAssertEqual(
address.description,
"-:-@-, Red and yellow flags, dome"
)
}
}
class RodGarrettAddressComparisonTests: XCTestCase {
func test_equal() {
XCTAssertEqual(
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 8,
radialMinute: 30,
textDescription: "Camp Equilibrium"
),
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 8,
radialMinute: 30,
textDescription: "Camp Equilibrium"
)
)
}
func test_notEqual_concentric() {
XCTAssertNotEqual(
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 8,
radialMinute: 30,
textDescription: "Camp Equilibrium"
),
RodGarettAddress(
concentric: ConcentricStreet.A,
radialHour: 8,
radialMinute: 30,
textDescription: "Camp Equilibrium"
)
)
}
func test_notEqual_hour() {
XCTAssertNotEqual(
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 8,
radialMinute: 30,
textDescription: "Camp Equilibrium"
),
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 3,
radialMinute: 30,
textDescription: "Camp Equilibrium"
)
)
}
func test_notEqual_minute() {
XCTAssertNotEqual(
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 8,
radialMinute: 30,
textDescription: "Camp Equilibrium"
),
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 8,
radialMinute: 00,
textDescription: "Camp Equilibrium"
)
)
}
func test_notEqual_description() {
XCTAssertNotEqual(
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 8,
radialMinute: 30,
textDescription: "Camp Equilibrium"
),
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 8,
radialMinute: 30,
textDescription: "Camp Shazbot"
)
)
}
func test_lessThan_concentric() {
XCTAssertLessThan(
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 8,
radialMinute: 30,
textDescription: "Camp Equilibrium"
),
RodGarettAddress(
concentric: ConcentricStreet.D,
radialHour: 8,
radialMinute: 30,
textDescription: "Camp Equilibrium"
)
)
}
func test_lessThan_hour() {
XCTAssertLessThan(
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 8,
radialMinute: 30,
textDescription: "Camp Equilibrium"
),
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 9,
radialMinute: 30,
textDescription: "Camp Equilibrium"
)
)
}
func test_lessThan_minute() {
XCTAssertLessThan(
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 8,
radialMinute: 30,
textDescription: "Camp Equilibrium"
),
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 8,
radialMinute: 45,
textDescription: "Camp Equilibrium"
)
)
}
func test_lessThan_description() {
XCTAssertLessThan(
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 8,
radialMinute: 30,
textDescription: "Camp Equilibrium"
),
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 8,
radialMinute: 30,
textDescription: "Camp Shazbot"
)
)
}
func test_notLessThan_greater_concentric() {
XCTAssertFalse(
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 8,
radialMinute: 30,
textDescription: "Camp Equilibrium"
) <
RodGarettAddress(
concentric: ConcentricStreet.A,
radialHour: 8,
radialMinute: 30,
textDescription: "Camp Equilibrium"
)
)
}
func test_notLessThan_greater_hour() {
XCTAssertFalse(
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 8,
radialMinute: 30,
textDescription: "Camp Equilibrium"
) <
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 2,
radialMinute: 30,
textDescription: "Camp Equilibrium"
)
)
}
func test_notLessThan_greater_minute() {
XCTAssertFalse(
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 8,
radialMinute: 30,
textDescription: "Camp Equilibrium"
) <
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 8,
radialMinute: 00,
textDescription: "Camp Equilibrium"
)
)
}
func test_notLessThan_greater_description() {
XCTAssertFalse(
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 8,
radialMinute: 30,
textDescription: "Camp Equilibrium"
) <
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 8,
radialMinute: 30,
textDescription: "Camp Awesome"
)
)
}
func test_notLessThan_equal() {
XCTAssertFalse(
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 8,
radialMinute: 30,
textDescription: "Camp Equilibrium"
) <
RodGarettAddress(
concentric: ConcentricStreet.C,
radialHour: 8,
radialMinute: 30,
textDescription: "Camp Equilibrium"
)
)
}
}
class RodGarettAddressNillishTests: XCTestCase {
func test_nilAttributes() {
XCTAssertTrue(RodGarettAddress().isNillish())
}
func test_concentric() {
XCTAssertFalse(
RodGarettAddress(concentric: ConcentricStreet.A).isNillish()
)
}
func test_radialHour() {
XCTAssertFalse(
RodGarettAddress(radialHour: 8).isNillish()
)
}
func test_radialMinute() {
XCTAssertFalse(
RodGarettAddress(radialMinute: 45).isNillish()
)
}
func test_textDescription() {
XCTAssertFalse(
RodGarettAddress(textDescription: "over there").isNillish()
)
}
}
class ConcentricStreetNameTests: XCTestCase {
func test_name() {
XCTAssertEqual(ConcentricStreet.Esplanade.description, "Esplanade")
XCTAssertTrue(ConcentricStreet.A.description.hasPrefix("A"))
XCTAssertTrue(ConcentricStreet.B.description.hasPrefix("B"))
XCTAssertTrue(ConcentricStreet.C.description.hasPrefix("C"))
XCTAssertTrue(ConcentricStreet.D.description.hasPrefix("D"))
XCTAssertTrue(ConcentricStreet.E.description.hasPrefix("E"))
XCTAssertTrue(ConcentricStreet.F.description.hasPrefix("F"))
XCTAssertTrue(ConcentricStreet.G.description.hasPrefix("G"))
XCTAssertTrue(ConcentricStreet.H.description.hasPrefix("H"))
XCTAssertTrue(ConcentricStreet.I.description.hasPrefix("I"))
XCTAssertTrue(ConcentricStreet.J.description.hasPrefix("J"))
XCTAssertTrue(ConcentricStreet.K.description.hasPrefix("K"))
XCTAssertTrue(ConcentricStreet.L.description.hasPrefix("L"))
XCTAssertTrue(ConcentricStreet.M.description.hasPrefix("M"))
XCTAssertTrue(ConcentricStreet.N.description.hasPrefix("N"))
}
}
| apache-2.0 | 81baf1cffff044b358e0dbf3905513cb | 25.144708 | 75 | 0.532838 | 4.659353 | false | true | false | false |
visenze/visearch-sdk-swift | ViSearchSDK/ViSearchSDK/Classes/ViSearch.swift | 1 | 5226 | import Foundation
import ViSenzeAnalytics
/// wrapper for various API calls
/// create shared client
open class ViSearch: NSObject {
public static let sharedInstance = ViSearch()
public var client : ViSearchClient?
private override init(){
super.init()
}
/// Check if search client is setup properly
///
/// - returns: true if client is setup
public func isClientSetup() -> Bool {
return client != nil
}
// MARK: setup
/// Setup API client. Must be called first before various API calls
///
/// - parameter accessKey: application access key
/// - parameter secret: application secret key
public func setup(accessKey: String, secret: String) -> Void {
if client == nil {
client = ViSearchClient(accessKey: accessKey, secret: secret)
}
client?.accessKey = accessKey
client?.secret = secret
client?.isAppKeyEnabled = false
}
/// Setup API client. Must be called first before various API calls
///
/// - parameter appKey: application app key
public func setup(appKey: String) -> Void {
if client == nil {
client = ViSearchClient(appKey: appKey)
}
client?.accessKey = appKey
client?.isAppKeyEnabled = true
}
// MARK: Analytics
public func newTracker(code: String) -> ViSenzeTracker {
return ViSenzeTracker(code: code, isCn: false)!
}
public func newTracker(code: String, forCn: Bool) -> ViSenzeTracker {
return ViSenzeTracker(code: code, isCn: forCn)!
}
// MARK: API calls
/// Search by Image API
@discardableResult public func uploadSearch(params: ViUploadSearchParams,
successHandler: @escaping ViSearchClient.SuccessHandler,
failureHandler: @escaping ViSearchClient.FailureHandler) -> URLSessionTask?
{
if let client = client {
return client.uploadSearch(params: params, successHandler: successHandler, failureHandler: failureHandler);
}
print("\(type(of: self)).\(#function)[line:\(#line)] - error: client is not initialized. Please call setup(accessKey, secret) before using the API.")
return nil
}
/// Discover Search API
@discardableResult public func discoverSearch(params: ViUploadSearchParams,
successHandler: @escaping ViSearchClient.SuccessHandler,
failureHandler: @escaping ViSearchClient.FailureHandler) -> URLSessionTask?
{
if let client = client {
return client.discoverSearch(params: params, successHandler: successHandler, failureHandler: failureHandler);
}
print("\(type(of: self)).\(#function)[line:\(#line)] - error: client is not initialized. Please call setup(accessKey, secret) before using the API.")
return nil
}
/// Search by Color API
@discardableResult public func colorSearch(params: ViColorSearchParams,
successHandler: @escaping ViSearchClient.SuccessHandler,
failureHandler: @escaping ViSearchClient.FailureHandler
) -> URLSessionTask?
{
if let client = client {
return client.colorSearch(params: params, successHandler: successHandler, failureHandler: failureHandler)
}
print("\(type(of: self)).\(#function)[line:\(#line)] - error: client is not initialized. Please call setup(accessKey, secret) before using the API.")
return nil
}
/// Find Similar API
@discardableResult public func findSimilar(params: ViSearchParams,
successHandler: @escaping ViSearchClient.SuccessHandler,
failureHandler: @escaping ViSearchClient.FailureHandler
) -> URLSessionTask?
{
if let client = client {
return client.findSimilar(params: params, successHandler: successHandler, failureHandler: failureHandler)
}
print("\(type(of: self)).\(#function)[line:\(#line)] - error: client is not initialized. Please call setup(accessKey, secret) before using the API.")
return nil
}
/// You may also like API
@discardableResult public func recommendation(params: ViRecParams,
successHandler: @escaping ViSearchClient.SuccessHandler,
failureHandler: @escaping ViSearchClient.FailureHandler
) -> URLSessionTask?
{
if let client = client {
return client.recommendation(params: params, successHandler: successHandler, failureHandler: failureHandler)
}
print("\(type(of: self)).\(#function)[line:\(#line)] - error: client is not initialized. Please call setup(accessKey, secret) before using the API.")
return nil
}
}
| mit | e960a418795af3f3f0919d814a5fc668 | 37.145985 | 157 | 0.591083 | 5.793792 | false | false | false | false |
Pstoppani/swipe | network/SwipeConnection.swift | 2 | 3983 | //
// SwipeConnection.swift
// sample
//
// Created by satoshi on 10/9/15.
// Copyright © 2015 Satoshi Nakajima. All rights reserved.
//
#if os(OSX)
import Cocoa
#else
import UIKit
#endif
import CoreData
private func MyLog(_ text:String, level:Int = 0) {
let s_verbosLevel = 0
if level <= s_verbosLevel {
NSLog(text)
}
}
class SwipeConnection: NSObject {
private static var connections = [URL:SwipeConnection]()
static let session:URLSession = {
let config = URLSessionConfiguration.default
config.urlCache = nil // disable cache by URLSession (because we do)
return URLSession(configuration: config, delegate: nil, delegateQueue: OperationQueue.main)
}()
static func connection(_ url:URL, urlLocal:URL, entity:NSManagedObject) -> SwipeConnection {
if let connection = connections[url] {
return connection
}
let connection = SwipeConnection(url: url, urlLocal: urlLocal, entity:entity)
//connection.start()
let session = SwipeConnection.session
let start = Date()
let task = session.downloadTask(with: url) { (urlTemp:URL?, res:URLResponse?, error:Swift.Error?) -> Void in
assert(Thread.current == Thread.main, "thread error")
let duration = Date().timeIntervalSince(start)
if let urlT = urlTemp {
if let httpRes = res as? HTTPURLResponse {
if httpRes.statusCode == 200 {
let fm = FileManager.default
do {
let attr = try fm.attributesOfItem(atPath: urlT.path)
if let size = attr[FileAttributeKey.size] as? Int {
connection.fileSize = size
SwipeAssetManager.sharedInstance().wasFileLoaded(connection)
}
} catch {
MyLog("SWConn failed to get attributes (but ignored)")
}
MyLog("SWConn loaded \(url.lastPathComponent) in \(duration)s (\(connection.fileSize))", level:1)
do {
if fm.fileExists(atPath: urlLocal.path) {
try fm.removeItem(at: urlLocal)
}
try fm.copyItem(at: urlT, to: urlLocal)
} catch {
connection.callbackAll(error as NSError)
return
}
} else {
MyLog("SWConn HTTP error (\(url.lastPathComponent), \(httpRes.statusCode))")
connection.callbackAll(NSError(domain: NSURLErrorDomain, code: httpRes.statusCode, userInfo: nil))
return
}
} else {
MyLog("SWConn no HTTPURLResponse, something is wrong!")
}
} else {
MyLog("SWConn network error (\(url.lastPathComponent), \(error))")
}
connection.callbackAll(error as NSError?)
}
task.resume()
return connection
}
let url, urlLocal:URL
let entity:NSManagedObject
var callbacks = Array<(NSError!) -> Void>()
var fileSize = 0
private init(url:URL, urlLocal:URL, entity:NSManagedObject) {
self.url = url
self.urlLocal = urlLocal
self.entity = entity
super.init()
SwipeConnection.connections[url] = self
}
deinit {
//MyLog("SWCon deinit \(url.lastPathComponent)")
}
func load(_ callback:@escaping (NSError!) -> Void) {
callbacks.append(callback)
}
func callbackAll(_ error: NSError?) {
SwipeConnection.connections.removeValue(forKey: self.url)
for callback in callbacks {
callback(error)
}
}
}
| mit | 238958f0df63e31d4987267722daf2b7 | 35.87037 | 122 | 0.534907 | 5.072611 | false | false | false | false |
kuangniaokuang/Cocktail-Pro | smartmixer/smartmixer/Common/WebView.swift | 1 | 2550 | //
// PhoneWeb.swift
// smartmixer
//
// Created by 姚俊光 on 14/10/1.
// Copyright (c) 2014年 smarthito. All rights reserved.
//
import UIKit
class WebView: UIViewController,UIWebViewDelegate{
//网页的控件
@IBOutlet var webPage:UIWebView!
//显示的标题
@IBOutlet var webTitle:UINavigationItem!
@IBOutlet var tipLable:UILabel!
//显示的标题
var WebTitle:String!="Smart Hito"
//需要显示的网页链接
var WebUrl:String!
var showToolbar:Bool = false
override func viewDidLoad() {
super.viewDidLoad()
var right = UIBarButtonItem(image: UIImage(named: "refresh"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("refresh:"))
self.navigationItem.rightBarButtonItem = right
if(osVersion<8){//新版
webPage.frame = CGRect(x: 0, y: -64, width: self.view.frame.width, height: self.view.frame.height-64)
self.view.layoutIfNeeded()
}
self.navigationController?.setNavigationBarHidden(false, animated: true)
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.navigationController?.navigationItem.backBarButtonItem?.title = ""
webTitle.title = WebTitle
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
var request = NSURLRequest(URL: NSURL(string: WebUrl)!)
webPage.loadRequest(request)
}
//返回一个初始化
class func WebViewInit()-> WebView {
var extende = ""
if(osVersion<8){
extende = "7"
}
var webView = UIStoryboard(name: "Common"+deviceDefine, bundle: nil).instantiateViewControllerWithIdentifier("webView"+extende) as WebView
return webView
}
/**
刷新页面
:param: sender <#sender description#>
*/
func refresh(sender:UINavigationItem){
webPage.reload()
}
//网页加载中
func webViewDidStartLoad(webView: UIWebView) {
tipLable.hidden=false
}
//网页加载完毕
func webViewDidFinishLoad(webView: UIWebView) {
tipLable.hidden=true
}
//返回
@IBAction func goback(sender:UINavigationItem){
self.navigationController?.popViewControllerAnimated(true)
if(showToolbar){
rootController.showOrhideToolbar(true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| apache-2.0 | 527c89ee31267924d5102b74c1981809 | 26.133333 | 148 | 0.635545 | 4.678161 | false | false | false | false |
hemangshah/printer | PrinterExampleApp/PrinterExampleApp/ViewController.swift | 1 | 3530 | //
// ViewController.swift
// PrinterExampleApp
//
// Created by Hemang Shah on 4/27/17.
// Copyright © 2017 Hemang Shah. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
/*
Printer – A fancy way to print logs.
You can print following types of logs with Printer.
- Success
- Error
- Warning
- Information
- Alert
With each of the type, it will print a particular emoji and titles which will help you to
easily identify what's exactly the log is. Moreover, it will looks cool too.
Let's check what you can do with Printer.
It's advice you to read the README file to avail most of the features of Printer.
*/
//Printer.log.plainLog = true
//To get a call back before a log prints. This completion blocks will ignore all the filters.
Printer.log.onLogCompletion = { (printLog, fileName, functionName, lineNumber) in
print(printLog, fileName, functionName, lineNumber)
}
//To Skip a file from logging.
Printer.log.skipFile()
//Manual Tracing
Printer.log.trace()
//To Add a file for logging.
Printer.log.addFile()
//To keep track of all the logs. You can always print all the logs by calling 'all()'.
Printer.log.keepTracking = true
//Printer.log.keepAutoTracing = false //Default: true
Printer.log.show(id: "001", details: "This is a Success message.", logType: .success)
Printer.log.show(id: "002", details: "This is a Error message.", logType: .error)
Printer.log.show(id: "003", details: "This is an Information message.", logType: .information)
Printer.log.show(id: "004", details: "This is a Warning message.", logType: .warning)
Printer.log.show(id: "005", details: "This is an Alert message.", logType: .alert)
Printer.log.show(details: "This is another Success message without ID", logType: .success)
//Printing of a Success message without providing a log type.
//With ID
Printer.log.success(id: "001", details: "This is another Success message.")
//Without ID
Printer.log.success(details: "This is a Success message.")
//Printer.log.all(showTrace: true)
//Printer.log.all(filterLogTypes: [.success], showTrace: true)
//let array = Printer.log.getAllLogs()
let array = Printer.log.getAllLogs(filterLogTypes: [.success])
if !array.isEmpty {
array.forEach({ (log) in
//print(log.details)
//or do something with logs.
})
}
Printer.log.saveLogsToFile(logs: array)
//Printer.log.deleteLogFiles()
//Printer.log.flush()
}
@IBAction func actionOpenPrinterView(_ sender: Any) {
let printerStoryboard = UIStoryboard.init(name: "Printer", bundle: Bundle.main)
let navcontroller = UINavigationController.init(rootViewController: (printerStoryboard.instantiateViewController(withIdentifier: "PrinterViewControllerID")))
self.present(navcontroller, animated: true, completion: nil)
}
}
| mit | 3627006149d2b3967a3d2d9adaafc15b | 36.126316 | 165 | 0.605614 | 4.574578 | false | false | false | false |
crazypoo/PTools | PooToolsSource/CheckDirtyWord/PTCheckFWords.swift | 1 | 4728 | //
// PTCheckFWords.swift
// PooTools_Example
//
// Created by jax on 2022/9/28.
// Copyright © 2022 crazypoo. All rights reserved.
//
import UIKit
import Foundation
import SwifterSwift
let EXIST = "isExists"
@objcMembers
public class PTCheckFWords: NSObject {
public static let share = PTCheckFWords()
fileprivate var root:NSMutableDictionary = NSMutableDictionary()
public var isFilterClose:Bool = false
public override init() {
super.init()
self.initFilter()
}
func initFilter()
{
let bundlePath = Bundle.init(path: PTUtils.cgBaseBundle().path(forResource: "PooTools", ofType: "bundle")!)
let filePath = bundlePath?.path(forResource: "minganci", ofType: "txt")
var dataFile:NSString?
do{
dataFile = try NSString(contentsOfFile: filePath!, encoding: String.Encoding.utf8.rawValue)
let dataArr = dataFile?.components(separatedBy: "|")
for item in dataArr!
{
if item.count > 0
{
self.insertWords(words: item as NSString)
}
}
}
catch
{
}
}
func insertWords(words:NSString)
{
var node:NSMutableDictionary = self.root
for i in stride(from: 0, to: words.length, by: 1)
{
let word = words.substring(with: NSRange(location: i, length: 1))
if node.object(forKey: word) == nil
{
let dict = NSMutableDictionary()
node.setObject(dict, forKey: word as NSCopying)
}
node = node.object(forKey: word) as! NSMutableDictionary
}
node.setObject(NSNumber(integerLiteral: 1), forKey: EXIST as NSCopying)
}
public func haveFWord(str:NSString)->Bool
{
for i in stride(from: 0, to: str.length, by: 1)
{
let subString:NSString = str.substring(from: i) as NSString
var node:NSMutableDictionary = self.root.mutableCopy() as! NSMutableDictionary
var num = 0
for j in stride(from: 0, to: subString.length, by: 1)
{
let word = subString.substring(with: NSRange(location: j, length: 1))
if node.object(forKey: word) == nil
{
break
}
else
{
num += 1
node = node.object(forKey: word) as! NSMutableDictionary
}
if node.object(forKey: EXIST) != nil
{
let nodeObj:NSNumber = node.object(forKey: EXIST) as! NSNumber
if nodeObj.intValue == 1
{
return true
}
}
}
}
return false
}
public func filter(str:NSString)->NSString
{
if self.isFilterClose || self.root.count == 0
{
return str
}
let result:NSMutableString = str.mutableCopy() as! NSMutableString
for var i in stride(from: 0, to: str.length, by: 1)
{
let subString:NSString = str.substring(from: i) as NSString
var node:NSMutableDictionary = self.root.mutableCopy() as! NSMutableDictionary
var num = 0
for j in stride(from: 0, to: subString.length, by: 1)
{
let word = subString.substring(with: NSRange(location: j, length: 1))
if node.object(forKey: word) == nil
{
break
}
else
{
num += 1
node = node.object(forKey: word) as! NSMutableDictionary
}
if node.object(forKey: EXIST) != nil
{
let nodeObj:NSNumber = node.object(forKey: EXIST) as! NSNumber
if nodeObj.intValue == 1
{
let symbolStr:NSMutableString = NSMutableString()
for _ in stride(from: 0, to: num, by: 1)
{
symbolStr.append("*")
}
result.replaceCharacters(in: NSRange(location: i, length: num), with: symbolStr as String)
i += j
break
}
}
}
}
return result
}
func freeFilter()
{
self.root.removeAllObjects()
}
}
| mit | 3f5dda0a672af8b7a0a74ba54ebdd12f | 30.513333 | 115 | 0.480855 | 4.949738 | false | false | false | false |
SwiftGit2/SwiftGit2 | SwiftGit2/Pointers.swift | 1 | 1919 | //
// Pointers.swift
// SwiftGit2
//
// Created by Matt Diephouse on 12/23/14.
// Copyright (c) 2014 GitHub, Inc. All rights reserved.
//
import Clibgit2
/// A pointer to a git object.
public protocol PointerType: Hashable {
/// The OID of the referenced object.
var oid: OID { get }
/// The libgit2 `git_object_t` of the referenced object.
var type: git_object_t { get }
}
public extension PointerType {
static func == (lhs: Self, rhs: Self) -> Bool {
return lhs.oid == rhs.oid
&& lhs.type == rhs.type
}
func hash(into hasher: inout Hasher) {
hasher.combine(oid)
}
}
/// A pointer to a git object.
public enum Pointer: PointerType {
case commit(OID)
case tree(OID)
case blob(OID)
case tag(OID)
public var oid: OID {
switch self {
case let .commit(oid):
return oid
case let .tree(oid):
return oid
case let .blob(oid):
return oid
case let .tag(oid):
return oid
}
}
public var type: git_object_t {
switch self {
case .commit:
return GIT_OBJECT_COMMIT
case .tree:
return GIT_OBJECT_TREE
case .blob:
return GIT_OBJECT_BLOB
case .tag:
return GIT_OBJECT_TAG
}
}
/// Create an instance with an OID and a libgit2 `git_object_t`.
init?(oid: OID, type: git_object_t) {
switch type {
case GIT_OBJECT_COMMIT:
self = .commit(oid)
case GIT_OBJECT_TREE:
self = .tree(oid)
case GIT_OBJECT_BLOB:
self = .blob(oid)
case GIT_OBJECT_TAG:
self = .tag(oid)
default:
return nil
}
}
}
extension Pointer: CustomStringConvertible {
public var description: String {
switch self {
case .commit:
return "commit(\(oid))"
case .tree:
return "tree(\(oid))"
case .blob:
return "blob(\(oid))"
case .tag:
return "tag(\(oid))"
}
}
}
public struct PointerTo<T: ObjectType>: PointerType {
public let oid: OID
public var type: git_object_t {
return T.type
}
public init(_ oid: OID) {
self.oid = oid
}
}
| mit | 06c95292fdd74a8a1093415f81490f87 | 17.103774 | 65 | 0.642522 | 2.872754 | false | false | false | false |
wuzhenli/MyDailyTestDemo | swiftTest/swifter-tips+swift+3.0/Swifter.playground/Pages/reflect.xcplaygroundpage/Contents.swift | 2 | 1164 |
import Foundation
struct Person {
let name: String
let age: Int
}
let xiaoMing = Person(name: "XiaoMing", age: 16)
let r = Mirror(reflecting: xiaoMing) // r 是 MirrorType
print("xiaoMing 是 \(r.displayStyle!)")
print("属性个数:\(r.children.count)")
for child in r.children {
print("属性名:\(child.label),值:\(child.value)")
}
//for i in r.children.startIndex..<r.children.endIndex {
// print("属性名:\(r.children[i].0!),值:\(r.children[i].1)")
//}
// 输出:
// xiaoMing 是 Struct
// 属性个数:2
// 属性名:name,值:XiaoMing
// 属性名:age,值:16
dump(xiaoMing)
// 输出:
// ▿ Person
// - name: XiaoMing
// - age: 16
func valueFrom(_ object: Any, key: String) -> Any? {
let mirror = Mirror(reflecting: object)
for child in mirror.children {
let (targetKey, targetMirror) = (child.label, child.value)
if key == targetKey {
return targetMirror
}
}
return nil
}
// 接上面的 xiaoMing
if let name = valueFrom(xiaoMing, key: "name") as? String {
print("通过 key 得到值: \(name)")
}
// 输出:
// 通过 key 得到值: XiaoMing
| apache-2.0 | ed421dbae9d66ec202e8bb2383aadd4c | 18.163636 | 66 | 0.608159 | 3.011429 | false | false | false | false |
luosheng/OpenSim | OpenSim/FileInfo.swift | 1 | 2759 | //
// FileInfo.swift
// Markdown
//
// Created by Luo Sheng on 15/11/1.
// Copyright © 2015年 Pop Tap. All rights reserved.
//
import Foundation
struct FileInfo {
static let prefetchedProperties: [URLResourceKey] = [
.nameKey,
.isDirectoryKey,
.creationDateKey,
.contentModificationDateKey,
.fileSizeKey,
]
private enum FileInfoError: Error {
case invalidProperty
}
let name: String
let isDirectory: Bool
let creationDate: Date
let modificationDate: Date
let fileSize: Int
init?(URL: Foundation.URL) {
var nameObj: AnyObject?
try? (URL as NSURL).getResourceValue(&nameObj, forKey: URLResourceKey.nameKey)
var isDirectoryObj: AnyObject?
try? (URL as NSURL).getResourceValue(&isDirectoryObj, forKey: URLResourceKey.isDirectoryKey)
var creationDateObj: AnyObject?
try? (URL as NSURL).getResourceValue(&creationDateObj, forKey: URLResourceKey.creationDateKey)
var modificationDateObj: AnyObject?
try? (URL as NSURL).getResourceValue(&modificationDateObj, forKey: URLResourceKey.contentModificationDateKey)
var fileSizeObj: AnyObject?
try? (URL as NSURL).getResourceValue(&fileSizeObj, forKey: URLResourceKey.fileSizeKey)
guard let name = nameObj as? String,
let isDirectory = isDirectoryObj as? Bool,
let creationDate = creationDateObj as? Date,
let modificationDate = modificationDateObj as? Date,
let fileSize = isDirectory ? 0 : fileSizeObj as? Int else {
return nil
}
self.name = name
self.isDirectory = isDirectory
self.creationDate = creationDate
self.modificationDate = modificationDate
self.fileSize = fileSize
}
}
extension FileInfo: Equatable {}
func ==(lhs: FileInfo, rhs: FileInfo) -> Bool {
return lhs.name == rhs.name &&
lhs.isDirectory == rhs.isDirectory &&
lhs.creationDate == rhs.creationDate &&
lhs.modificationDate == rhs.modificationDate &&
lhs.fileSize == rhs.fileSize
}
func ==(lhs: FileInfo?, rhs: FileInfo?) -> Bool {
switch (lhs, rhs) {
case (.some(let lhs), .some(let rhs)):
return lhs == rhs
case (nil, nil):
// When two optionals are both nil, we consider them not equal
return false
default:
return false
}
}
func !=(lhs: FileInfo?, rhs: FileInfo?) -> Bool {
return !(lhs == rhs)
}
func ==(lhs: [FileInfo?], rhs: [FileInfo?]) -> Bool {
return lhs.elementsEqual(rhs) { $0 == $1 }
}
func !=(lhs: [FileInfo?], rhs: [FileInfo?]) -> Bool {
return !(lhs == rhs)
}
| mit | ca4cd3a7cf27e72d8f0addbe7fa3b57b | 28.010526 | 117 | 0.619739 | 4.593333 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.